|
You changed the _Name field of a temporary object that is immediately lost.
Solution: delete all of "Apple a = new Apple(); a."
You want to change the name of the thing itself, right? But now you make a second apple, change its name, and then throw it away.
|
|
|
|
|
Thanks Harold, you have clarified what Ravi referred to when he suggested the 'this' keyword.
I realise now instead of working with the class I'm in I'm creating a new instance which is then disposed of when I leave the method.
Once again its easy when you know how!
Thanks for your time
|
|
|
|
|
|
Can you edit you post and put the code between it in <pre> </pre> tags please, this will make it more readable:
public void Start(object sender, EventArgs e)
{
Apple a1 = new Apple();
a1.runApple();
txtOuput.Text = a1.Name;
}
The problem is that the RunApple method creates a new instance of Apple , change it to this instead:
public void runApple()
{
Name = "Apple";
}
This sets the name property of the instance of Apple it is running in.
A Few other points, fieldnames should start in lowercase e.g. string _name and method names should start uppercase e.g. RunApple . Finally, RunApple isn't a good name, Initialise Might be better, or better yet move Name = "Apple"; into the Apple constructor.
Dalek Dave: There are many words that some find offensive, Homosexuality, Alcoholism, Religion, Visual Basic, Manchester United, Butter.
Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.
|
|
|
|
|
Done. i will remember the pre tags in future, thanks
|
|
|
|
|
I think the other answers have addressed the answer to your question. However, based on my experience, I think I can guess your goal for this particular thought exercise and that is that each fruit would return it's correct name. For this you can delve into some more complicated OO concepts that will give you the result.
public abstract class Fruit{
protected abstract string GetFruitName();
public string Name{
get{
return GetFruitName();
}
}
}
public class Apple : Fruit{
protected override string GetFruitName(){
return "Apple";
}
}
|
|
|
|
|
Just wondering - why wouldn't you do that "directly" by making the property virtual (and overriding it) ? What's the benefit of doing it like this?
|
|
|
|
|
Actually guys you are both kind of on the right track.
The purpose is eventually to have a virtual method eg GetDefaults, then instead of analysing the type of objec or being specific I can pass a fruitbase object into the virtual method and it should implicitly choose the correct fruit class.
Thats what i'm building up to in an attempt to understand the virtual keyword.
|
|
|
|
|
It demonstrates three concepts instead of just one. Also, virtual indicates optional whereas abstract would be required.
|
|
|
|
|
Hi Guys,
I am coding a tool using C# 2005. I want to show a tooltip when the mouse is moving into a button.
I can do this in case click on the button. I show my code below:
private void btmInsertFromDate_Click(object sender, EventArgs e)
{
ToolTip tooltip1 = new ToolTip();
tooltip1.Show(btmInsertDateTo.Text, this, 158,69, 1000);
}
Need your guide.
|
|
|
|
|
You need to bind your tooltip on load event of your tool.
Like this
ToolTip1.SetToolTip(btnCustomerSearch, "Click here to search Customers.");
The tooltip is always shown on mousehover event.
It is automatically shown when you hover mouse on the button
"btnCustomerSearch".
HTH
Jinal Desai - LIVE
Experience is mother of sage....
|
|
|
|
|
Thank you very much for your guide.
Undynamicmagic
|
|
|
|
|
Hi All,
I have five web sites on my IIS 6.0 server. All but one of them (the one I am trying to change) is set to use ASP.NET 2.0. I changed one of my sites to use ASP.NET 4.0.30319.0. Now when I run this site I get get "Server Application Unavailable" and I get an application error (in my system event log) that says,
It is not possible to run two different versions of ASP.NET in the same IIS process. Please use the IIS Administration Tool to reconfigure your server to run the application in a separate process.
How do I fix this? Thanks for any help.
Please advice
Thanks
modified on Wednesday, June 30, 2010 11:54 AM
|
|
|
|
|
I have an C++ DLL to communicate with an intercom using TCP/IP. I have wrapped it using C#. Here are (some of) the declarations of the wrapper:
namespace TalkMasterLib
{
public static class TalkMaster
{
#region Callback Delegate
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CallbackFunc(int EventID, int Socket, IComData IData, IntPtr EventData, IntPtr UserData);
#endregion
#region Imported DLL Functions
// Check & Correct Marshalling on all Functions! AKA 20100624
[DllImport("DAPassThru", CharSet=CharSet.Auto)]
public unsafe static extern int DAOpen(
ref IntPtr DLLHandle,
ref IntPtr Flags,
CallbackFunc Callback,
IntPtr UserData);
[DllImport("DAPassThru", CharSet = CharSet.Auto)]
public unsafe static extern int DAClose(IntPtr DLLHandle);
[DllImport("DAPassThru", CharSet = CharSet.Auto)]
public unsafe static extern int DAStart(
IntPtr DLLHandle,
ref SockAddr_in SocketAddr,
int ThreadPriorty,
string UnknownName,
string Password,
string UserName,
IntPtr UserData);
[DllImport("DAPassThru", CharSet = CharSet.Auto)]
public unsafe static extern int DAStop(IntPtr DLLHandle);
….
}
I also use the following struct declarations to wrap the C++ structures and I have tried to map the original C++ to C#:
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MACAddr
{
public byte MAC1;
public byte MAC2;
public byte MAC3;
public byte MAC4;
public byte MAC5;
public byte MAC6;
}
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct uByte
{
public byte b1, b2, b3, b4;
}
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct uWord
{
public ushort w1, w2;
}
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
public struct IN_ADDR
{
#region C++ Original
// Attempt to mimic the following C++ union - taken from iTalkDemo inaddr.h file
//typedef struct in_addr {
// union {
// struct { UCHAR s_b1,s_b2,s_b3,s_b4; } S_un_b;
// struct { USHORT s_w1,s_w2; } S_un_w;
// ULONG S_addr;
// } S_un;
// #define s_addr S_un.S_addr /* can be used for most tcp & ip code */
// #define s_host S_un.S_un_b.s_b2 // host on imp
// #define s_net S_un.S_un_b.s_b1 // network
// #define s_imp S_un.S_un_w.s_w2 // imp
// #define s_impno S_un.S_un_b.s_b4 // imp #
// #define s_lh S_un.S_un_b.s_b3 // logical host
// } IN_ADDR;
#endregion
[System.Runtime.InteropServices.FieldOffset(0), MarshalAs(UnmanagedType.Struct)] public uByte addrb;
[System.Runtime.InteropServices.FieldOffset(0), MarshalAs(UnmanagedType.Struct)] public uWord addrw;
[System.Runtime.InteropServices.FieldOffset(0)] public uint addr;
}
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
unsafe public struct SockAddr_in
{
public short sin_family;
public ushort sin_port;
[MarshalAs(UnmanagedType.Struct)] public IN_ADDR sin_addr;
public fixed char sin_zero[8];
}
[Some code structs removed]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
unsafe public struct IComData
{
public int size; // same
public uint status; // unsigned
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)]
public byte[] name;
[MarshalAs(UnmanagedType.Struct)] public MACAddr MAC;
[MarshalAs(UnmanagedType.Struct)] public SockAddr_in addr_in;
public uint GPIO; // unsigned
public uint volume; // unsigned
public Int64 lastActive; // time_t - could use DateTime struct? AKA 20100628
[MarshalAs(UnmanagedType.Struct)] public PICfirmwareRev picRev;
[MarshalAs(UnmanagedType.Struct)] public NICfirmwareRev nicRev;
}
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
unsafe public struct IComConfiguration
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] MAC; // public fixed byte MAC[6];
public byte type;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] IP;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] Subnet;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] Gateway;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] Port;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] PeerIP;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] PeerPort;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 13)]
public byte[] UsedInternal;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] AppVer; // Version of intercom (major, minor)
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] UsedInternal2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)]
public byte[] FriendlyName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] FailForwardIP1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] FailForwardPort1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] FailForwardIP2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] FailForwardPort2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] FailForwardIP3;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] FailForwardPort3;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] IntercomOptions; // Options mask
public byte DoorRelaySeconds; // Num seconds for door to stay open
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] Extra;
}
Then I have written a C# test program, the following is the code:
public partial class frmMain : Form
{
// Declare and instantiate global variables
IntPtr DllHandle = IntPtr.Zero;
IntPtr Flags = IntPtr.Zero;
SockAddr_in ServerAddr = new SockAddr_in();
String BlankString = "";
MACAddr FindMAC = new MACAddr();
IComConfiguration GlobalIComConfig = new IComConfiguration();
GCHandle gchCallback, gchData; // handle to fix callback & data
StringBuilder DataBuffer; // Buffer for data
// Our delegate functions - one for DLL callback & other for safe output
TalkMaster.CallbackFunc EventHandlerFunc;
delegate void SafeOutput(string text);
public frmMain()
{
InitializeComponent();
// Setup Required Callback, Server Port & other variables
EventHandlerFunc = new TalkMaster.CallbackFunc(returnFunc);
ServerAddr.sin_addr.addr = TalkMaster.htons(3000);
FindMAC.MAC1 = 0xff; // All 0xff for find function
FindMAC.MAC2 = 0xff;
FindMAC.MAC3 = 0xff;
FindMAC.MAC4 = 0xff;
FindMAC.MAC5 = 0xff;
FindMAC.MAC6 = 0xff;
DataBuffer = new StringBuilder(256); // Allocate data buffer
gchData = GCHandle.Alloc(DataBuffer); // Pin data & keep handle
}
public void SafeOutputText(string OutputText)
{
if (OutputText != null)
{
if (OutputText.Length > 0)
{
if (this.rtbOutput.InvokeRequired)
{
SafeOutput d = new SafeOutput(SafeOutputText); // Create new instance of self via delegate
this.Invoke(d, new object[] { OutputText }); // Call invoke safely
}
else
{
this.rtbOutput.AppendText(String.Format("{0}\r\n", OutputText));
}
Application.DoEvents();
}
}
}
unsafe public void returnFunc(int EventID, int Socket, IComData IComData, IntPtr EventData, IntPtr UserData)
{
String OutputStr = String.Empty;
try
{
SafeOutputText(String.Format("Socket: {0} Event: {1} raised.", Socket, EventID));
switch (EventID)
{
case 0: // Event PRINT STRING
if (EventData != null)
{
OutputStr = new String((char*)EventData.ToPointer());
SafeOutputText(OutputStr);
}
break;
case 1: // Event NEW CONNECTION
break;
case 2: // Event RECEIVE DATA
break;
case 3: // Error
break;
case 4: // Event AUDIO LOW MARK
break;
case 8: // Event ICOM DONE TALKING - raised on Talk Button Press
break;
case 9: // Event RECONNECT
break;
case 10: // Event ICOM KEYPRESS
break;
case 16: // Event UPDATE STATUS
break;
case 40: // Response to DAFindIntercom (Event IMIN)
GlobalIComConfig = (IComConfiguration)Marshal.PtrToStructure(EventData, typeof(IComConfiguration));
OutputStr = Encoding.Unicode.GetString(GlobalIComConfig.FriendlyName);
SafeOutputText(String.Format("{0} connected.", OutputStr));
break;
case 41: // Event SETC
break;
default:
break;
}
}
catch (Exception e)
{
SafeOutputText(e.Message);
}
}
private void btnDAOpen_Click(object sender, EventArgs e)
{
try
{
SafeOutputText("DAOpen invoked.");
TalkMaster.DAOpen(ref DllHandle, ref Flags, EventHandlerFunc, (IntPtr)gchData);
gchCallback = GCHandle.Alloc(EventHandlerFunc); // Pin Callback so GC doesn't move or collect it
}
catch (Exception ex)
{
SafeOutputText(ex.Message);
}
}
private void btnDAStart_Click(object sender, EventArgs e)
{
int result;
try
{
SafeOutputText("DAStart invoked.");
result = TalkMaster.DAStart(DllHandle, ref ServerAddr, 14, BlankString, BlankString, BlankString, IntPtr.Zero);
}
catch (Exception ex)
{
SafeOutputText(ex.Message);
}
}
private void btnFindAll_Click(object sender, EventArgs e)
{
int result;
try
{
SafeOutputText("DAFindIntercom invoked.");
result = TalkMaster.DAFindIntercom(DllHandle, ref FindMAC);
}
catch (Exception ex)
{
SafeOutputText(ex.Message);
}
}
private void btnDAStop_Click(object sender, EventArgs e)
{
int result;
try
{
SafeOutputText("DAStop invoked.");
result = TalkMaster.DAStop(DllHandle);
gchCallback.Free();
gchData.Free();
}
catch (Exception ex)
{
SafeOutputText(ex.Message);
}
}
I can call DAOpen and DAStart without a problem (and the callback fires without a problem – that I can see ) but when I call DAFindIntercom I get an access violation when the C++ DLL calls the callback and I attempt to marshal the pointer to the correct structure on event 40 (following line):
GlobalIComConfig = (IComConfiguration)Marshal.PtrToStructure(EventData, typeof(IComConfiguration));
I would appreciate any assistance as I have read extensively and still cannot figure out what I am doing wrong.
|
|
|
|
|
Since I assume you have the C++ headers that you used to generate your pinvoke signatures, I would suggest by starting out using a tool that generates the pinvoke signatures from the C++ declarations.
I have used this one extensively, and it has worked well for me.
[^]
David
|
|
|
|
|
Hi sir,
As i am new C#.
I developed a code in VC++ where i am reading the data from combo box and storing it in map.
As i include header file,i can access
std::map<CString,CString>m_mapId;
std::map<CString,CString>::iterator it=m_mapId.begin();
The same code i want to use in C#
Any help will be thankful
Thanks
Raj
|
|
|
|
|
Didn't use C++ much, but I think, you should try Dictionary<t,u> class.
|
|
|
|
|
The closest thing to this, is probably the SortedDictionary. To do this code, all you'd do is:
SortedDictionary<string,string>_map;
foreach (KeyValuePair<string,string> kvp in _map)
{
}
"WPF has many lovers. It's a veritable porn star!" - Josh Smith As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.
My blog | My articles | MoXAML PowerToys | Onyx
|
|
|
|
|
raju_shiva wrote: The same code i want to use in C#
Here is the C# code
Dictionary<string, string> hashMap = new Dictionary<string, string>();
IDictionaryEnumerator en = hashMap.GetEnumerator();
while (en.MoveNext())
{
string key = (string)en.Key;
string keyValue = (string)en.Value;
}
Knock out 't' from can't, you can if you think you can.
|
|
|
|
|
Hi sir,
Thanks for your reply.
I am trying to use as u suggested but getting more confused.
Actually i have developed code in VC where i store some values in and store in combo after sorting accordingly.
Here is my complete code wt i am doing
CTest1View::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
ResizeParentToFit();
m_mapId["Abc"];
m_mapId["aa"];
}
CTest1View::OnEditchangeCombo1()
{
CString strvalue;
CString strTemp;
m_ctrlCombo.GetWindowText(strvalue);
std::map<CString,CString>::iterator it=m_mapId.begin();
m_ctrlCombo.ResetContent();
for(; it!=m_mapId.end();it++)
{
strTemp = it->first;
if(strTemp.Find(strvalue)==0)
m_ctrlCombo.AddString(strTemp);
}
m_ctrlCombo.SetWindowText(strvalue);
m_ctrlCombo.ShowDropDown();
}
I am trying with C#
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("aaat", 1);
d.Add("aat", 5);
How can i search in map and get the results back in CCombo.
Thanks
Raj
|
|
|
|
|
raju_shiva wrote: How can i search in map and get the results back in CCombo.
OK. then you could use HashSet with string as a type. This stores unique values and don't need to have key/value pair.
HashSet<string> stringSet = new HashSet<string> { "abc", "aa" };
string[] stringList = new string[stringSet.Count];
stringSet.CopyTo(stringList);
string strValue = "a";
string[] matchedStrings = Array.FindAll(stringList, delegate(string p)
{
return (p.Contains(strValue));
}
Array.Sort(matchedStrings);
cmbValues.Items.Clear();
cmbValues.Items.AddRange(matchedStrings);
cmbValues.SelectedIndex = 0;
});
Hope this gives some idea to you.
Knock out 't' from can't, you can if you think you can.
|
|
|
|
|
Hi sir,
I tried this code but getting an error as
HashSet stringSet = new HashSet { "abc", "aa" };
// "A new expression requires () or [] after type"
Thanks
Raj
|
|
|
|
|
Actually written code was correct, but due to incorrect formatting, it was not visible. The code line should be as below.
HashSet<string> stringSet = new HashSet<string> { "abc", "aa" };
You could check my previous post in FireFox as below.
1. Select the code.
2. Do right click.
3. select "View Selection Source".
Knock out 't' from can't, you can if you think you can.
|
|
|
|
|
Hi sir,
Laxman Auti wrote: HashSet<string> stringSet = new HashSet<string> { "abc", "aa" };
I tried the same ,but stilll the same error
Thanks
Raj
|
|
|
|
|
raju_shiva wrote: I tried the same ,but stilll the same error
Why don't you try something like following?
HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("abc");
hashSet.Add("aa");
Knock out 't' from can't, you can if you think you can.
modified on Monday, July 5, 2010 2:45 PM
|
|
|
|
|