Search Results

Search found 36880 results on 1476 pages for 'value initialization'.

Page 8/1476 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Observing an NSMutableArray for insertion/removal

    - by Adam Ernst
    A class has a property (and instance var) of type NSMutableArray with synthesized accessors (via @property). If you observe this array using: [myObj addObserver:self forKeyPath:@"theArray" options:0 context:NULL]; And then insert an object in the array like this: [[myObj theArray] addObject:[NSString string]]; An observeValueForKeyPath... notification is not sent. However, the following does send the proper notification: [[myObj mutableArrayValueForKey:@"theArray"] addObject:[NSString string]]; This is because mutableArrayValueForKey returns a proxy object that takes care of notifying observers. But shouldn't the synthesized accessors automatically return such a proxy object? What's the proper way to work around this--should I write a custom accessor that just invokes [super mutableArrayValueForKey...]?

    Read the article

  • 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

  • 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

  • HP ACU shows parity initialization failed (with screenshot)

    - by lbanz
    I put in a new drive due to a hard drive failure. When the rebuild got to 100%, the controller fails and I need to reboot the server to bring it online. I had to do this about three times and it eventually finished rebuilding. But I found that it says parity initialization status failed. I've left it for a few hours but it didn't seem to reinitialize. Then I ran the insight online diagnostic tools and it reported the disk that I put in reached read/write error threshold. So I'm beginning to think that the brand new disk I put in is faulty. Before I put in the disk, the parity initialization was at a finished state. Should I replace the new disk I put in? I'm very worried as I think the parity is broken. Or is there a way to kick start the initialization process?

    Read the article

  • Parity Initialization after putting in two new disks

    - by lbanz
    All my firmware is up to date on the server and the controllers. Storage crashed over the weekend. I rebooted it and it detected that I put in two new disks last week (I did check that both disk completed the rebuilding process last week). After it booted into the OS I see that it gave me an information message. After 18 hours it is at 54% so it is looking healthy. But I need to replace 5 more disk in the msa. Should I wait for this message to finish before replacing more disks? 785 Background parity initialization is currently queued or in progress on Logical Drive 1 (15.0 TB, RAID 5). If background parity initialization is queued, it will start when I/O is performed on the drive. When background parity initialization completes, the performance of the logical drive will improve.

    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

  • Class initialization and synchronized class method

    - by nybon
    Hi there, In my application, there is a class like below: public class Client { public synchronized static print() { System.out.println("hello"); } static { doSomething(); // which will take some time to complete } } This class will be used in a multi thread environment, many threads may call the Client.print() method simultaneously. I wonder if there is any chance that thread-1 triggers the class initialization, and before the class initialization complete, thread-2 enters into print method and print out the "hello" string? I see this behavior in a production system (64 bit JVM + Windows 2008R2), however, I cannot reproduce this behavior with a simple program in any environments. In Java language spec, section 12.4.1 (http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html), it says: A class or interface type T will be initialized immediately before the first occurrence of any one of the following: T is a class and an instance of T is created. T is a class and a static method declared by T is invoked. A static field declared by T is assigned. A static field declared by T is used and the reference to the field is not a compile-time constant (§15.28). References to compile-time constants must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization. According to this paragraph, the class initialization will take place before the invocation of the static method, however, it is not clear if the class initialization need to be completed before the invocation of the static method. JVM should mandate the completion of class initialization before entering its static method according to my intuition, and some of my experiment supports my guess. However, I did see the opposite behavior in another environment. Can someone shed me some light on this? Any help is appreciated, thanks.

    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

  • Is it normal for C++ static initialization to appear twice in the same backtrace?

    - by Joseph Garvin
    I'm trying to debug a C++ program compiled with GCC that freezes at startup. GCC mutex protects function's static local variables, and it appears that waiting to acquire such a lock is why it freezes. How this happens is rather confusing. First module A's static initialization occurs (there are __static_init functions GCC invokes that are visible in the backtrace), which calls a function Foo(), that has a static local variable. The static local variable is an object who's constructor calls through several layers of functions, then suddenly the backtrace has a few ??'s, and then it's is in the static initialization of a second module B (the __static functions occur all over again), which then calls Foo(), but since Foo() never returned the first time the mutex on the local static variable is still set, and it locks. How can one static init trigger another? My first theory was shared libraries -- that module A would be calling some function in module B that would cause module B to load, thus triggering B's static init, but that doesn't appear to be the case. Module A doesn't use module B at all. So I have a second (and horrifying) guess. Say that: Module A uses some templated function or a function in a templated class, e.g. foo<int>::bar() Module B also uses foo<int>::bar() Module A doesn't depend on module B at all At link time, the linker has two instances of foo<int>::bar(), but this is OK because template functions are marked as weak symbols... At runtime, module A calls foo<int>::bar, and the static init of module B is triggered, even though module B doesn't depend on module A! Why? Because the linker decided to go with module B's instance of foo::bar instead of module A's instance at link time. Is this particular scenario valid? Or should one module's static init never trigger static init in another module?

    Read the article

  • Are there any guarantees in JLS about order of execution static initialization blocks?

    - by Roman
    I wonder if it's reliable to use a construction like: private static final Map<String, String> engMessages; private static final Map<String, String> rusMessages; static { engMessages = new HashMap<String, String> () {{ put ("msgname", "value"); }}; rusMessages = new HashMap<String, String> () {{ put ("msgname", "????????"); }}; } private static Map<String, String> msgSource; static { msgSource = engMessages; } public static String msg (String msgName) { return msgSource.get (msgName); } Is there a possibility that I'll get NullPointerException because msgSource initialization block will be executed before the block which initializes engMessages? (about why don't I do msgSource initialization at the end of upper init. block: just the matter of taste; I'll do so if the described construction is unreliable)

    Read the article

  • Are there any garanties in JLS about order of execution static initialization blocks?

    - by Roman
    I wonder if it's reliable to use a construction like: private static final Map<String, String> engMessages; private static final Map<String, String> rusMessages; static { engMessages = new HashMap<String, String> () {{ put ("msgname", "value"); }}; rusMessages = new HashMap<String, String> () {{ put ("msgname", "????????"); }}; } private static Map<String, String> msgSource; static { msgSource = engMessages; } public static String msg (String msgName) { return msgSource.get (msgName); } Is there a possibility that I'll get NullPointerException because msgSource initialization block will be executed before the block which initializes engMessages? (about why don't I do msgSource initialization at the end of upper init. block: just the matter of taste; I'll do so if the described construction is unreliable)

    Read the article

  • Is std::move really needed on initialization list of constructor for heavy members passed by value?

    - by PiotrNycz
    Recently I read an example from cppreference.../vector/emplace_back: struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "I am being constructed.\n"; } My question: is this std::move really needed? My point is that compiler sees that this p_name is not used in the body of constructor, so, maybe, there is some rule to use move semantics for it by default? That would be really annoying to add std::move on initialization list to every heavy member (like std::string, std::vector). Imagine hundreds of KLOC project written in C++03 - shall we add everywhere this std::move? This question: move-constructor-and-initialization-list answer says: As a golden rule, whenever you take something by rvalue reference, you need to use it inside std::move, and whenever you take something by universal reference (i.e. deduced templated type with &&), you need to use it inside std::forward But I am not sure: passing by value is rather not universal reference?

    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

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