|
I didn't make a question.
I just would like to arrange that WeakClone has some problem and Why DeepClone needs.
Brad
You go, we go~.
|
|
|
|
|
When you clone using Memberwise Clone, it creates a "shallow copy:" any internal fields in the cloned object that you don't set explicitly retain their value: for a cloned generic List that value is a reference: change that reference, and you change its value in any object that has a reference to it.
To make your code work: initialize the List in the MyClass constructor; and, in the Clone method initialize the cloned reference List. This is a bit tricky, and I suggest you spend some time carefully studying the examples here: [^]
public class MyClass : ICloneable
{
public string Name { get; set; }
public string Value { get; set; }
public List<string> Lists;
public MyClass()
{
Lists = new List<string>() { "A", "B", "C" };
}
public MyClass Clone()
{
var clone = this.MemberwiseClone() as MyClass;
clone.Lists = new List<string>();
return clone;
}
object ICloneable.Clone()
{
return this.MemberwiseClone();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Name={0}, ", Name);
sb.AppendFormat("Value={0}, ", Value);
sb.Append("Lists=");
bool b = false;
foreach (var item in Lists)
{
if (b)
sb.AppendFormat("|{0}", item);
else
sb.AppendFormat("{0}", item); b = true;
}
return sb.ToString();
}
}
«Differences between Big-Endians, who broke eggs at the larger end, and Little-Endians gave rise to six rebellions: one Emperor lost his life, another his crown. The Lilliputian religion says an egg should be broken on the convenient end, which is now interpreted by the Lilliputians as the smaller end. Big-Endians gained favor in Blefuscu.» J. Swift, 'Gulliver's Travels,' 1726CE
|
|
|
|
|
Good Idea. Even WeakClone we could use safly without DeepClone.
Brad
You go, we go~.
|
|
|
|
|
The task of deep cloning a .NET object is the subject of numerous articles, and some open source libraries; techniques used include serialization, reflection, and some very esoteric stuff:
CP 2017: [^] this prize-winning article contains a good overview of the different possible techniques.
GitHub: [^] reflection, [^] serialization
cheers, Bill
«Differences between Big-Endians, who broke eggs at the larger end, and Little-Endians gave rise to six rebellions: one Emperor lost his life, another his crown. The Lilliputian religion says an egg should be broken on the convenient end, which is now interpreted by the Lilliputians as the smaller end. Big-Endians gained favor in Blefuscu.» J. Swift, 'Gulliver's Travels,' 1726CE
|
|
|
|
|
I am using VS 2015 with .Net framework 5.2.1 and winforms. The rich text box calls are making the application crash intermittently
with System.AccessViolationException:
At the bottom there is error from Event Viewer and it seems it is crashing while setting Selection start. I set Selection start at two
places in my code. The crash is intermittent. I will really appreciate any pointers.
1) While scrolling it to the bottom:
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
2) while appending text to the richtextbox:
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
}
EventViewer:
Application: AutomationHost.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.NativeWindow.DefWndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control.DefWndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.TextBoxBase.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.RichTextBox.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control+ControlNativeWindow.OnMessage(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control+ControlNativeWindow.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.UnsafeNativeMethods.SendMessage(System.Runtime.InteropServices.HandleRef, Int32, Int32, EDITSTREAM)
at System.Windows.Forms.RichTextBox.StreamOut(System.IO.Stream, Int32, Boolean)
at System.Windows.Forms.RichTextBox.StreamOut(Int32)
at System.Windows.Forms.RichTextBox.get_SelectedText()
at System.Windows.Forms.RichTextBox.get_SelectionLength()
at System.Windows.Forms.TextBoxBase.set_SelectionStart(Int32)
at AutomationHostHelper.Test.ThreadSafeRichTextBox()
Exception Info: System.Reflection.TargetInvocationException
at System.RuntimeMethodHandle.InvokeMethod(System.Object, System.Object[], System.Signature, Boolean)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(System.Object, System.Object[], System.Object[])
at System.Delegate.DynamicInvokeImpl(System.Object[])
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback,
System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object,
Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.TextBoxBase.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.RichTextBox.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control+ControlNativeWindow.OnMessage(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control+ControlNativeWindow.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG ByRef)
at System.Windows.Forms.Application
+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application.Run(System.Windows.Forms.Form)
at AutomationHost.Program.Main(System.String[])
|
|
|
|
|
public static void AppendText(this RichTextBox box, string text, Color color)
at AutomationHostHelper.Test.ThreadSafeRichTextBox() Are you calling those functions from a different thread?
Then that might be the reason. I don't know enough about thread safety of C# controls to help you but other's might know.
|
|
|
|
|
My host:
IP: 192.168.28.143
Mask: 255.255.254.0
Default gateway: 192.168.28.1
Target IP: 192.168.4.93
My IP and target IP are both working PC in my company.
I want get host name of target IP.
string name = Dns.GetHostEntry("192.168.4.93").HostName;
But it failed.
If I get same segment IP hostname, e.g.
string name = Dns.GetHostEntry("192.168.28.121").HostName;
It successfull.
My question is:
How to get host name of target IP successfull?
Use .Net method.
|
|
|
|
|
The only solution I know would be having the IP address of the local DNS server for the other segment (if there is any but it is usually on the gateway for that segment). Than you have to query that DNS server which requires a DNS client library that allows specifying the server(s) to be queried because the .NET Dns class uses only the servers from Windows configuration.
But even that might not work when denied by firewalls or your gateway has no route to the other network segment.
The problem is that all your addresses are local (reserved). Those can be only resolved by DNS when there is a DNS server for the local network segment. This is usually the gateway system (e.g. a router). There are also some fallback methods like the /etc/hosts file and SMB/CIFS name resolution with Windows. But those will work again only for the local network segment.
|
|
|
|
|
You need to talk to your SysAdmins and determine how DNS is provided within your environment. Until you know that you will be shooting in the dark.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
maybe this code will help
string ip = "192.168.1.5";
Ping myPing = new Ping();
PingReply reply = myPing.Send(ip);
if (reply.Status == IPStatus.Success)
{
try
{
IPAddress ipAddres = IPAddress.Parse(ip);
IPHostEntry host = Dns.GetHostEntry(ipAddres);
Console.WriteLine(host.HostName.ToString());
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
|
|
|
|
|
Hi all,
i am trying to expose C# object to COM and in this process i got a query and not sure how to progress further. so here i am seeking for help.
i want to define a interface in C# in such a way the consumer of the COM object should be able to use the method in the following way.
comObject.methodName(123)
the above statement will return a value, assume where 123 is the parameter which could id or some thing like that
comObject.methodName(123) = 100
the above statement should set the value 100 something internal member having id 123
in both the above statement the methodName is the same.
so the question is how can we define an interface in C# that can be exposed to COM using regasm.exe.
i know it is possible to define such a way in C++ using ATL but not sure how can i achieve the same in C#.
[Comvisible(true)]
interface ExposeToCom
{
// don't know what all to add to make the method appear to COM to be get and set
int methodName(int);
}
Thanks for your help,
|
|
|
|
|
|
You are use a method as if it was a property . You cannot assign a value to a function!
Rather think of comObject.methodName(123, 100) , i.e. a function with 2 parameters (key and value ).
|
|
|
|
|
Thanks for your response.
Actually, i am trying re-write a COM component developed in ATL which is production. i want to give the same interface so that consumer has minimal impact.
code snippet from my existence code.
STDMETHOD(get_methodA)( VARIANT storeID, VARIANT *pVal);
STDMETHOD(put_methodA)( VARIANT storeID, VARIANT newVal);
STDMETHOD(get_methodB)( VARIANT storeID, VARIANT index, VARIANT *pVal);
STDMETHOD(put_methodB)( VARIANT storeID, VARIANT index, VARIANT newVal);
when i extract the typelib for this
[id(0x00000001), propget, helpstring("property methodA")]
HRESULT methodA([in] VARIANT storeID, [out, retval] VARIANT* pVal);
[id(0x00000001), propput, helpstring("property methodA")]
HRESULT methodA([in] VARIANT storeID, [in] VARIANT pVal);
[id(0x00000004), propget, helpstring("property methodB")]
HRESULT methodB([in] VARIANT storeID, [in] VARIANT index, [out, retval] VARIANT* pVal);
[id(0x00000004), propput, helpstring("property methodB")]
HRESULT methodB([in] VARIANT storeID, [in] VARIANT index, [in] VARIANT pVal);
so the consumer can use as
methodA(123) -- return a value
methodA(123) = 100 -- this will set a value
methodB(123, 3) -- return a value
methodB(123, 3) = 100 -- this will set a value.
i am trying to mimic the same methods defined in my ATL in a C# interface and use .net com interoperability using a regasm.
i am not able to find out how achieve this in C#. if this is done in ATL i was thinking there could be a way to achieve this.
thanks for your time
modified 27-Jul-17 13:36pm.
|
|
|
|
|
If you have a type library, you can convert it into a .NET assembly using tlbimp.
This space for rent
|
|
|
|
|
Not sure, but I believe you have to turn on this feature in the AssemblyInfo page. Then, you have to put it on the Type you want to make visible.
Ben Scharbach
Temporalwars.Com
YouTube:Ben Scharbach
|
|
|
|
|
Hi,
I was looking for some guidance on best practices regarding error handling.
public class DemoController : Controller
{
private readonly ILogger _logger;
public DemoController(ILogger logger)
{
_logger = logger;
}
public ActionResult Index()
{
try
{
}
catch (Exception ex)
{
_logger.Error(ex.ToString());
}
return View();
}
}
I was therefore wondering if anyone would have any suggestions to improve this code?
Thanks
The Dark Knight
modified 26-Jul-17 16:34pm.
|
|
|
|
|
Ask the person who told you it was sub-standard what their issues are. They could be referring to the fact that catching just "Exception" is too generic, that you should aim for specific exceptions (that rarely happens in the real world though). Or it could be the fact that you just log the exception and do nothing with it, you go on to return the View as normal so the user has no real knowledge that the code failed.
|
|
|
|
|
Thanks, makes more sense to me now.
Paul McGann
|
|
|
|
|
It's usually good practice to inform the user that an error occurred, and therefore the output might not be trustworthy or the input was not accepted by the system.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
Thanks Benjamin, i'll keep this in mind for future.
Paul McGann
|
|
|
|
|
The "best wisdom" I have found re error-handling is in the writings of Eric Lippert, a key .NET architect: his "classic" piece often cited by other language gurus: [^].
Also: [^], [^].
A summary based on Eric's writings: [^].
There's a 3 part series on "Dr. Spock Engineer" blog I think is worth studying that starts here: [^].
I favor always throwing an Exception except in very special cases like within an enumeration of data where partial results are acceptable and usable.
«Differences between Big-Endians, who broke eggs at the larger end, and Little-Endians gave rise to six rebellions: one Emperor lost his life, another his crown. The Lilliputian religion says an egg should be broken on the convenient end, which is now interpreted by the Lilliputians as the smaller end. Big-Endians gained favor in Blefuscu.» J. Swift, 'Gulliver's Travels,' 1726CE
|
|
|
|
|
Thanks Bill, great articles and advice appreciate everyone's feedback.
Paul McGann
|
|
|
|
|
Logging the exception is useful, but I would recommend also throwing (not rethrowing) it. What I mean is:
try {
DoSomething();
}
catch (Exception ex) {
this._logger.Log(ex);
throw;
}
/ravi
|
|
|
|
|
Yes, instead of writing the same old boiler-code (as they call it), I would use PostSharp to create code-injection attributes which would automatically wrap the method with your try-catch{} exception-logger. This reduces the redundant code and improves the visibility of your class code.
Ben Scharbach
Temporalwars.Com
YouTube:Ben Scharbach
|
|
|
|
|