|
MadDashCoder wrote: In my test project my code does return a Toy object. Then the value in the setter would also be of type Toy . The only half sensible types to use would be object or string .
MadDashCoder wrote: This is just a test project to find out how I can use a single set property to change different properties using one LINQ Query. It's always going to be messy and I would avoid it unless there's some very compelling reason to do so.
Staying with your pseudo-code-style, it should look like this:
public object this[int toyId, string toyProperty]
{
get { return listOfProducts.Single(prod => prod.Id == toyId).toyProperty; }
set { listOfProducts.Single(prod => prod.Id == toyId).toyProperty = value; }
}
And to resolve the .toyProperty pseudo-code you would have to use reflection or reflection+expressions.
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
modified 17-May-16 17:18pm.
|
|
|
|
|
After thinking about this for a couple of minutes, the answer is "probably yes", but the code ends up being hideously complex because of other property types outside of the string case you're showing. You have to handle all possible types through reflection, even structures and class instances.
This isn't something I've done, nor want to because of time.
|
|
|
|
|
As the others have said, this is probably possible but almost certainly not advisable!
You would lose type safety and compile-time checking for correct property identification, etc.
Here are my initial thoughts on how I'd do this.
public class Toy
{
public Toy(int id)
{
ID = id;
}
public int ID { get; private set; }
public double Price { get; set; }
public string Color { get; set; }
}
public class Merchandise
{
public Dictionary<int, Toy> toys;
public Merchandise()
{
var toyList = new List<Toy>();
toyList.Add(new Toy {ID = 1, Price = 10, Color = "Red"});
toyList.Add(new Toy {ID = 2, Price = 10, Color = "White"});
toyList.Add(new Toy {ID = 3, Price = 10, Color = "Black"});
toys = toyList.ToDictionary(t => t.ID);
}
public string this[int toyId]
{
get
{
Toy theToy;
toys.TryGetValue(toyID, out theToy);
return theToy;
}
}
}
Then the usage is:
public double price = txtPrice.Text;
public string color = txtColor.Text;
public Merchandise item = new Merchandise();
item[2].Price = price;
item[2].Color = color;
Toy theToy = item[2];
if (theToy != null)
{
theToy.Price = price;
theToy.Color = color;
}
else
{
}
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
Thank all for your valuable inputs especially you Matt. The purpose of this project was just to explore how to dynamically choose a property to be inserted into a LINQ query at runtime. I've learned a lot from everyone's input.
I was able to do what I had originally set out to do using the code below although it is not as elegant as your solution.
public string this[int toyId, string price, string color]
{
get
{
string result = string.Empty;
if (color != null)
{
result = toyList.FirstOrDefault(toy => toy.ID == toyId).Color;
}
else if (price != null)
{
result = (toyList.FirstOrDefault(toy => toy.ID == toyId).Price).ToString();
}
return result;
}
set
{
if (color != null)
{
toyList.FirstOrDefault(toy => toy.ID == toyId).Color = value;
}
else if (price != null)
{
toyList.FirstOrDefault(toy => toy.ID == toyId).Price = Convert.ToDouble(value);
}
}
}
|
|
|
|
|
This still suffers from the problems that I mentioned.
It isn't even close to type-safe.
You'll get a NullReferenceException if the toyId isn't found, unless both price and color are null , in which case you'll never know!
For the "price" case, if the string is not a valid double , it will throw a FormatException (or, less likely, OverflowException ).
This is the wrong place in a design to be parsing the price value string to double !
It ought to be done as near as possible to where the user provides the input so it can be reported appropriately.
Finally, in fact, you did not "dynamically choose a property to be inserted into a LINQ query at runtime".
You're choosing different properties of the result of identical LINQ queries based on boolean conditions represented by string values being null or not.
I would consider this abuse of the indexer to gain a syntactic shortcut of very dubious value.
So lesson learned.
Don't do this in production code!
(Or any code! )
This is serious "code smell".
I'm sorry, but it needed to be said.
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
Restated another way, the question is how to update an existing item in a collection using LINQ:
List<Toy> toys = new List<Toy>();
toys.Add( new Toy() { Id = 1, Color = "Red", Price = 1.20M } );
toys.Add( new Toy() { Id = 2, Color = "Red", Price = 1.20M } );
toys.Add( new Toy() { Id = 3, Color = "Red", Price = 1.20M } );
toys.Single( o => o.Id == 2 ).Color = "Blue";
toys.Single( o => o.Id == 2 ).Price = 3.99M;
toys.ForEach( o => Console.WriteLine( $"{o.Id} {o.Color} {o.Price}" ) );
|
|
|
|
|
I want to know a process what file create or delete or change in Windows or what manipulte registry keys? Is it possible in c#? Please suggest me how I should do it? Give me example or useful link. Thanks
|
|
|
|
|
Start by studying, and experimenting with, the System.FileWatcher class in .NET: [^]
«There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008
|
|
|
|
|
Thanks. FileWatcher can catch registry keys?
|
|
|
|
|
saeedmir wrote: FileWatcher can catch registry keys? It does not, as the name already implies.
You can do that easily yourself; make a copy of the parts of the registry you want to monitor, let your foreign application run and modify away, take another snapshot of those registry-parts, and compare those two.
Good luck
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
|
Hello there. I am using FrameGrabber to get me the images which I then use in MainForm - 2 self developed classes. But it gives me the said exception. Here is the relevant code for both classes.
------------ FrameGrabber ----------------
static object m_obj = new object()
Bitmap CurrentBitmap = null;
public Bitmap CurrentFrame
{
get
{
Bitmap bmp = null;
try
{
lock (m_obj)
{
if (CurrentBitmap != null)
bmp = new Bitmap(CurrentBitmap);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bmp;
}
}
private void OnNewFrame(Frame frm)
{
Bitmap current_bitmap = new Bitmap(frm.Image);
lock (m_obj)
{
if (current_bitmap != null)
{
if (DateTime.Now.Subtract(LastFrameSendTime).TotalMilliseconds >= FrameDelay)
{
LastFrameSendTime = DateTime.Now;
CurrentBitmap = new Bitmap(current_bitmap);
}
}
}
}
And here is the code for MainForm .
------------ MainForm ----------------
bool isplaying = objFrameGrabber.Player.IsPlaying;
while ((isplaying))
{
Bitmap current_frame = objFrameGrabber.CurrentFrame;
while ((current_frame == null)
{
System.Threading.Thread.Sleep(10);
current_frame = objFrameGrabber.CurrentFrame;
}
picLiveVideo.Image = current_frame;
}
As you can see, I am using lock in FrameGrabber class. What could be wrong ? (I can provide full stack trace if needed) Thanks for any input.
|
|
|
|
|
Something that jumps out at me from your code is that you are creating an awful lot of Bitmaps, and not disposing of any of them. Bitmap wraps an unmanaged resource, so you should really get in the habit of releasing them.
This space for rent
|
|
|
|
|
(I'm not sure if this would be better asked in the COM forum... or QA...)
Is there a way to implement C#-implemented functionality via COM (for adding to legacy code) in such a way that I need build only an AnyCPU targeted dll that can then be used via COM either 32 or 64 bit?
================
Update May 18, 2016:
As it turns out, setting the build target to AnyCPU and selecting the "Register for COM interop" in the build settings does work. It appears to register the class in both HKCR and HKCR\Wow6432Node\CLSID (and the interfaces and type library in both, as well).
In my defense, this was originally written in C#, and the 32 bit COM requirement was added, so I first went down the explicit 32 bit COM path, and then I tried to add the 64 bit COM. If I had known about the COM up front I probably would have just done it this way in the first place.
And lest anyone blame the provider of the requirements...
I started this side project because I overheard coworkers discussing how to solve this conceptual issue and what they were thinking was only going to give the appearance of solving the issue. I thought that the correct solution shouldn't be difficult, so I started. When I told them what I'd accomplished, then they informed me of the COM requirement (for use by the legacy application).
================
I have a C# assembly that implements some functionality and it works fine when invoked from within C#.
There's one entry point class which implements the functionality, and exposes a support class's functionality via another interface.
Like:
public class DSS
{
public ITSF TSF { get; private set; }
}
public interface ITSF
{
string Prop1 { get; set; }
}
I have enabled COM using the [assembly: ComVisible(true)] in the AssemblyInfo.cs.
I then added [ComVisible(false)] for things I didn't want visible to COM. (Doing it the other way around didn't seem to do the "right thing".)
[ComVisible(false)]
public class DSS
{
public ITSF TSF { get; private set; }
}
[Guid("...")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITSF
{
string Prop1 { get; set; }
}
I wrote a separate class to wrap the entry point class, and it implements an interface to expose the functionality in a COM-friendly way. (I.e., different names for overloaded methods, ...)
It inherits from the DSS class.
Like:
[Guid("...")]
[ClassInterface(ClassInterfaceType.None)]
public class DSScom : DSS, IDSS
{
public ITSF TSF { get; private set; }
}
[Guid("...")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IDSS
{
ITSF TSF { get; }
}
I then added the "Register for COM interop" setting in the project properties.
So far, so good. This all builds. (Yes I needed to run Visual Studio 2013 as Administrator...)
Then I wanted to build for both 32 and 64 bit. (It isn't clear if the legacy application will be converted to 64 bit when it uses this via COM.)
So I added two additional build configurations (Debug32 and Release32) and set the Platform target to either 64 or 32 appropriate for the configurations.
Trying to build both configurations would fail, apparently when it was trying to unregister the previously registered, other size, dll, before registering what it had just built.
Side note: There are different versions of regasm.exe for 64 and 32. I managed to get this working, I think, by unchecking the "Register for COM interop" and adding a post-build step that registers the dll with the correct regasm.exe. At least, it doesn't fail and I think the registry info is correct. What's the easiest way to check both sizes of the COM implementation? Any suggestions?
So all of this seems to work but is there an easier way to do this so that I don't have to do all of the size-specific .BAT file PATH hackery and separate registrations? Is there a way to just build for AnyCPU, and register the COM to "just work" in 32 and/or 64 bit?
Thanks,
Matt
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
modified 18-May-16 12:50pm.
|
|
|
|
|
I think Ive seen two 'part solutions' to this,
- the first involved late loading with LoadLibrary from c# ...
- the second involved modify the dll search path using ? SetDllDirectory
Both techniques mean you had 32 and 64 bit builds of the assembly that used the COM library
I'll see what I can dredge up, Im interested in this myself
|
|
|
|
|
Garth, I think you misunderstood the issue.
I have a C# assembly that is exposing functionality via COM.
I will be using it both from a managed C# application
and a legacy application: old, unmanaged C++ that can't be wholesale ported. (But ought to be!)
I'd like to register a single AnyCPU dll so it can be used if the managed application is either 32 or 64 bit, as well as by the legacy app via COM.
I suppose I can only register the 32 bit COM, at least for now.
But can I do that with an AnyCPU dll, or do I still need to build two versions of the dll: 32 bit (==x86) for COM, and AnyCPU for managed app use?
"Fairy tales do not tell children the dragons exist. Children already know that dragons exist. Fairy tales tell children the dragons can be killed."
- G.K. Chesterton
|
|
|
|
|
|
Couple of problems here:
1) This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind.
At a guess, you are trying to write a "bible search" program - but that's all I get.
2) Don't post links to images: most people won't follow them because they have no idea what they will find on the other end. Describe your problem in detail instead. (This is a very worthwhile thing to do anyway: you frequently find the solution just by a process of meticulously documenting the problem!)
3) If you are going to post a link for people anywhere, make sure that anybody can open it. You link requires me to sign in as you in order to access the image...
4) Tell us what you have tried; where you are stuck; what help you need. Don't assume we know the context of your application, because we don't! And your app is probably in C# (or you wouldn't post here) but it could be webapp, website, winforms, WPF... it could use SQL Server, MySQL, SQLite, Access, XML, text, CSV ... we do not know. You need to tell us the relevant facts around your project in order to get a meaningful answer.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I just started learning about client server architecture. And I want to create client server application which can send request and receive response. Firstly I want to do communication between client server without any security. Later I want to add Open SSL to my application and check the security level. Is it possible? What is the best way or example to create Http client server application? Any suggestion or Help or reference?
|
|
|
|
|
This is not a question that can be easily answered in a technical forum; you should use Google to find samples of the various parts you are interested in. Here is one to get you started: HttpWebRequest/Response in a Nutshell - Part 1[^].
|
|
|
|
|
Hi, recetly, i found .net code .exe file can be decompile easily ,and other one can get your code in detail ,but my code has some secret,so i don't hope other one can decompile my code easily.
how can i do it?
|
|
|
|
|
You can't, and your code should not contain secrets.
You can make it "harder" to read by obfuscating it; that means that it will take me more time to read it.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
All security is really about is making something more difficult. The best you can hope for is to make the cost of acquisition higher than the value of acquisition.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
Nathan Minier wrote: The best you can hope for is to make the cost of acquisition higher than the value of acquisition. For a hobbyist, cost is zero; I can remember how many games were pirated, not too long ago - often within days of release, and that was usually not done using .NET reflection
Given the "genuine" application, I'd say that even Microsoft lost that battle.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
You can try various obfuscation tools that make your code much less readable; some of the expensive ones (and, I mean very expensive) claim to make it extremely hard to reverse-engineer code. But, all .NET apps are to a large extent accessible.
To really get security you need to use extra measures, which may include hardware dongles, or installation software that binds your app to machine specific identification and limits its use.
I suggest you start exploring some of these sites: [^].
«There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008
|
|
|
|
|