Search Results

Search found 44052 results on 1763 pages for 'pass by value'.

Page 10/1763 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • using KVO to filter an NSTableView using NSPredicate (with arrays)

    - by KingRufus
    My UI is not updating when I expect it to. The application displays "projects" using a view similar to iTunes -- a source list on the left lets you filter a list (NSTableView) on the right. My filters update properly when they are examining any simple field (like name, a string), but not for arrays (like tags). I'm removing a tag from one of my objects (from an NSMutableArray field called "tags") and I expect it to disappear from the list because it no longer matches the predicate that is bound to my table's NSArrayController. ProjectBrowser.mm: self.filter = NSPredicate* srcPredicate = [NSPredicate predicateWithFormat:@"%@ IN %K", selectedTag, @"tags"]; Project.mm: [self willChangeValueForKey:@"tags"]; [tags removeAllObjects]; [self didChangeValueForKey:@"tags"]; I've also tried this, but the result is the same: [[self mutableArrayValueForKey:@"tags"] removeAllObjects]; Interface Builder setup: a ProjectBrowser object is the XIB's File Owner an NSArrayController (Project Controller) has its Content Array bound to "File's Owner".projects Project Controller's filter predicate is bound to "File's Owner".filter NSTableView's column is bound to "Project Controller".name

    Read the article

  • Problem getting value from "Checkbox group value prompt"

    - by Veer
    Hi, I've value prompt with ui:checkbox group parameter: p_IsLastMonth Name: Prompt_IsLastMonth ItemCount: 1; UseValue:Yes, DisplayValue: LastMonth? and two Date Prompts. Whenever the checkbox is checked, the UseValue 'Yes' is passed to the parameter 'p_IsLastMonth'. But whenever the checkbox is left as it is, it results in an error. Element 'selectOptions' is not valid for content model: 'All(style,defaultSelections,conditionalStyles,conditionalRender,XMLAttributes)' I also tried giving a default value. But the default value has to be in the collection. But i want only one checkbox to be displayed. I tried with html checkbox. But i'm not able to send the value 'either yes or no' to the parameter through javascript because however the finish button overrides the value. Any help?

    Read the article

  • using KVO to update an NSTableView filtered by an NSPredicate

    - by KingRufus
    My UI is not updating when I expect it to. The application displays "projects" using a view similar to iTunes -- a source list on the left lets you filter a list (NSTableView) on the right. My filters update properly when they are examining any simple field (like name, a string), but not for arrays (like tags). I'm removing a tag from one of my objects (from an NSMutableArray field called "tags") and I expect it to disappear from the list because it no longer matches the predicate that is bound to my table's NSArrayController. ProjectBrowser.mm: self.filter = NSPredicate* srcPredicate = [NSPredicate predicateWithFormat:@"%@ IN %K", selectedTag, @"tags"]; Project.mm: [self willChangeValueForKey:@"tags"]; [tags removeAllObjects]; [self didChangeValueForKey:@"tags"]; I've also tried this, but the result is the same: [[self mutableArrayValueForKey:@"tags"] removeAllObjects]; Interface Builder setup: a ProjectBrowser object is the XIB's File Owner an NSArrayController (Project Controller) has its Content Array bound to "File's Owner".projects Project Controller's filter predicate is bound to "File's Owner".filter NSTableView's column is bound to "Project Controller".name

    Read the article

  • Redeclaration of parameters

    - by Scott
    While looking through the Selenium source code I noticed the following in the PageFactory: public static <T> T initElements(WebDriver driver, Class<T> pageClassToProxy) { T page = instantiatePage(driver, pageClassToProxy); initElements(driver, page); return page; } public static void initElements(WebDriver driver, Object page) { final WebDriver driverRef = driver; initElements(new DefaultElementLocatorFactory(driverRef), page); } What is the benefit of having the following line? final WebDriver driverRef = driver; Wouldn't it have made sense to just make the parameter final, and then passing that along to the next method without declaring the new reference?

    Read the article

  • Why is this Python class copying another class contents?

    - by fjfnaranjo
    Hello guys. I'm trying to understand an estrange behavior in Python. I have the next python code: class IntContainer: listOfInts = [] def __init__(self, initListOfInts): for i in initListOfInts: self.listOfInts.append(i) def printInts(self): print self.listOfInts if __name__ == "__main__": intsGroup1 = [1,2,3,4] intsGroup2 = [4,5,6,7] intsGroups = [intsGroup1,intsGroup2] intsContainers = [] for ig in intsGroups: newIntContainer = IntContainer(ig) intsContainers.append(newIntContainer) for ic in intsContainers: print ic.listOfInts I expect to get something like: [1, 2, 3, 4] [4, 5, 6, 7] But i get: [1, 2, 3, 4, 4, 5, 6, 7] [1, 2, 3, 4, 4, 5, 6, 7] I have check the next question: http://stackoverflow.com/questions/1876905/why-is-python-reusing-a-class-instance-inside-in-function And a lot of Python reference, but I can not understand what is happening. I think is related with the newIntContainer identifier reutilization, but I do not understand it deeply. Why Python appears to reused the last reference for the new object, even if I have added it to a permanent list? What can I do to resolve this behavior? Thanks ;)

    Read the article

  • Javascript jQuery .click() callback references local variable from the calling method instead of cop

    - by Eric Freese
    The following jQuery Javascript code is included on an otherwise empty page. $(function() { for (var i = 0; i < 10; i++) { element = $('<div>' + i + '</div>'); element.click(function() { alert(i); }); $('body').append(element); } }); The desired behavior is that this code should generate 10 div elements numbered from 0 to 9. When you click on a div element, an alert popup will show the number of the div element you clicked on (i.e. if a user clicks on the div element labeled '4', the alert popup should show the number 4). The alert popup instead shows the number 10 regardless of which div element is clicked on. How can I modify this code to make it behave in the desired way?

    Read the article

  • SQL Design: representing a default value with overrides?

    - by Mark Harrison
    I need a sparse table which contains a set of "override" values for another table. I also need to specify the default value for the items overridden. For example, if the default value is 17, then foo,bar,baz will have the values 17,21,17: table "things" table "xvalue" name stuff name xval ---- ----- ---- ---- foo ... bar 21 bar ... baz ... If I don't care about a FK from xvalue.name - things.name, I could simply put a "DEFAULT" name: table "xvalue" name xval ---- ---- DEFAULT 17 bar 21 But I like having a FK. I could have a separate default table, but it seems odd to have 2x the number of tables. table "xvalue_default" xval ---- 17 table "xvalue" name xval ---- ---- bar 21 I could have a "defaults table" tablename attributename defaultvalue xvalue xval 17 but then I run into type issues on defaultvalue. My operations guys prefer as compact a representation as possible, so they can most easily see the "diff" or deviations from the default. What's the best way to represent this, including the default value? This will be for Oracle 10.2 if that makes a difference.

    Read the article

  • unable to return 'true' value in C function

    - by Byron
    If Im trying to check an input 5 byte array (p) against a 5 byte array stored in flash (data), using the following function (e2CheckPINoverride), to simply return either a true or false value. But it seems, no matter what I try, it only returns as 'false'. I call the function here: if (e2CheckPINoverride(pinEntry) == 1){ PTDD_PTDD1 = 1; } else{ PTDD_PTDD1 = 0; } Here is the function: BYTE e2CheckPINoverride(BYTE *p) { BYTE i; BYTE data[5]; if(e2Read(E2_ENABLECODE, data, 5)) { if(data[0] != p[0]) return FALSE; if(data[1] != p[1]) return FALSE; if(data[2] != p[2]) return FALSE; if(data[3] != p[3]) return FALSE; if(data[4] != p[4]) return FALSE; } return TRUE; } I have already assigned true and false in the defines.h file: #ifndef TRUE #define TRUE ((UCHAR)1) #endif #ifndef FALSE #define FALSE ((UCHAR)0) #endif and where typedef unsigned char UCHAR; when i step through the code, it performs all the checks correctly, it passes in the correct value, compares it correctly and then breaks at the correct point, but is unable to process the return value of true? please help?

    Read the article

  • ASP.NET MVC 2 / Localization / Dynamic Default Value?

    - by cyberblast
    Hello In an ASP.NET MVC 2 application, i'm having a route like this: routes.MapRoute( "Default", // Route name "{lang}/{controller}/{action}/{id}", // URL with parameters new // Parameter defaults { controller = "Home", action = "Index", lang = "de", id = UrlParameter.Optional }, new { lang = new AllowedValuesRouteConstraint(new string[] { "de", "en", "fr", "it" }, StringComparison.InvariantCultureIgnoreCase) } Now, basically I would like to set the thread's culture according the language passed in. But there is one exception: If the user requests the page for the first time, like calling "http://www.mysite.com" I want to set the initial language if possible to the one "preferred by the browser". How can I distinguish in an early procesing stage (like global.asax), if the default parameter has been set because of the default value or mentioned explicit through the URL? (I would prefer a solution where the request URL is not getting parsed). Is there a way to dynamically provide a default-value for a paramter? Something like a hook? Or where can I override the default value (good application event?). This is the code i'm actually experimenting with: protected void Application_AcquireRequestState(object sender, EventArgs e) { string activeLanguage; string[] validLanguages; string defaultLanguage; string browsersPreferredLanguage; try { HttpContextBase contextBase = new HttpContextWrapper(Context); RouteData activeRoute = RouteTable.Routes.GetRouteData(new HttpContextWrapper(Context)); if (activeRoute == null) { return; } activeLanguage = activeRoute.GetRequiredString("lang"); Route route = (Route)activeRoute.Route; validLanguages = ((AllowedValuesRouteConstraint)route.Constraints["lang"]).AllowedValues; defaultLanguage = route.Defaults["lang"].ToString(); browsersPreferredLanguage = GetBrowsersPreferredLanguage(); //TODO: Better way than parsing the url bool defaultInitialized = contextBase.Request.Url.ToString().IndexOf(string.Format("/{0}/", defaultLanguage), StringComparison.InvariantCultureIgnoreCase) > -1; string languageToActivate = defaultLanguage; if (!defaultInitialized) { if (validLanguages.Contains(browsersPreferredLanguage, StringComparer.InvariantCultureIgnoreCase)) { languageToActivate = browsersPreferredLanguage; } } //TODO: Where and how to overwrtie the default value that it gets passed to the controller? contextBase.RewritePath(contextBase.Request.Path.Replace("/de/", "/en/")); SetLanguage(languageToActivate); } catch (Exception ex) { //TODO: Log Console.WriteLine(ex.Message); } } protected string GetBrowsersPreferredLanguage() { string acceptedLang = string.Empty; if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length > 0) { acceptedLang = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2); } return acceptedLang; } protected void SetLanguage(string languageToActivate) { CultureInfo cultureInfo = new CultureInfo(languageToActivate); if (!Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.Equals(languageToActivate, StringComparison.InvariantCultureIgnoreCase)) { Thread.CurrentThread.CurrentUICulture = cultureInfo; } if (!Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName.Equals(languageToActivate, StringComparison.InvariantCultureIgnoreCase)) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name); } } The RouteConstraint to reproduce the sample: public class AllowedValuesRouteConstraint : IRouteConstraint { private string[] _allowedValues; private StringComparison _stringComparism; public string[] AllowedValues { get { return _allowedValues; } } public AllowedValuesRouteConstraint(string[] allowedValues, StringComparison stringComparism) { _allowedValues = allowedValues; _stringComparism = stringComparism; } public AllowedValuesRouteConstraint(string[] allowedValues) { _allowedValues = allowedValues; _stringComparism = StringComparison.InvariantCultureIgnoreCase; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (_allowedValues != null) { return _allowedValues.Any(a => a.Equals(values[parameterName].ToString(), _stringComparism)); } else { return false; } } } Can someone help me out with that problem? Thanks, Martin

    Read the article

  • value of Identity column returning null when retrieved by value in dataGridView

    - by Raven Dreamer
    Greetings. I'm working on a windows forms application that interacts with a previously created SQL database. Specifically, I'm working on implementing an "UPDATE" query. for (int i = 0; i < dataGridView1.RowCount; i++) { string firstName = (string)dataGridView1.Rows[i].Cells[0].Value; string lastName = (string)dataGridView1.Rows[i].Cells[1].Value; string phoneNo = (string)dataGridView1.Rows[i].Cells[2].Value; short idVal = (short)dataGridView1.Rows[i].Cells[3].Value; this.contactInfoTableAdapter.UpdateQuery(firstName, lastName, phoneNo, idVal); } The dataGridView has 4 columns, First Name, Last Name, Phone Number, and ID (which was created as an identity column when I initially formed the table in SQL). When I try to run this code, the three strings are returned properly, but dataGridView1.Rows[i].Cells[3].Value is returning "null". I'm guessing this is because it was created as an identity column rather than a normal column. What's a better way to retrieve the relevant ID value for my UpdateQuery?

    Read the article

  • Asp.net Hidden field not having value in code behind, but *is* retaining value after postbacks

    - by KallDrexx
    In my ASCX, I have an asp.net hidden field defined as <asp:HiddenField ID="hdnNewAsset" runat="server" />. In the Code Behind I have the following code: protected void Page_Load(object sender, EventArgs e) { _service = new ArticleDataService(PortalId); if (!IsPostBack) { string rawId = Request[ArticleQueryParams.ArticleId]; DisplayArticleDetails(rawId); } if (hdnNewAsset.Value.Trim() != string.Empty) ProcessNewAsset(); } Now, in my frontend, I have a javascript function to react to an event and set the hidden field and trigger a postback: function assetSelected(assetGuid) { $('input[id*="hdnNewAsset"]').val(assetGuid); __doPostBack() } What's happening is that my hidden field is being set in the markup (chrome shows [ <input type=?"hidden" name=?"dnn$ctr466$Main$ctl00$hdnNewAsset" id=?"dnn_ctr466_Main_ctl00_hdnNewAsset" value=?"98d88e72-088c-40a4-9022-565a53dc33c4">? ] for $('input[id*="hdnNewAsset"]')). However, when the postback occurs, hdnNewAsset.Value is an empty string. What's even more puzzling is that at the beginning of Page_Load Request.Params["dnn$ctr466$Main$ctl00$hdnNewAsset"] shows 98d88e72-088c-40a4-9022-565a53dc33c4, and after the postback my hidden field has the same value (so the hidden field is persisting across postbacks), yet I cannot access this value via hdnNewAsset.Value. Can anyone see what I"m doing wrong?

    Read the article

  • Name for method that takes a string value and returns DBNull.Value || string

    - by David Murdoch
    I got tired of writing the following code: /* Commenting out irrelevant parts public string MiddleName; public void Save(){ SqlCommand = new SqlCommand(); // blah blah...boring INSERT statement with params etc go here. */ if(MiddleName==null){ myCmd.Parameters.Add("@MiddleName", DBNull.Value); } else{ myCmd.Parameters.Add("@MiddleName", MiddleName); } /* // more boring code to save to DB. }*/ So, I wrote this: public static object DBNullValueorStringIfNotNull(string value) { object o; if (value == null) { o = DBNull.Value; } else { o = value; } return o; } // which would be called like: myCmd.Parameters.Add("@MiddleName", DBNullValueorStringIfNotNull(MiddleName)); If this is a good way to go about doing this then what would you suggest as the method name? DBNullValueorStringIfNotNull is a bit verbose and confusing. I'm also open to ways to alleviate this problem entirely. I'd LOVE to do this: myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName); but that won't work. I've got C# 3.5 and SQL Server 2005 at my disposal if it matters.

    Read the article

  • 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

  • Weird Excel Formatting

    - by Gage
    Recently a new co-op was hired at our company and has been tasked to run a report. The report queries the database and returns a resultset and from there procedes to create the spreadsheets. Depending on the number of days selected a different number of reports are generated but I do not believe that is relavent to the question. Basically it runs the reports and loops through the resultset but at some point continues to loop through until tow 65536 at which it stops. For Example if the resultset contained 74 records then the first 74 rows would appear normally (formatted yellow) while everything after that would also be formatted yellow although it should be left alone. I am inheriting this code as I to am a new co-op. Apparently this only happens when a "change of guards" happens (New co-op has to run the report).` DoCmd.SetWarnings False DoCmd.OpenQuery ("DailySummaryQueryMain") strSQL = "SELECT * FROM DailySummaryMain" Set rs = CurrentDb.OpenRecordset(strSQL) DoCmd.Echo True, "Running first Report" If Not rs.EOF Then rs.MoveFirst Do While Not rs.EOF And Not rs.BOF xlapp.Range("A" & i).Value = rs.Fields(0).Value xlapp.Range("B" & i).Value = rs.Fields(1).Value xlapp.Range("C" & i).Value = rs.Fields(2).Value Set rs2 = CurrentDb.OpenRecordset("SELECT dbo_StatusType.StatusTypeID, dbo_StatusType.Name FROM dbo_StatusType WHERE (((dbo_StatusType.StatusTypeID)=" & rs.Fields(3) & "))") rs2.MoveFirst xlapp.Range("D" & i).Value = rs2.Fields(1).Value xlapp.Range("E" & i).Value = rs.Fields(4).Value xlapp.Range("F" & i).Value = rs.Fields(5).Value xlapp.Range("G" & i).Value = rs.Fields(6).Value 'count number of outages that start and end on same day If Format(xlapp.Range("F" & i).Value, "mm/dd/yyyy") = Format(xlapp.Range("G" & i).Value, "mm/dd/yyyy") Then dayCount = dayCount + 1 End If xlapp.Range("H" & i).Value = rs.Fields(7).Value xlapp.Range("I" & i).Value = rs.Fields(8).Value xlapp.Range("J" & i).Value = rs.Fields(9).Value xlapp.Range("K" & i).Value = rs.Fields(10).Value xlapp.Range("L" & i).Value = rs.Fields(11).Value xlapp.Range("M" & i).Value = rs.Fields(12).Value xlapp.Range("N" & i).Value = rs.Fields(13).Value 'highlite recently modified rows If rs.Fields(14).Value = "Yes" Then xlapp.Range("A" & i & ":N" & i).Select With xlapp.Selection.Interior .ColorIndex = 36 .Pattern = xlSolid End With End If 'break apart by sector If CInt(rs.Fields(2).Value) = 1 Then row = row1 ElseIf CInt(rs.Fields(2).Value) = 2 Then row = row2 ElseIf CInt(rs.Fields(2).Value) = 3 Then row = row3 Else row = row4 End If xlapp.Worksheets(CInt(rs.Fields(2).Value) + 1).Activate xlapp.Range("A" & row).Value = rs.Fields(0).Value xlapp.Range("B" & row).Value = rs.Fields(1).Value xlapp.Range("C" & row).Value = rs.Fields(13).Value xlapp.Range("D" & row).Value = rs.Fields(4).Value xlapp.Range("E" & row).Value = rs.Fields(5).Value xlapp.Range("F" & row).Value = rs.Fields(6).Value xlapp.Range("G" & row).Value = rs.Fields(7).Value xlapp.Range("H" & row).Value = rs.Fields(8).Value xlapp.Range("I" & row).Value = rs.Fields(9).Value xlapp.Range("J" & row).Value = rs.Fields(10).Value xlapp.Range("K" & row).Value = "" xlapp.Range("L" & row).Value = rs.Fields(11).Value xlapp.Range("M" & row).Value = rs.Fields(13).Value If CInt(rs.Fields(2).Value) = 1 Then row1 = row1 + 1 ElseIf CInt(rs.Fields(2).Value) = 2 Then row2 = row2 + 1 ElseIf CInt(rs.Fields(2).Value) = 3 Then row3 = row3 + 1 Else row4 = row4 + 1 End If 'activate main summary sheet for next outage xlapp.Worksheets(1).Activate i = i + 1 rs.MoveNext Loop` Also I should note that this is all happening within an access database which has its tables linked from SQL. The query is extremely slow to run from which I believe is the use of views but thats neither here nor there. All you have to know is attempting to debug takes an enormous amount of time due to having to wait for the recordset to return. My guess is that its not checking to see if the resultset is empty correctly. Is there a way I could check to see if theres a value is rs.Fields(0) and base it off that maybe? That is the ID column and there should always be a value. I am wondering why rs.EOF isn't catching this though.

    Read the article

  • django-admin formfield_for_* change default value per/depending on instance

    - by Nick Ma.
    Hi, I'm trying to change the default value of a foreignkey-formfield to set a Value of an other model depending on the logged in user. But I'm racking my brain on it... This: Changing ForeignKey’s defaults in admin site would an option to change the empty_label, but I need the default_value. #Now I tried the following without errors but it didn't had the desired effect: class EmployeeAdmin(admin.ModelAdmin): ... def formfield_for_foreignkey(self, db_field, request=None, **kwargs): formfields= super(EmployeeAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) if request.user.is_superuser: return formfields if db_field.name == "company": #This is the RELEVANT LINE kwargs["initial"] = request.user.default_company return db_field.formfield(**kwargs) admin.site.register(Employee, EmployeeAdmin) ################################################################## # REMAINING Setups if someone would like to know it but i think # irrelevant concerning the problem ################################################################## from django.contrib.auth.models import User, UserManager class CompanyUser(User): ... objects = UserManager() company = models.ManyToManyField(Company) default_company= models.ForeignKey(Company, related_name='default_company') #I registered the CompanyUser instead of the standard User, # thats all up and working ... class Employee(models.Model): company = models.ForeignKey(Company) ... Hint: kwargs["default"] ... doesn't exist. Thanks in advance, Nick

    Read the article

  • NLB and Host Header Value

    - by Hafeez
    Background: We are using MOSS 2007 in farm configuration, 2 WFE, 1 Indexer and SQL Server. MS NLB is used for load balancing. Host header value mapped to Virtual IP of Cluster in DNS, is used while creating the web applications in MOSS and all are sharing port 80. Problem: When client tries to access the web application that are configured with host header values. Both of WFEs Hangs for 5 minutes, they stop responding to ping and browser shows 'Page not found'. In the Application Log on the WFE, this error is registered "provider: TCP Provider, error: 0 - The semaphore timeout period has expired". Interestingly, the web application with no host header value and hosted on different ports is working correctly. Any clue to solve this problem will be helpful. Thks. Hafeez

    Read the article

  • Which syntax is better for return value?

    - by Omar Kooheji
    I've been doing a massive code review and one pattern I notice all over the place is this: public bool MethodName() { bool returnValue = false; if (expression) { // do something returnValue = MethodCall(); } else { // do something else returnValue = Expression; } return returnValue; } This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct? I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.

    Read the article

  • jQuery Validator's "required" not working when value is set at statup

    - by nandrew
    Hello, I have a problem with jQuery Validator. I want to use "required" property on a text input. It doesn't work when input has set value attribute by HTML code (tested on Firefox (3.5), and on IE 8 - on IE it works a bit better). Story: 1. Page loads; 2. value is cleared; 3. focus is changed. 4. Nothing happens but the error message should be displayed; 5. getting back to the field and typing some characters. 6. changing focus; 7. getting back to the field; 8. clearing the field. 9. Error is displayed even before leaving the field. The HTML code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <script src="Web/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="Web/Scripts/jquery.validate.js" type="text/javascript"></script> </head> <body> <form id="form1"> <input type="text" id="name1" name="name1" value="test" /><br /> <input type="text" /> </form> <script type="text/javascript"> $(document).ready(function() { var validator = $("form").validate({ rules: { name1: { required: true, minlength: 2 } }, messages: { name1: "bad name" }, }); }); </script> </body> </html>

    Read the article

  • Unexpected key-value behavior in a Core Data Context

    - by ????
    If I create an array of strings (via key-value coding) containing the names of a Managed Object entity's attributes which are stored in the App Delegate the first time, I get an array of NSStrings without any problems. If I subsequently make the same call later from the same entry point in code, that same collection becomes an array of NULL objects- even though nothing in the Core Data Context has changed. One unappealing work-around involves re-creating the string array every time, but I'm wondering if anyone has a guess as to what's happening behind the scenes. // Return an array of strings with the names of attributes the Activity entity - (NSArray *)activityAttributeNames { #pragma mark ALWAYS REFRESH THE ENTITY NAMES? //if (activityAttributeNames == nil) { // Create an entity pointer for Activity NSEntityDescription *entity = [NSEntityDescription entityForName:@"Activity" inManagedObjectContext:managedObjectContext]; NSArray *entityAttributeArray = [[NSArray alloc] initWithArray:[[entity attributesByName] allValues]]; // Extract the names of the attributes with Key-Value Coding activityAttributeNames = [entityAttributeArray valueForKeyPath:@"name"]; [entityAttributeArray release]; //} return activityAttributeNames; }

    Read the article

  • Creating an IF statement for datagrid value

    - by EvanRyan
    This is something I thought would be easier than it's turning out to be. For whatever reason, I can't seem to figure out a way to make what I'm trying to do here work with an If statement: List<int> miscTimes = new List<int>(); for (int i = 0; i < MISCdataGridView1.RowCount; i++) { if (MISCdataGridView1.Rows[i].Cells[2].Value == "Something") { miscTimes.Add(Convert.ToInt32(MISCdataGridView1.Rows[i].Cells[3].Value)); } } return miscTimes; For some reason, I can't get it to like anything I do with the if statement. I've tried converting to string and all of that. How should I go about this?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >