Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
C

Clive D Pottinger

@Clive D Pottinger
About
Posts
51
Topics
17
Shares
0
Groups
0
Followers
0
Following
0

Posts

Recent Best Controversial

  • Sequence of events inside a stored procedure
    C Clive D Pottinger

    Thank you gentlemen. I found the cause of the issue. The section that reads

      PRINT 'copying order\_summary:';
          INSERT INTO order\_summary
          SELECT \[order\_num\],\[order\_date\], etc, etc, etc...
          FROM   sourcesummary
          WHERE  sourcesummary.order\_num = @orderNum;
    

    should have been

      PRINT 'copying order\_summary:';
          SET IDENTITY\_INSERT order\_summary ON;
          INSERT INTO order\_summary (\[order\_num\],\[order\_date\], etc, etc, etc...)
          SELECT \[order\_num\],\[order\_date\], etc, etc, etc...
          FROM   sourcesummary
          WHERE  sourcesummary.order\_num = @orderNum;
          SET IDENTITY\_INSERT order\_summary OFF;
    

    "... to become an SQL expert? Oh, I figure 3 or 4 days reading. A week tops!"

    Clive Pottinger Victoria, BC

    Database database sharepoint sysadmin hosting tools

  • Sequence of events inside a stored procedure
    C Clive D Pottinger

    Hello everyone. Everything I have read says that operations within a stored procedure are executed in the order in which they are encountered, and the semi-colons and BEGIN-END blocks can be used to ensure that statements are executed before subsequent statements are performed. However I am stumped by what is happening in my script. The intent of the script is to copy an order record and all associated table entries for the order from one database to another. I have stripped down the script code below to just the order table itself (and removed some passwords, server names etc). Here is the code:

    IF @@SERVERNAME <> 'Server1'
    BEGIN
    EXEC SP_ADDLINKEDSERVER
    'Server1'

      EXEC SP\_ADDLINKEDSRVLOGIN
        'Server1',
        'False',
        NULL,
        'userX',
        'passwordX'
    

    END

    go

    DECLARE @mode VARCHAR(1);
    DECLARE @orderNum INT;

    SET @orderNum = 1338464;
    SET @mode = 'R' -- set to 'R' for Report or 'U' for update
    BEGIN TRANSACTION

    DECLARE @sourceName VARCHAR(8);
    DECLARE @okay CHAR(1);
    DECLARE @user VARCHAR(20);

    SET @sourceName = 'liveDB';
    SET @user = SYSTEM_USER;

    CREATE synonym sourcesummary FOR [Server1].[liveDB].[dbo].[order_summary];
    SET @okay = 'Y'

    IF @okay = 'Y'
    AND @@SERVERNAME = 'Server1'
    BEGIN
    SELECT 'Cannot execute on live server - retry on the sever hosting the db that is to be copied to' [error]

      SET @okay = 'N'
    

    END

    IF @okay = 'Y'
    AND NOT EXISTS (SELECT order_num
    FROM sourcesummary
    WHERE order_num = @orderNum)
    BEGIN
    SELECT 'Unable to find order' [error],@sourceName [source db],@orderNum [order number];

      SET @okay = 'N';
    

    END

    IF @okay = 'Y'
    BEGIN
    IF EXISTS (SELECT order_num
    FROM order_summary
    WHERE ordr_num = @orderNum)
    BEGIN
    PRINT 'deleting order_summary:';

            DELETE order\_summary
            WHERE  order\_num = @orderNum;
        END
    
      BEGIN
    
      PRINT 'copying order\_summary:';
          INSERT INTO order\_summary
          SELECT \[order\_num\],\[order\_date\], etc, etc, etc...
          FROM   sourcesummary
          WHERE  sourcesummary.order\_num = @orderNum;
      END
    
      PRINT 'retreiving copied order\_summary:';
      SELECT 'copied' \[order\_summary\],\*
      FROM   order\_summary
      WHERE  order\_num = @orderNum;
    

    END

    DROP synonym sourcesummary;

    IF @mode = 'U'
    BEGIN
    COMMIT TRANSACTION

      SELECT 'Changes hav
    
    Database database sharepoint sysadmin hosting tools

  • Do you not understand booleans?
    C Clive D Pottinger

    I fully agree. This kind of stuff makes the code SO hard to read. And so many people do this too - just look at all the examples you were able to find! Atrocious. When will people learn to put spaces around their operators !?!?! :cool:

    Clive Pottinger Victoria, BC

    The Weird and The Wonderful data-structures question announcement

  • Finding a custom event using reflection
    C Clive D Pottinger

    Yup - that was it. embarassing... that's all I have to say... embarassing oh, and thanks. BTW: I find it interesting that the question from one C.D.P was answered by another C.D.P.

    Clive Pottinger Victoria, BC

    C# question

  • Circular dependency between classes
    C Clive D Pottinger

    I am by no means an expert, so don't take this answer as gospel. I am posting more to see if the gurus out there will correct any bad assumptions I have. As I believe: C++ is based on C. When C was created there was a need to keep compilers efficient - CPU time = $$$$. Therefore, the C language was designed with the idea that its compilers should not need to make multiple passes of the code. In a single-pass compiling strategy, you have to know what something is before you can use it. Hence procedures and variables had to be declared before they could be used. That led to the need for header files and forward declarations. I don't know if C++ compilers really need forward declarations, or whether it was just a carry over from C. But either way, this why I believe C++ has header files too. C# simply broke the tradition. If you allow your compiler to go over the code once and categorize the classes/methods/properties/fields and then go over it again to compile it, then there is no need for forward declaration, nor for header files. Am I way off base, Gurus?

    Clive Pottinger Victoria, BC

    C# database question csharp c++ help

  • Finding a custom event using reflection
    C Clive D Pottinger

    Whoa! :doh: I feel like I've just gone to the hospital to ask a surgeon why I keep getting headaches whenever I hit my head with a hammer. There should be a facepalm emoticon. Thanks guys. I'll apply your suggestion to the code tonight and see what happens.

    Clive Pottinger Victoria, BC

    C# question

  • Finding a custom event using reflection
    C Clive D Pottinger

    Hello Gurus. Yes, I've painted myself into yet another corner. It seems to be what I do best, so I guess I should stick with it. This time I am trying use reflection to find an event that I have attached to a class, but reflection is not showing the event. I don't know why. I have created a simple class called ListPicker that is based on the DomainUpDown control. It is supposed to act just like a DomainUpDown control, but it supports the Modified property and the ModifiedChanged events that DomainUpDown does not. Here is the code:

    using System;
    using System.Windows.Forms;

    namespace WindowsFormsControlLibrary
    {
    public partial class ListPicker : DomainUpDown
    {
    public EventHandler ModifiedChanged;

    	public ListPicker()
    	{
    		InitializeComponent();
    
    		// Register our TextChanged hander.
    		TextChanged += new EventHandler(ListPicker\_TextChanged);
    
    		Modified = false;
    	}
    
    	public bool Modified { get; set; }
    
    	public void ListPicker\_TextChanged(object sender, EventArgs args)
    	{
    		Modified = true;
    		OnModifiedChanged();
    	}
    
    	protected void OnModifiedChanged()
    	{
    		if (ModifiedChanged != null)
    		{
    			ModifiedChanged(this, null);
    		}				
    	}
    }
    

    }

    The Modified property works just as I wanted it to, and the ModifiedChanged event fires when it is supposed to, but when I use this code (where ctl is a reference to the ListPicker control)

    var x = ctl.GetType().GetEvents();
    var modifiedChangedEventInfo = ctl.GetType().GetEvent("ModifiedChanged");

    to look for the events on the ListPicker, it does not show the ModifiedChanged event. All the other DomainUpDown event show up in x, but not the ModifiedChanged event and modifiedChangedEventInfo is null Any ideas? ... and many thanks

    Clive Pottinger Victoria, BC

    C# question

  • Ambiguous constructor signatures?
    C Clive D Pottinger

    Thanks for the clarification, keefb.

    keefb wrote:

    If I understand you correctly, by passing the formula as a string will require the current class to be responsible for performing the parsing as well as whatever this class is meant to do with the result, this is probably bad object encapsulation.

    Agreed. But the class is not actually responsible for the parsing or evaluation (it passes those tasks off to another class), nor is it responsible for acting on the value. The class just holds on to expression tree created by parsing the formula and uses it to provide a value when requested. Perhaps my original example was over-simplified.

    keefb wrote:

    ...unless you are parsing text entries from a user or some other source (e.g. text input from a UI or file), writing formulas in strings and then evaluating them is bad design...

    This is exactly what I am doing. The formulas are read from user-created XML files and used to control the program's behaviour. This is fun... every criticism you offer just seems to confirm that I'm doing it correctly :laugh: . Keep going, keefb... one more critique should cement that I'm the bona fide genuis that I always knew myself to be:cool: (no matter what those jerks at Mensa had to say :mad:)

    Clive Pottinger Victoria, BC

    C# question help

  • Ambiguous constructor signatures?
    C Clive D Pottinger

    Thanks guys. That explains why it acts like it does.

    keefb wrote:

    The design in the OP needs refactoring [...] unless there is a specific reason for dealing with strings specifically.

    In the actual code MyClass is a class that represents some kind of value. The first ctor (MyClass(string initStr)) is used when the initStr holds a formula that needs to be parsed and evaluated to get the value. The second ctor (MyClass(G initVal, bool dummy)) is used when the value is already known, and does not need to be parsed or evaluated. The confusion arose, of course, when the value is a known string. I will take your recommendation to remove the first ctor into consideration, but at this point, I don't see a way for it work (is MyClass("foo()") a request for the string returned by foo or for the string "foo()"?). In the meantime, I will take it that my "workaround" is not wrong/dangerous/problematic/laughable. Thanks again.

    Clive Pottinger Victoria, BC

    C# question help

  • Ambiguous constructor signatures?
    C Clive D Pottinger

    Hello gurus and mavens! I haven't had to post any problems here in a while - which I take to be good sign for me. And this one isn't so much a "problem" as a "question". I thought the compiler would choke on the following code:

    namespace ConsoleApplication1
    {
    public class MyClass<G>
    {
    private G Val;

        public MyClass(string initStr)
        {
            if (initStr == "bad init string")
                throw new ApplicationException("You can't do that!");
            Val = default(G);
        }
    
        public MyClass(G initVal)
        {
            Val = initVal;
        }
    }
        
    class Program
    {
        static void Main(string\[\] args)
        {
            MyClass<int> example1 = new MyClass<int>("test"); // use the first constructor
            MyClass<int> example2 = new MyClass<int>(1);      // use the second constructor
    
            MyClass<string> example3 = new MyClass<string>("what happens here?"); // I want the second constructor
        }
    }
    

    }

    and tell me that it did not know which constructor to use with example3 since both constructors for MyClass would accept a string. But it didn't! Instead it just elects to use the constructor with the parameter of type string. Not what I expected, and not what I wanted. To get around this, I changed the second constructor to

    public MyClass(G initVal, bool dummy)

    and the call to

    MyClass<string> example3 = new MyClass<string>("what happens here?", true);

    just to make it clear that I want to use the second constructor. My question is this: is there a better way to handle this that I am not aware of? Is there some hidden option or obscure construct that makes sense of ambiguous constructor signatures? Many thanks,

    Clive Pottinger Victoria, BC

    C# question help

  • Deserialising derived classes using XmlAttributeOverrides
    C Clive D Pottinger

    Henry Minute wrote:

    Yeah, and you've misspelled hittythingy, as well!! Big Grin

    I checked AskOford.com first - but appearently, it is not a term in common usage in England. So I was left to guess. :-O I have corrected my code ;)

    Clive Pottinger Victoria, BC

    C# xml tutorial csharp database linq

  • Deserialising derived classes using XmlAttributeOverrides
    C Clive D Pottinger

    Thanks Navaneeth. To answer point about where the XmlSerializer was getting my XmlAttributesOverrides object: the idea was to have the Orchestra class deserialise each <bloweythingy> and <hittythingy> tag as it encountered them. To do this Orchestra implement IXmlSerializable and the deserialisation was done inside the ReadXml() method. So the XmlAttributeOverrides were being assigned to the XmlSerializer ts in the Orchestra class, not the iniSerializer in Main. That was the idea. But after carefully examining the example you linked to, I now realise my mistake: I misunderstood the meaning of each parameter in the XmlAttributeOverrides.Add() method. I had written

    instrumentXmlOverrides.Add(typeof(Instrument), kvp.Value.Name, xa);
    = when told to deserialise an Instrument [parm 1], if you run across a <bloweythingy> tag [parm2] apply the rules in xa (deserialise the <bloweythingy> tags into Woodwinds) [parm 3]

    I thought the first 2 parms were the class being deserialised and the "alternate" tagname for that class (Instrument and <bloweythingy>). In reality they are the class being deserialised and the tagname/class name of a property of that class. I should have been trying do this:

    instrumentXmlOverrides.Add(typeof(Orchestra), "Instrument", xa);
    = when told to deserialise an Orchestra [parm 1], where you would normally expect an Instrument tag [parm2] apply the rules in xa (which should include both alternate tagnames for Instrument [bloweythingy and hittythingy] and their classes [Woodwinds and Percussion]) [parm 3]

    In order to do that, I had to reorganise my code so that the overrides were all constructed before ever trying to deserialise Orchestra. That allowed me to remove the IXmlSerializable interface from Orchestra and simplify the code. Thanks again, Navaneeth. I can now move ahead with the actual application I am writing.

    Clive Pottinger Victoria, BC

    C# xml tutorial csharp database linq

  • Deserialising derived classes using XmlAttributeOverrides
    C Clive D Pottinger

    Hello again. I've painted myself into a corner once more - this time with a different colour of paint! I am trying to understand how to use XmlAttributeOverrides() to control the deserialisation of an XML file, but I can't seem to figure out how to tell it what I want to do. I have created a running example. Using this XML:

    <?xml version="1.0" encoding="utf-8"?>
    <orchestra>
    <bloweythingy name="flute" reed="false"/>
    <bloweythingy name="oboe" reed="true"/>
    <hitythingy name="tympani" keys="false"/>
    <hitythingy name="piano" keys="true"/>
    </orchestra>

    I would like to create an Orchestra object that contains 2 objects of class Woodwind (representing the contents of the bloweything elements) and 2 of class Percussion (representing hitythingy content). Both Woodwind and Percussion are derived from class Instrument. Additionally, I would like to do this without decorating the classes with [XmlElement] attributes so that, later on, I will be able to programatically add new Instrument types. To do this, I created a "registry" to which the code will be able to add an XML tag name and the class to be used to represent the data in that tag. Eventually, the registry will cache the XmlSerializer objects to be used with each tag... but for now the serialisers are created on the fly. Here is the code to try and do this:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;

    namespace Deserialising
    {
    class ExampleA
    {
    static void Main(string[] args)
    {
    XmlSerializer iniSerializer = new XmlSerializer(typeof(Orchestra));
    TextReader iniReader = new StreamReader("C:\\Temp\\ExampleOrchestra.xml");
    try
    {
    Orchestra DuchyOfGrandFenwickPhilharmonic = (Orchestra)iniSerializer.Deserialize(iniReader);
    }
    catch (Exception ex)
    {
    while (ex != null)
    {
    Console.WriteLine(ex.Message);
    ex = ex.InnerException;
    }
    Console.ReadKey();
    }
    iniReader.Close();
    }
    }

    \[XmlRoot("orchestra")\]
    public class Orc
    
    C# xml tutorial csharp database linq

  • XML Deserialisation to an inherited class type based on an XML attribute
    C Clive D Pottinger

    Perhaps I need to clarify further. I would like to deserialise this XML

    <fleet>
    <auto type="car">boss's limo</auto>
    <auto type="truck"/>delivery truck</auto>
    <auto type="car">employee's rusty corvair</auto>
    </fleet>

    into these classes

    public class AutoClass { ... }

    [XmlRoot("fleet")]
    public class FleetClass
    {
    [XmlElement("auto")
    public AutoClass[] Vehicles { ... }
    }
    public class CarClass : AutoClass { ... }
    public class TruckClass : AutoClass { ... }

    so that

    XmlSerializer s = new XmlSerializer( typeof( FleetClass ) );
    TextReader r = new StreamReader( "example.xml" );
    FleetClass myFleet = (FleetClass)s.Deserialize( r );
    AutoClass[] myVehicles = myFleet.Vehicles;

    should result in myVehicles containing 2 objects of type CarClass and 1 object of type TruckClass - not 3 objects of type AutoClass. Edit: I know I could change the <auto> tags to <car> and <truck> and collect them in the Vehicles property - but that is not the goal. The XML tag should remain as <auto> but the objects created need to be of types CarClass and TruckClass. Is there any way to decorate the classes and properties to accomplish this?

    Clive Pottinger Victoria, BC

    modified on Thursday, July 23, 2009 12:11 PM

    C# question xml help tutorial announcement

  • XML Deserialisation to an inherited class type based on an XML attribute
    C Clive D Pottinger

    Thanks for the speedy reply. However, I don't see how the XSD tool will help in this case. From the documentation here (http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.80).aspx) it seems that the tool will simply generate code for classes based on the XML elements found. I don't see how to use it to generate a class based on an XML element's attribute.

    Clive Pottinger Victoria, BC

    C# question xml help tutorial announcement

  • XML Deserialisation to an inherited class type based on an XML attribute
    C Clive D Pottinger

    Hi folks. This is probably a simple one for the XML gurus, but it has me stumped. I am trying deserialise an XML file, which is easy enough. But now I need to create objects based on an XML element's attribute, and I can't see how to do it. Here is a simplified version of the problem. I started with a file that looks like this:

    <fleet>
    <auto>boss's limo</auto>
    <auto<delivery truck</auto>
    <auto<employee's rusty corvair</auto>
    </fleet>

    Easy enough to deserialise:

    public class AutoClass { ... }

    [XmlRoot("fleet")]
    public class FleetClass
    {
    [XmlElement("auto")
    public AutoClass[] Vehicles { ... }
    }

    But now, I need to change the classes around. I need a CarClass and TruckClass that inherit from AutoClass. So I created:

    public class CarClass : AutoClass { ... }
    public class TruckClass : AutoClass { ... }

    Additionally, the file should look like this

    <fleet>
    <auto type="car">boss's limo</auto>
    <auto type="truck"/>delivery truck</auto>
    <auto type="car">employee's rusty corvair</auto>
    </fleet>

    But the Vehicles property generates AutoClass objects and I need the results to be of type CarClass and TruckClass. I can't downcast Vehicles[0] to CarClass (or can I?). How do I get Vehicles to examine the type attribute of the auto element and create 2 CarClass objects and one TruckClass? I hope that is clear - if not, let me know.

    Clive Pottinger Victoria, BC

    C# question xml help tutorial announcement

  • Overriding a Dictionary's Item property
    C Clive D Pottinger

    Thank you too, Mika

    Clive Pottinger Victoria, BC

    C# help com tutorial

  • Overriding a Dictionary's Item property
    C Clive D Pottinger

    Thank you Mike - exactly the syntax I needed. Now I can hang from ceiling and continue painting the floor...

    Clive Pottinger Victoria, BC

    C# help com tutorial

  • Overriding a Dictionary's Item property
    C Clive D Pottinger

    sorry. The definition of DataImage should say "string,string", but the display is dropping the second "string". And for some reason, I can't get in to edit to the message.

    Clive Pottinger Victoria, BC

    C# help com tutorial

  • Overriding a Dictionary's Item property
    C Clive D Pottinger

    Hello TCP gurus! It's me again, standing in a the corner of a room with wet paint all around me.... Any help would be appreciated. I have a dictionary

    public class DataImage : Dictionary<string,>

    which has been working wonderfully for me. But now I find that when I have a problem when adding values using the Item property.

    DataImage<string,> modImage = new DataImage<string,>();
    ...
    modImage["xxx"] = "yyy";

    I need to have some additional actions occur. In particular, DataImage contains some private data that needs to be updated whenever an element is added or removed. I have the required code in the Add() and Remove() methods, but I also need that logic to occur when the dictionary is accessed using its Item property. I would like to do something akin to

    public override string Item[key]
    {
    get { return base[key]; }
    set
    {
    base[key] = value;
    changeOtherStuff(key, value);
    }
    }

    I looked at this page (http://msdn.microsoft.com/en-us/library/9tee9ht2.aspx[^]), but couldn't see how to write the necessary code from it. I also searched online, but to no avail.

    Clive Pottinger Victoria, BC

    C# help com tutorial
  • Login

  • Don't have an account? Register

  • Login or register to search.
  • First post
    Last post
0
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups