Search Results

Search found 370 results on 15 pages for 'csharp'.

Page 2/15 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • An Xml Serializable PropertyBag Dictionary Class for .NET

    - by Rick Strahl
    I don't know about you but I frequently need property bags in my applications to store and possibly cache arbitrary data. Dictionary<T,V> works well for this although I always seem to be hunting for a more specific generic type that provides a string key based dictionary. There's string dictionary, but it only works with strings. There's Hashset<T> but it uses the actual values as keys. In most key value pair situations for me string is key value to work off. Dictionary<T,V> works well enough, but there are some issues with serialization of dictionaries in .NET. The .NET framework doesn't do well serializing IDictionary objects out of the box. The XmlSerializer doesn't support serialization of IDictionary via it's default serialization, and while the DataContractSerializer does support IDictionary serialization it produces some pretty atrocious XML. What doesn't work? First off Dictionary serialization with the Xml Serializer doesn't work so the following fails: [TestMethod] public void DictionaryXmlSerializerTest() { var bag = new Dictionary<string, object>(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42, 45, 66 }); TestContext.WriteLine(this.ToXml(bag)); } public string ToXml(object obj) { if (obj == null) return null; StringWriter sw = new StringWriter(); XmlSerializer ser = new XmlSerializer(obj.GetType()); ser.Serialize(sw, obj); return sw.ToString(); } The error you get with this is: System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary. Got it! BTW, the same is true with binary serialization. Running the same code above against the DataContractSerializer does work: [TestMethod] public void DictionaryDataContextSerializerTest() { var bag = new Dictionary<string, object>(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42, 45, 66 }); TestContext.WriteLine(this.ToXmlDcs(bag)); } public string ToXmlDcs(object value, bool throwExceptions = false) { var ser = new DataContractSerializer(value.GetType(), null, int.MaxValue, true, false, null); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, value); return Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length); } This DOES work but produces some pretty heinous XML (formatted with line breaks and indentation here): <ArrayOfKeyValueOfstringanyType xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <KeyValueOfstringanyType> <Key>key</Key> <Value i:type="a:string" xmlns:a="http://www.w3.org/2001/XMLSchema">Value</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key2</Key> <Value i:type="a:decimal" xmlns:a="http://www.w3.org/2001/XMLSchema">100.10</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key3</Key> <Value i:type="a:guid" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/">2cd46d2a-a636-4af4-979b-e834d39b6d37</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key4</Key> <Value i:type="a:dateTime" xmlns:a="http://www.w3.org/2001/XMLSchema">2011-09-19T17:17:05.4406999-07:00</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key5</Key> <Value i:type="a:boolean" xmlns:a="http://www.w3.org/2001/XMLSchema">true</Value> </KeyValueOfstringanyType> <KeyValueOfstringanyType> <Key>Key7</Key> <Value i:type="a:base64Binary" xmlns:a="http://www.w3.org/2001/XMLSchema">Ki1C</Value> </KeyValueOfstringanyType> </ArrayOfKeyValueOfstringanyType> Ouch! That seriously hurts the eye! :-) Worse though it's extremely verbose with all those repetitive namespace declarations. It's good to know that it works in a pinch, but for a human readable/editable solution or something lightweight to store in a database it's not quite ideal. Why should I care? As a little background, in one of my applications I have a need for a flexible property bag that is used on a free form database field on an otherwise static entity. Basically what I have is a standard database record to which arbitrary properties can be added in an XML based string field. I intend to expose those arbitrary properties as a collection from field data stored in XML. The concept is pretty simple: When loading write the data to the collection, when the data is saved serialize the data into an XML string and store it into the database. When reading the data pick up the XML and if the collection on the entity is accessed automatically deserialize the XML into the Dictionary. (I'll talk more about this in another post). While the DataContext Serializer would work, it's verbosity is problematic both for size of the generated XML strings and the fact that users can manually edit this XML based property data in an advanced mode. A clean(er) layout certainly would be preferable and more user friendly. Custom XMLSerialization with a PropertyBag Class So… after a bunch of experimentation with different serialization formats I decided to create a custom PropertyBag class that provides for a serializable Dictionary. It's basically a custom Dictionary<TType,TValue> implementation with the keys always set as string keys. The result are PropertyBag<TValue> and PropertyBag (which defaults to the object type for values). The PropertyBag<TType> and PropertyBag classes provide these features: Subclassed from Dictionary<T,V> Implements IXmlSerializable with a cleanish XML format ToXml() and FromXml() methods to export and import to and from XML strings Static CreateFromXml() method to create an instance It's simple enough as it's merely a Dictionary<string,object> subclass but that supports serialization to a - what I think at least - cleaner XML format. The class is super simple to use: [TestMethod] public void PropertyBagTwoWayObjectSerializationTest() { var bag = new PropertyBag(); bag.Add("key", "Value"); bag.Add("Key2", 100.10M); bag.Add("Key3", Guid.NewGuid()); bag.Add("Key4", DateTime.Now); bag.Add("Key5", true); bag.Add("Key7", new byte[3] { 42,45,66 } ); bag.Add("Key8", null); bag.Add("Key9", new ComplexObject() { Name = "Rick", Entered = DateTime.Now, Count = 10 }); string xml = bag.ToXml(); TestContext.WriteLine(bag.ToXml()); bag.Clear(); bag.FromXml(xml); Assert.IsTrue(bag["key"] as string == "Value"); Assert.IsInstanceOfType( bag["Key3"], typeof(Guid)); Assert.IsNull(bag["Key8"]); //Assert.IsNull(bag["Key10"]); Assert.IsInstanceOfType(bag["Key9"], typeof(ComplexObject)); } This uses the PropertyBag class which uses a PropertyBag<string,object> - which means it returns untyped values of type object. I suspect for me this will be the most common scenario as I'd want to store arbitrary values in the PropertyBag rather than one specific type. The same code with a strongly typed PropertyBag<decimal> looks like this: [TestMethod] public void PropertyBagTwoWayValueTypeSerializationTest() { var bag = new PropertyBag<decimal>(); bag.Add("key", 10M); bag.Add("Key1", 100.10M); bag.Add("Key2", 200.10M); bag.Add("Key3", 300.10M); string xml = bag.ToXml(); TestContext.WriteLine(bag.ToXml()); bag.Clear(); bag.FromXml(xml); Assert.IsTrue(bag.Get("Key1") == 100.10M); Assert.IsTrue(bag.Get("Key3") == 300.10M); } and produces typed results of type decimal. The types can be either value or reference types the combination of which actually proved to be a little more tricky than anticipated due to null and specific string value checks required - getting the generic typing right required use of default(T) and Convert.ChangeType() to trick the compiler into playing nice. Of course the whole raison d'etre for this class is the XML serialization. You can see in the code above that we're doing a .ToXml() and .FromXml() to serialize to and from string. The XML produced for the first example looks like this: <?xml version="1.0" encoding="utf-8"?> <properties> <item> <key>key</key> <value>Value</value> </item> <item> <key>Key2</key> <value type="decimal">100.10</value> </item> <item> <key>Key3</key> <value type="___System.Guid"> <guid>f7a92032-0c6d-4e9d-9950-b15ff7cd207d</guid> </value> </item> <item> <key>Key4</key> <value type="datetime">2011-09-26T17:45:58.5789578-10:00</value> </item> <item> <key>Key5</key> <value type="boolean">true</value> </item> <item> <key>Key7</key> <value type="base64Binary">Ki1C</value> </item> <item> <key>Key8</key> <value type="nil" /> </item> <item> <key>Key9</key> <value type="___Westwind.Tools.Tests.PropertyBagTest+ComplexObject"> <ComplexObject> <Name>Rick</Name> <Entered>2011-09-26T17:45:58.5789578-10:00</Entered> <Count>10</Count> </ComplexObject> </value> </item> </properties>   The format is a bit cleaner than the DataContractSerializer. Each item is serialized into <key> <value> pairs. If the value is a string no type information is written. Since string tends to be the most common type this saves space and serialization processing. All other types are attributed. Simple types are mapped to XML types so things like decimal, datetime, boolean and base64Binary are encoded using their Xml type values. All other types are embedded with a hokey format that describes the .NET type preceded by a three underscores and then are encoded using the XmlSerializer. You can see this best above in the ComplexObject encoding. For custom types this isn't pretty either, but it's more concise than the DCS and it works as long as you're serializing back and forth between .NET clients at least. The XML generated from the second example that uses PropertyBag<decimal> looks like this: <?xml version="1.0" encoding="utf-8"?> <properties> <item> <key>key</key> <value type="decimal">10</value> </item> <item> <key>Key1</key> <value type="decimal">100.10</value> </item> <item> <key>Key2</key> <value type="decimal">200.10</value> </item> <item> <key>Key3</key> <value type="decimal">300.10</value> </item> </properties>   How does it work As I mentioned there's nothing fancy about this solution - it's little more than a subclass of Dictionary<T,V> that implements custom Xml Serialization and a couple of helper methods that facilitate getting the XML in and out of the class more easily. But it's proven very handy for a number of projects for me where dynamic data storage is required. Here's the code: /// <summary> /// Creates a serializable string/object dictionary that is XML serializable /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> [XmlRoot("properties")] public class PropertyBag : PropertyBag<object> { /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml">Serialize</param> /// <returns></returns> public static PropertyBag CreateFromXml(string xml) { var bag = new PropertyBag(); bag.FromXml(xml); return bag; } } /// <summary> /// Creates a serializable string for generic types that is XML serializable. /// /// Encodes keys as element names and values as simple values with a type /// attribute that contains an XML type name. Complex names encode the type /// name with type='___namespace.classname' format followed by a standard xml /// serialized format. The latter serialization can be slow so it's not recommended /// to pass complex types if performance is critical. /// </summary> /// <typeparam name="TValue">Must be a reference type. For value types use type object</typeparam> [XmlRoot("properties")] public class PropertyBag<TValue> : Dictionary<string, TValue>, IXmlSerializable { /// <summary> /// Not implemented - this means no schema information is passed /// so this won't work with ASMX/WCF services. /// </summary> /// <returns></returns> public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Serializes the dictionary to XML. Keys are /// serialized to element names and values as /// element values. An xml type attribute is embedded /// for each serialized element - a .NET type /// element is embedded for each complex type and /// prefixed with three underscores. /// </summary> /// <param name="writer"></param> public void WriteXml(System.Xml.XmlWriter writer) { foreach (string key in this.Keys) { TValue value = this[key]; Type type = null; if (value != null) type = value.GetType(); writer.WriteStartElement("item"); writer.WriteStartElement("key"); writer.WriteString(key as string); writer.WriteEndElement(); writer.WriteStartElement("value"); string xmlType = XmlUtils.MapTypeToXmlType(type); bool isCustom = false; // Type information attribute if not string if (value == null) { writer.WriteAttributeString("type", "nil"); } else if (!string.IsNullOrEmpty(xmlType)) { if (xmlType != "string") { writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } } else { isCustom = true; xmlType = "___" + value.GetType().FullName; writer.WriteStartAttribute("type"); writer.WriteString(xmlType); writer.WriteEndAttribute(); } // Actual deserialization if (!isCustom) { if (value != null) writer.WriteValue(value); } else { XmlSerializer ser = new XmlSerializer(value.GetType()); ser.Serialize(writer, value); } writer.WriteEndElement(); // value writer.WriteEndElement(); // item } } /// <summary> /// Reads the custom serialized format /// </summary> /// <param name="reader"></param> public void ReadXml(System.Xml.XmlReader reader) { this.Clear(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "key") { string xmlType = null; string name = reader.ReadElementContentAsString(); // item element reader.ReadToNextSibling("value"); if (reader.MoveToNextAttribute()) xmlType = reader.Value; reader.MoveToContent(); TValue value; if (xmlType == "nil") value = default(TValue); // null else if (string.IsNullOrEmpty(xmlType)) { // value is a string or object and we can assign TValue to value string strval = reader.ReadElementContentAsString(); value = (TValue) Convert.ChangeType(strval, typeof(TValue)); } else if (xmlType.StartsWith("___")) { while (reader.Read() && reader.NodeType != XmlNodeType.Element) { } Type type = ReflectionUtils.GetTypeFromName(xmlType.Substring(3)); //value = reader.ReadElementContentAs(type,null); XmlSerializer ser = new XmlSerializer(type); value = (TValue)ser.Deserialize(reader); } else value = (TValue)reader.ReadElementContentAs(XmlUtils.MapXmlTypeToType(xmlType), null); this.Add(name, value); } } } /// <summary> /// Serializes this dictionary to an XML string /// </summary> /// <returns>XML String or Null if it fails</returns> public string ToXml() { string xml = null; SerializationUtils.SerializeObject(this, out xml); return xml; } /// <summary> /// Deserializes from an XML string /// </summary> /// <param name="xml"></param> /// <returns>true or false</returns> public bool FromXml(string xml) { this.Clear(); // if xml string is empty we return an empty dictionary if (string.IsNullOrEmpty(xml)) return true; var result = SerializationUtils.DeSerializeObject(xml, this.GetType()) as PropertyBag<TValue>; if (result != null) { foreach (var item in result) { this.Add(item.Key, item.Value); } } else // null is a failure return false; return true; } /// <summary> /// Creates an instance of a propertybag from an Xml string /// </summary> /// <param name="xml"></param> /// <returns></returns> public static PropertyBag<TValue> CreateFromXml(string xml) { var bag = new PropertyBag<TValue>(); bag.FromXml(xml); return bag; } } } The code uses a couple of small helper classes SerializationUtils and XmlUtils for mapping Xml types to and from .NET, both of which are from the WestWind,Utilities project (which is the same project where PropertyBag lives) from the West Wind Web Toolkit. The code implements ReadXml and WriteXml for the IXmlSerializable implementation using old school XmlReaders and XmlWriters (because it's pretty simple stuff - no need for XLinq here). Then there are two helper methods .ToXml() and .FromXml() that basically allow your code to easily convert between XML and a PropertyBag object. In my code that's what I use to actually to persist to and from the entity XML property during .Load() and .Save() operations. It's sweet to be able to have a string key dictionary and then be able to turn around with 1 line of code to persist the whole thing to XML and back. Hopefully some of you will find this class as useful as I've found it. It's a simple solution to a common requirement in my applications and I've used the hell out of it in the  short time since I created it. Resources You can find the complete code for the two classes plus the helpers in the Subversion repository for Westwind.Utilities. You can grab the source files from there or download the whole project. You can also grab the full Westwind.Utilities assembly from NuGet and add it to your project if that's easier for you. PropertyBag Source Code SerializationUtils and XmlUtils Westwind.Utilities Assembly on NuGet (add from Visual Studio) © Rick Strahl, West Wind Technologies, 2005-2011Posted in .NET  CSharp   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How to choose between protobuf-csharp-port and protobuf-net

    - by PierrOz
    Hi Folks, I've recently had to look for a C# porting of the Protocole Buffer library originally developped by Google. And guess what, I found two projects owned both by two very well known persons here: protobuf-csharp-port, written by Jon Skeet and protobuf-net, written by Mark Gravell. My question is simple: which one do I have to choose ? I quite like Mark's solution as it seems to me closer to C# philisophy (for instance, you can just add attributes to the properties of existing class) and it looks like it can support .NET built-in types such as System.Guid. I am sure both of them are really great projects but what's your oppinion?

    Read the article

  • check status application pool iis7 with csharp (access-denied)

    - by jack
    I need to monitor the status of an application in the applications pool of IIS 7 from an other machine on the same domain. My monitoring application must be in C# and running as a Windows service. On my server, I create a user with administration rights and I execute the command aspnet_regiis -ga machine\username wich worked succesfully. My problem is when I try to access the application pool i still get COMExcepttion "Access denied". What did i do wrong or wich step did i miss? I used code from http://patelshailesh.com/index.php/create-a-website-application-pool-programmatically-using-csharp as example. int status = 0; string ipAddress = "10.20.2.13"; string username = "username"; string password = "password"; try { DirectoryEntry de = new DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools/MyAppPoolName", ipAddress), username, password); //the exception is thron here. status = (int)de.InvokeGet("AppPoolState"); switch (status) { case 2: //Runnig break; case 4: //Stopped break; default: break; } } catch (Exception ex) { }

    Read the article

  • Csharp component which generates fragments with highlights for diffs for 2 strings

    - by MicMit
    I need C# implementation ( ideally open source ) which is similar to Delphi DLL. I am currently using the wrapper ( C# syntax is provided , but it is a call from a different language ) zdiff( string ref str1, string ref str2, int range , int trim ) it calls inside str1 = GetHiDiff(@str1,1,trim) str2 = GetHiDiff(@str1,2,trim) where function GetHiDiff(s:pchar; sIndex:integer; wtrim:integer): pchar; stdcall; What it does it returns a left fragment html of str1 and a right html fragment of str2 with diffs highlighted as strings are passed by reference. Range parameter determines the size of html fragment. Not sure what trim 0 does.

    Read the article

  • CSharp: Testing a Generic Class

    - by Jonas Gorauskas
    More than a question, per se, this is an attempt to compare notes with other people. I wrote a generic History class that emulates the functionality of a browser's history. I am trying to wrap my head around how far to go when writing unit tests for it. I am using NUnit. Please share your testing approaches below. The full code for the History class is here (http://pastebin.com/ZGKK2V84).

    Read the article

  • Csharp component which generates fragmens with highlights for diffs for 2 strings

    - by MicMit
    I need C# equivalent ( ideally open source ) which is similar to Delphi DLL. I am currently using the wrapper ( C# syntax is provided , but it is a call from a different language ) zdiff( string ref str1, string ref str2, int range , int trim ) it calls inside str1 = GetHiDiff(@str1,1,trim) str2 = GetHiDiff(@str1,2,trim) where function GetHiDiff(s:pchar; sIndex:integer; wtrim:integer): pchar; stdcall; What it does it returns a left fragment html of str1 and a right html fragment of str2 with diffs highlighted as strings are passed by reference. Range parameter determines the size of html fragment. Not sure what trim 0 does.

    Read the article

  • asp.net - csharp - jquery - looking for a better and usage solution

    - by LostLord
    hi my dear friends i have a little problem about using jquery...(i reeally do not know jquery but i forced to use it) i am using vs 2008 - asp.net web app with c# also i am using telerik controls in my pages also i am using sqldatasources (Connecting to storedprocedures) in my pages my pages base on master and content pages and in content pages i have mutiviews ================================================================================= in one of the views(inside one of those multiviews)i had made two radcombo boxes for country and city requirement like cascading dropdowns as parent and child combo boxes. i used old way for doing that , i mean i used update panel and in the SelectedIndexChange Event of Parent RadComboBox(Country) i Wrote this code : protected void RadcomboboxCountry_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e) { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } my child radcombo box can fill by upper code , let me tell you how : the child sqldatasource have a sp that has a parameter and i fill that parameter by this line - hfSelectedCo_ID.Value = RadcbCoNameInInsert.SelectedValue; RadcbCoNameInInsert.SelectedValue means country ID. after doing that SelectedIndexChange Event of Parent RadComboBox(Country) could not be fire therefore i forced to set the autopostback property to true. afetr doing that every thing was ok until some one told me can u control focus and keydown of your radcombo boxes (when u press enter key on the parent combobox[country] , so child combobox gets focus -- and when u press upperkey on child radcombobox [city], so parent combobox[country] gets focus) (For Users That Do Not Want To Use Mouse for Input Info And Choose items) i told him this is web app , not win form and we can not do that. i googled it and i found jquery the only way for doing that ... so i started using jquery . i wrote this code with jquery for both of them : <script src="../JQuery/jquery-1.4.1.js" language="javascript" type="text/javascript"></script> <script type="text/javascript"> $(function() { $('input[id$=RadcomboboxCountry_Input]').focus(); $('input[id$=RadcomboboxCountry_Input]').select(); $('input[id$=RadcomboboxCountry_Input]').bind('keyup', function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) { -----------> Enter Key $('input[id$=RadcomboboxCity_Input]').focus(); $('input[id$=RadcomboboxCity_Input]').select(); } }); $('input[id$=RadcomboboxCity_Input]').bind('keyup', function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 38) { -----------> Upper Key $('input[id$=RadcomboboxCountry_Input]').focus(); $('input[id$=RadcomboboxCountry_Input]').select(); } }); }); </script> this jquery code worked BBBBBBUUUUUUUTTTTTT autopostback=true of the Parent RadComboBox Became A Problem , Because when SelectedIndex Change Of ParentRadComboBox is fired after that Telerik Skins runs and after that i lost parent ComboBox Focus and we should use mouse but we don't want it.... for fix this problem i decided to set autopostback of perentCB to false and convert protected void RadcomboboxCountry_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e) { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } to a public non static method without parameters and call it with jquey like this : (i used onclientchanged property of parentcombo box like onclientchanged = "MyMethodForParentCB_InJquery();" insread of selectedindexchange event) public void MyMethodForParentCB_InCodeBehind() { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } for doing that i read the blow manual and do that step by step : ======================================================================= http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=732 ======================================================================= but this manual is about static methods and this is my new problem ... when i am using static method like : public static void MyMethodForParentCB_InCodeBehind() { hfSelectedCo_ID.Value = RadcomboboxCountry.SelectedValue; RadcomboboxCity.Items.Clear(); RadcomboboxCity.Items.Add(new RadComboBoxItem(" ...", "5")); RadcomboboxCity.DataBind(); RadcomboboxCity.SelectedIndex = 0; } so i recieved some errors and this method could not recognize my controls and hidden field... one of those errors like this : Error 2 An object reference is required for the non-static field, method, or property 'Darman.SuperAdmin.Users.hfSelectedCo_ID' C:\Javad\Copy of Darman 6\Darman\SuperAdmin\Users.aspx.cs 231 13 Darman any idea or is there any way to call non static methods with jquery (i know we can not do that but is there another way to solve my problem)???????????????

    Read the article

  • CSharp -- PInvokeStackImbalance detected on a well documented function?

    - by Aaron Hammond
    Here is my code for a ClickMouse() function: [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo); private const long MOUSEEVENTF_LEFTDOWN = 0x02; private const long MOUSEEVENTF_LEFTUP = 0x04; private const long MOUSEEVENTF_RIGHTDOWN = 0x08; private const long MOUSEEVENTF_RIGHTUP = 0x10; private void ClickMouse() { long X = Cursor.Position.X; long Y = Cursor.Position.Y; mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0); } For some reason, when my program comes to this code, it throws this error message: PInvokeStackImbalance was detected Message: A call to PInvoke function 'WindowsFormsApplication1!WindowsFormsApplication1.Form1::mouse_event' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. Please help?

    Read the article

  • CSharp Compiler and Windows.Forms

    - by j-t-s
    Hi All I've just created a little app that programmatically compiles code using the C# Compiler, and it works brilliantly. But, one thing that I need it to do is compile Windows.Forms code. Like, I can create a console app with it, but I can't create a GUI-based form. Here's the link that got me started: http://support.microsoft.com/kb/304655 Can somebody please help? Thank you :)

    Read the article

  • Accessing C++ methods from Csharp

    - by Code Smack
    Hello, I have a string with CompressedRichText in it. I want to uncompressed it to standard RTF and then to plain Text. I am using VS 2008 C# Windows Application. I found references to C++ code to do it, but nothing directly in C#. I found some info at this site on the C++ part, but I have no idea how to use this from my C# code. What do I need to do in order to access the methods in the C++ code from my C# project. Link to the C++ Code http://msdn.microsoft.com/en-us/library/bb905295.aspx Thanks!

    Read the article

  • Csharp: I am trying to get the top nth values from and rectangular array

    - by user355925
    I am reading a txt file for strings that represent intergers. the file is space delimited. I have created an array[10,2]. evertime the the strings 1~10 is found in the file I increment array[n,0] by 1. I also feed array[n,1] with numbers 1~10. ie txt file contents: 1/1/1 10/1/2001 1 1 10 2 2 3 1 5 10 word word 3 3 etc.. streamreader reads 1/1/1 and determines that is is not 1~10 streamreader reads 10/1/2001 and determines that it is not 1~10 streamreader reads 1 and ++array[0,0] streamreader reads 1 and ++array[0,0] streamreader reads 10 and ++array[9,0] etc.. the result will be: '1' was found 3 times '2' was found 2 times '3' was found 3 times '5' was found 1 time '10' was found 2 times My problem is that I need this array placed in order(sorted) by value of column 0 so that it would be: 1 3 2 10 5

    Read the article

  • csharp get value datatemplate element

    - by To-me
    Hello, Here is my code <ListBox x:Name="myList" IsSynchronizedWithCurrentItem="True" SelectionChanged="editElement"> <ListBox.ItemTemplate> <DataTemplate x:Name="ElementItemTemplate"> <StackPanel Name="stackPanelElementItem" Orientation="Horizontal"> <Label Name="SelectedItemlabel" Content="{Binding}" /> <Button Name="buttonDelElement" Click="btnDelElement">Delete</Button> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> private void btnDelElement(object sender, RoutedEventArgs e) { ListBoxItem lbi2 = (ListBoxItem)(lstCursus.ItemContainerGenerator.ContainerFromItem(myList.Items.CurrentItem)); String selectedItem = lbi2.Content.ToString(); MessageBox.Show("Selected Item " + selectedItem + " ."); private void editCursus(object sender, RoutedEventArgs e) { MessageBox.Show("Selected Item " + selectedItem + " ."); /* some code to edit selected item using linq */ } My issue, SelectionChange doesn't work anymore and when I click on buttonDelElement, Selected Item doesn't change immediately. Please, any ideas?

    Read the article

  • directoryperdb issue

    - by Rich Blumer
    I installed MongoDB to run as a Windows Service on Win 7 and everything runs well. However, when I attempt to use the command --directoryperdb, it does not recognize this command. Does anyone know how to resolve this issue?

    Read the article

  • Initializing a property in c#

    - by Shonna
    I have a constructor I am trying to build with the header public KsuPoint(double x0, double y0) now i also have properties in the class as shown below private double x; public double X { get { return x; } } private double y; public double Y { get { return y; } } This constructor is suppose to initialize the properties X and Y ... is this correct? or am i off? public KsuPoint(double x0, double y0) { new KsuPoint(x0, y0); }

    Read the article

  • How to get actual type of an derived class from its parent interface

    - by Tarik
    Hello people, Lets say we have a code portion like this : IProduct product = ProductCreator.CreateProduct(); //Factory Method we have here SellThisProduct(product); //... private void SellThisProduct(IProduct product) { //..do something here } //... internal class Soda : IProduct {} internal class Book : IProduct {} How can I infer which product is actually passed into SellThisProduct() method in the method? I think if I say GetType() or something it will probably return the IProduct type. Thanks...

    Read the article

  • Which audio library to use?

    - by Jeb
    I want to build a .Net application for processing audio, and distribute it using ClickOnce deployment. I need access to a raw audio pipeline. Which audio library should I be using? I've heard the managed libraries for DirectSound are a dead end. I need as little as possible to be installed on the client's machine. Anything outside of the ClickOnce process isn't going to work. NAudio might be a possibility, but isn't there potentially a separate driver install? There's also SlimDX. It's a shame -- the managed DirectX libraries seem to work nicely and from what I've read, DirectX can be included in the ClickOnce install.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >