Hi, I have the following problem: I have a generic, which derives from a normal base class like this: public class MyClass : BaseClass { T m_Value; public SetValue(T val) { // ... } public T GetValue(){ ... } ; } These classes are stored in a generic dictionary, which is instantiated like this: dictionary dic = new dictionary(); At one point, I want to acess the SetValue Function, but I have to cast to the exact type, and typeof() / GetType doesn't works here. What I try to do looks similar like this, but I haven't a solution yet; MyClass< dic["Key"].GetType() > tC, tC2; tC.SetValue((dic["Key"].GetType())dic["Key"].GetValue()); This isn't correct (i left out the instantiation) , I know, but I need to cast at runtime to the exact generic type, stored at the position in the dictionary, for accessing the generic, type specific Get/Set function. Any comments ? Thanks, Florian
Florian Storck
Posts
-
Cast to a Generic Type at runtime -
FileNotFound Error when trying instantiate XMLSerializer with arrayOops,
try { if (m_dicXmlSerCache.ContainsKey(TObj)) { // m_Log.DebugFormat(" Serializer Cache Hit: Type {0}", TObj) m_dicCacheHits[TObj]++; // for statistic purposes return m_dicXmlSerCache[TObj]; } else { XmlSerializer tSer = new XmlSerializer(TObj); m_dicXmlSerCache.Add(TObj, tSer); // just for keeping track of some statistics m_dicCacheHits.Add(TObj, 1); tSer.UnknownAttribute += new XmlAttributeEventHandler(XML_UnknownAttribute); tSer.UnknownElement += new XmlElementEventHandler(XML_UnknownElement); tSer.UnknownNode += new XmlNodeEventHandler(XML_UnknownNode); tSer.UnreferencedObject += new UnreferencedObjectEventHandler(XML_UnreferencedObject); return tSer; } } catch (Exception e) { m_Log.ErrorFormat("Error in SerializerCache: {0}", e.Message); }
I didn't post the whole block. I think the handler are not the problem, this also happened before i wrote this cache object, which attached no handler at all. I also had the problem, that the try-catch didn't worked, only the VS handler shows up. But I have to access to the exception object there, so I can't check the inner exceptions. Something weird seems to happen here... Bye, Florian -
FileNotFound Error when trying instantiate XMLSerializer with arrayHello Marc, some other strange thing is, that the VisualStudio catches the Exception, but I don't get the Exception in my own exception handler. Even if I switch off all Exception in Debug->Exceptions in VS, the Exception handler isn't called.
if (m_dicXmlSerCache.ContainsKey(TObj)) { // m_Log.DebugFormat(" Serializer Cache Hit: Type {0}", TObj) m_dicCacheHits[TObj]++; // for statistic purposes return m_dicXmlSerCache[TObj]; } else { XmlSerializer tSer = new XmlSerializer(TObj); m_dicXmlSerCache.Add(TObj, tSer); // just for keeping track of some statistics m_dicCacheHits.Add(TObj, 1); tSer.UnknownAttribute += new XmlAttributeEventHandler(XML_UnknownAttribute); tSer.UnknownElement += new XmlElementEventHandler(XML_UnknownElement); tSer.UnknownNode += new XmlNodeEventHandler(XML_UnknownNode); tSer.UnreferencedObject += new UnreferencedObjectEventHandler(XML_UnreferencedObject); return tSer; } } catch (Exception e) { m_Log.ErrorFormat("Error in SerializerCache: {0}", e.Message); }
For explanation: This Code acts as a cache for various serializer objects, to avoid unnecessary instantiations. I've no real idea, why also my exception handler doesn't work here... Bye, Florian -
FileNotFound Error when trying instantiate XMLSerializer with arrayHi, I tried it in an completely empty project, and it doesn't happen there. So there seem to be some project dependencies...looks like I have to track it down there.. Florian
-
FileNotFound Error when trying instantiate XMLSerializer with arrayHi Marc, do you use .Net 2.0 ? Can you post a code example ? Maybe there are some prerequisites in my project causing this error. Thanks, Florian
-
FileNotFound Error when trying instantiate XMLSerializer with arrayHi, I'm currently stuck with the following problem:
XmlSerializer tSer = new XmlSerializer(typeof(Int16[]);
This generates an FileNotFound error. It's obviously an problem whith the OnTheFly generation of the serializer dlls and happens with each Array declaration at the moment. I found some stuff on the net dealing with this, but no real solution for my problem. I tried to track it down with the XMLPreCompiler, but until now with no success. The funny thing is, that this error seems only to happen on the first stage, as the array occurs in the written XML file. Does anybody have a clue, how to deal with Arrays and the .Net 2.0 XMLSerializer ? Thanks in advance, Florian -
XML Serialize / Deserialize generic dictionary holding various generic typesFor the interested ones, I found a solution:
Type t = Type.GetType(typestring); object o = Activator.CreateInstance(t);
This works, if you serialize the type on saving with GetType().ToString(). -
XML Serialize / Deserialize generic dictionary holding various generic typesHi, I'm kind of stuck with an serializing / deserializing problem using a generic dictionary holding references to various generic types. It goes as follows:
class MyBase : IXmlSerializable { // whatever } class MyGeneric : MyBase, IXmlSerializable { MyGeneric(Valuetype tVal) { val = tVal; } ValueType val; } class Program { dictionary m_Dic = new dictionary(); void FillDictionary() { dictionary.Add("Key1", new MyGeneric(10)); dictionary.Add("Key1", new MyGeneric("StringValue")); dictionary.Add("Key1", new MyGeneric(3.1415)); } }
Ok, I hope you can see the idea behind it. It's mainly thought to hold a variety of different types whithout specifying a parameter enum which selects the appropiate value via a huge switch statement on lots of overloads to the value Get/Set property. While I'm able to serialize the dictionary without a problem to an XML file, I'm stuck deserializing it. The problem: how can I can generate a generic from a textinformation like or MyApp.MyGeneric`1[System.String] ? The first classification is generated by the .Net serializer and the second is generated from typeof(...) . Any ideas are very appreciated. Thanks, Florian -
Generic MultiMap class / Set like the STL one... [modified]Hi, I'm looking for a generic version of a map container that acts similar like the multimap known from C++ / STL .
Dictionary map = new Dictionary(); map.Add("CATEGORY1", new myobject()); map.Add("CATEGORY1", new myobject(); // <-- this is not possible here, // because the Net 2.0 Dictionary only supports // unique keys.
It should support multiple objects per key. Does anybody have a good solution / code for this ? And by the way, I heard of STLNET ? But as I understood, this is only for C++ available ? Or does this work under C# ( I found no documentation abaout this so far). Thanks, Florian -- modified at 5:07 Monday 21st August, 2006 - no suggestions yet, no one missing STL ... ??? -
Define interface / abstract class with constructorHi Colin, thanks for your answer. By the way: do you have a certain style for naming abstract classes (probably ATest, I guess ;-) ). I didn't changed the name because I'm used to C++ were abstract classes and interfaces are handled the same way (I do C# programming for basically 5 months now) ... so this difference in naming makes only really sense (for me), if the abstract class implements things, so it's not completely abstract anymore... but ok, C# has the interface type/definition, then it makes probably more sense. Bye, Florian
-
Define interface / abstract class with constructorHello, I'm trying to to the following thing:
public abstract class ITest { public abstract ITest(string val); // causes error CS0106: The modifier 'abstract' is not valid for this item } public class Test : ITest { public Test(string val) // this constructor MUST be implemented { // by any inheriting classes // do something } }
Is there any possibility for defining abstract constructors ? Interfaces can't define constructors. It's not important because I realized that it is not necessary, but nevertheless it's an interesting question. thanks, Florian -
Firmware programming with C#Hi KiT, well, if you want to do embedded programming you shouldn't rely too much on the garbage collection, as you've usually very limited resources. So it's a great benefit knowing what is going on in the system and having everthying under control. Otherwise you may be in trouble with running out of resources. So it's very helpful to do some things the hard way, it's usually easier then being effective on managed languages as well. Bye, Florian
-
Using Custom Controls in Designer from .cs source filesHi Robert, if I click on the control sourcecode item ( e.g. Control.cs) i get a screen with the follwing text (window tab says "Control.cs [Design]": To add components to your class, drag them from the Toolbox and use the Properties window to set their properties. To create events for your class, click here to switch to code view. Well, that pretty obvious, but I have no idea how to convince the toolbox when editing a form to display the control which is only existing in sourcecode at that moment. Ok, it seems that the Control I use is not inherited from UserControl, so it may not work here. But you mean, if doubleclicking the sourcefile in the project should be enough if it is inherited from UserControl ? Thanks, Florian
-
Firmware programming with C#Hi KiT, do you want to program a firmware using C# or do you just want to acess functions using an existing SDK for your hardware ? Firmware Programming using C# doesn't works at the moment I suppose, because you would need a CLR (common language runtime) for your desired microcontroller. But the most microcontrollers have a C/C++ compiler generating native code, which can be executed by them, so I suppose you have at the least to use C/C++, which is very common in the embedded world (despite a few native java processors). Bye, Florian
-
Using Custom Controls in Designer from .cs source filesHi, I have the following problem when trying to use Custom Controls published here at CodeProject with the full source code: 1.) I add the control source to my project 2.) Project compiles, everythings fine. When I now want to add the control using the designer, I have to import it from the binary assembly the project has created ( so I'm referencing myself). Is there another way of registering in the toolbox just using the sourcecode ? Its a bit annoying, because I get a warning that I'm using a different type. The most ExampleProjects have all integrated, but don't reference the outputbinary for having designer support. I don't want to create a separate assembly containing all controls at the moment and I didn't found another solution yet. Many thanks, Florian
-
Equivalent of OLE_PropertyPageHi, I have a Dialog based Application and I want to achieve the following thing: I have a certain area described by a Panel and want to insert there several subforms according to a selected function. I tried to generate a Page as WinForm and set the Parent to the Panel Control, but this didn't worked out. How can I generate several subforms and display them in a clientarea in my main application form. In usual Win32/ATL this was done with OLE_PropertyPages. Is there any equivalent I'm missing at the moment ? Bye, Florian
-
Creating a Bitmap from IntPtr to unmanaged memory: issues [modified]Guffa wrote:
If you create a new blank Bitmap, you can use LockBits to pin the bitmap data and get a pointer to it. Could you use that with Marshal.Copy to copy the unmanaged data into the bitmap?
Ups, seems that my reply notification didn't worked... Meanwhile it seems to work using an IntPtr for initialising, but as far as I can see, the new instance allocates also memory, which is completetly unnecessary because the bitmap data are already in an unmanaged buffer, where the IntPtr points to. My initial idea was to avoid any copying issues for performance reasons and just define the bitmap format and set the pointer directly to the image data. This seems to be a lot more complicated used the managed environment. I'm not sure if it would work if the IntPtr would point to a managed location. Any suggestions are welcome. Bye, Florian
-
Instantiate Bitmap object from unmanaged memory/ Memory Allocation ? [modified]Hi, I'm struggling with the following problem: I have a large unmanaged buffer, allocated with VirtualAlloc for performmance reasons. I use this buffer to load prepared bitmap image data into it. For displaying, I tried to instantiate a bitmap object the following way:
// ButPtrStart points to an offset in my linear, unmanaged buffer. Bitmap bmp = new Bitmap(Width, Height, Width * 4, System.Drawing.Imaging.PixelFormat.Format32bppPArgb, new IntPtr((void*)BufPtrStart.ToPointer());
Usually, as I understood, creating a bitmap this way should not allocate any memory through the GC. But in my tests I found that memory is allocated anyway. Interestingly it isn't the size the bitmap has uncompressed in memory, but it is a significant amount. Does anybody have similar Effects and knows the cause ? Bye, Florian -- modified at 11:45 Wednesday 21st June, 2006 -
Direct instantiation of Bitmap from unsafe memoryHi there, I'm quite exhausted now trying to directly set the Scan0 Paramater of a Bitmap to avoid slow copying bitmaps in memory. Basically, I try to do the following: 1.) I have a buffer containing already loaded Bitmap files in memory. Fo r performance reasons, this buffer is allocated via VirtualAlloc and therefore unsafe. 2.) I'm passing a UnmanagedMemoryStream with a subportion of the buffer to my Drawing function, pointing to the beginning of the bitmap file. 3.) I'll try to instantiate a bitmap, using the Streampointer to use the buffer directly and draw it to the screen ( or better, a backbuffer). This looks like this:
// linear buffer containing bmp file unsafe { UnmanagedMemoryStream mstr= new UnmanagedMemoryStream((byte*)buf.ptrStart.ToPointer(), buf.Count, buf.Count, FileAccess.Read); } BitmapData bmd; BufferBitmap = new Bitmap(1920, 1080); ImageLockMode fLock = ImageLockMode.UserInputBuffer; // causes "Invalid Parameter" exception at the moment bmd = BufferBitmap.LockBits(new Rectangle(0,0,1920,1080), fLock,PixelFormat.Format24bppRgb); unsafe { bmd.Scan0 = new IntPtr(mstr.PositionPointer+14); } BufferBitmap.Unlock(bmd); GfxBuffer.Graphics.DrawImageUnscaled(BufferBitmap, new Point(0,0));
Well, all I get is a "Invalid Parameter" Exception when setting the LockBits with the UserInputBuffer Flag, or, if I use the ReadWrite Flag, I would probably have to use the buffer the Bitmapobject manages, which would be an unnecessary copy operation. I just want to display the bitmap I've already in memory which the smallest possible effort. Does anybody have an idea whats going wrong here ? According to some examples I found, it should work this way. Interestingly, even if a try to pass a buffer allocated with Marshal.AllocHGlobal the LockBits operation fails... The buffer contains valid data, because this code works, but I think, this causes every time an instantiation and copy procedure:// GfxBuffer.Graphics.DrawImageUnscaled(Bitmap.FromStream(mstr,false), new Point(0,0));
Bye, Florian -
Find unused source code using the debuggerHi, Alexander M. wrote: VS.NET does not need to detect unused routines because in release mode they are not included in the executable (removed by the linker). well, that's not my main problem. I want to use the information what is NOT compiled to do some refactoring and cleanup of the source code. Therefore it would be extremely useful to see all codelines marked, which are really existing in the binaries. Of course, this is just one small step into refactoring old code. Any tools or settings known to achieve this ? This was really nice in CBuilder. Bye, Florian