|
My application is C# .net Framework 3.5.
The main functionality of the application is:
let the user choose a network interface card (NIC)
assign to the user selected NIC an IP address (and subnet mask) - I use WMI - EnableStatic method of Win32_NetworkAdapterConfiguration class.
start through a Process a 3rd party C++ exe component, behaving like a server, which will be listening to the given IP address - the binding functionality is implemented by the server, so on Process start up I just give pass the proper IP address and it starts listening on that one.
Operation 2 and 3 can be repeated an unlimited number of times, thus it's possible to assign to the very same NIC several IP addresses and have multiple servers, each one listening to the its own IP address.
To assign the IP address to the given NIC I use WMI, in particular this code, where adapterGUID is the GUID of the user selected NIC and newSettings it's a class holding a list of IPs and subnet masks:
public static bool ChangeNetworkInterfaceIPs(string adapterGUID, IpSettings newSettings)
{
try
{
if (String.IsNullOrEmpty(adapterGUID))
throw new ArgumentException("adapterGUID");
ManagementBaseObject inPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
ManagementObject moTarget = null;
foreach (ManagementObject mo in moc)
{
if ((string) mo["SettingID"] == adapterGUID)
{
moTarget = mo;
break;
}
}
if (moTarget == null)
{
mc = null;
return false;
}
object winsSecondary = moTarget.GetPropertyValue("WINSSecondaryServer");
object gateways = moTarget.GetPropertyValue("DefaultIPGateway");
object dnsDomain = moTarget.GetPropertyValue("DNSDomain");
object dnsServers = moTarget.GetPropertyValue("DNSServerSearchOrder");
object winsPrimary = moTarget.GetPropertyValue("WINSPrimaryServer");
if (newSettings.DHCP)
{
inPar = moTarget.GetMethodParameters("EnableDHCP");
moTarget.InvokeMethod("EnableDHCP", inPar, null);
}
else
{
inPar = moTarget.GetMethodParameters("EnableStatic");
inPar["IPAddress"] = newSettings.Ips;
inPar["SubnetMask"] = newSettings.Netmasks;
moTarget.InvokeMethod("EnableStatic", inPar, null);
}
if (gateways != null && !newSettings.DHCP)
{
inPar = moTarget.GetMethodParameters("SetGateways");
inPar["DefaultIPGateway"] = gateways;
outPar = moTarget.InvokeMethod("SetGateways", inPar, null);
}
if (dnsDomain != null && !newSettings.DHCP)
{
inPar = moTarget.GetMethodParameters("SetDNSDomain");
inPar["DNSDomain"] = dnsDomain;
outPar = moTarget.InvokeMethod("SetDNSDomain", inPar, null);
}
if (dnsServers != null && !newSettings.DHCP)
{
inPar = moTarget.GetMethodParameters("SetDNSServerSearchOrder");
inPar["DNSServerSearchOrder"] = dnsServers;
outPar = moTarget.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
}
if (winsPrimary != null && !newSettings.DHCP)
{
inPar = moTarget.GetMethodParameters("SetWINSServer");
inPar["WINSPrimaryServer"] = winsPrimary;
if (winsSecondary != null)
{
inPar["WINSSecondaryServer"] = winsSecondary;
}
outPar = moTarget.InvokeMethod("SetWINSServer", inPar, null);
}
return true;
}
catch
{
return false;
}
}
Now, my problem comes when the user wants to kill one the active servers. On server closure I have to remove from the NIC the IP address the server was listening to.
Killing the process it's not a problem, but when I call my ChangeNetworkInterfaceIPs to update the IP assigned to NIC (removing the one of the server no longer in use) using a new list of IP address (namely: the old list without the ip address of the killed server) something very strange happens: randomly some of other running servers get a SOCKET_ERROR and their connection it's closed.
Any idea on what's happening? Why the running servers are randomly getting SOCKET_ERRORs when I remove an unused IP address from the NIC ? Additionally, I know that probably setting a whole list of IP addresses just to remove one it's not really a best practice: is there a way to remove just a given IP address?
I hope the question is clear enough. Thank you for your time.
|
|
|
|
|
The problem occurs probably because the underlying code in the Win32_NetworkAdapterConfiguration class deletes all the IP's from the adapter and rewrites the list of IPs, or at least partially so.
Using WMI, there's nothing you can do about it. Also, the 3rd party server apparently isn't tolerant of the IP binding changing or disappearing for a brief time. There's nothing you can do about that either, except find another product.
One method I've used to get around screwy problems like this is to run this stuff in virtual machines, one server instance = one VM. If you need to change the IP or the server, mearly shutdown the VM, make any IP changes to it, reatart the VM and the server comes up not knowing anything happened.
|
|
|
|
|
thank you for you support Dave.
I came exactly to the same conclusion as well.
Sadly due several reason we cannot use VMs, so I'm still struggling in order to find a proper solution / work around.
Cheers
|
|
|
|
|
Hi all,
I want to create an application which detects the webcam to take the photos and this application should work on any platform,operating System.
Please can any one suggest me how can i start creating this application.
Thanks in advance
|
|
|
|
|
sarang_k wrote: I want to create an application which detects the webcam to take the photos and this application should work on any platform,operating System.
Good luck with that. So, you want it to work on Android, or Linux, or iOS, or Mountain Lion, or Windows. You aren't going to get the same codebase to do all that.
|
|
|
|
|
i think we can write the code by using different conditions,like when u open a browser and a site it detects the things from site automatically what player or plugins r required.
|
|
|
|
|
You really can't.Taking the browser example, the browser itself is compiled differently for different platforms.
|
|
|
|
|
ok
Atleast can u tell me how can i implement in windows OS ?
|
|
|
|
|
Hello Everyone
Can someone please tell me if there is a equivalent to java's ResourceBundle class in C#?
kind regards
lapeci
|
|
|
|
|
Sort of. Basically, you create resource files that are locale specific or default locale, and .NET takes care of a lot of the heavy lifting for you. Have a read of this[^] article to get you started.
|
|
|
|
|
While debugging, I am seeing the following error messages from the code at the bottom. Do I need some sort of time out period for my this.invoke commands?
Thanks for reading!
DisconnectedContext was detected
Message: Context 0x3eb6e0' is disconnected. Releasing the interfaces from the current context (context 0x3eb570).This may cause corruption or data loss. To avoid this problem, please ensure that all contexts/apartments stay alive until the applicationis completely done with the RuntimeCallableWrappers that represent COM components that liveinside them.
ContextSwitchDeadlock was detected
Message: The CLR has been unable to transition from COM context 0x3eb570 to COM context 0x3eb6e0 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.
<pre>this.Invoke((MethodInvoker)delegate()
{
string uptime = GetUptime(server.TrimEnd()).ToString();
string days = "";
int firstPeriodIndex = uptime.IndexOf('.');
int firstColonIndex = uptime.IndexOf(':');
int daysIndex = 0;
if (firstPeriodIndex < firstColonIndex)
{
daysIndex = uptime.IndexOf('.');
if (daysIndex >= 0)
{
days = uptime.Remove(daysIndex);
}
}
else
{
days = "0";
}
string hours = uptime.Remove(0, daysIndex + 1);
int hoursIndex = hours.IndexOf(':');
if (hoursIndex >= 0)
{
hours = hours.Remove(hoursIndex);
}
string minutes = uptime.Remove(0, daysIndex + 1);
minutes = minutes.Remove(0, hoursIndex + 1);
int minutesIndex = minutes.IndexOf(':');
if (minutesIndex >= 0)
{
minutes = minutes.Remove(minutesIndex);
}
string seconds = uptime.Remove(0, daysIndex + 1);
seconds = seconds.Remove(0, hoursIndex + 1);
seconds = seconds.Remove(0, minutesIndex + 1);
int secondsIndex = seconds.IndexOf('.');
if (secondsIndex >= 0)
{
seconds = seconds.Remove(secondsIndex);
}
if (_shouldStop == true) { return; }
lvwShutdown.BeginUpdate();
if (lvwShutdown.Items[selectedIndex].SubItems[2].Text != "")
{
lvwShutdown.Items[selectedIndex].SubItems[2].Text = "";
}
lvwShutdown.Items[selectedIndex].SubItems[3].Text = days + " D, " + hours + " H, " + minutes + " M, " + seconds + " S";
lvwShutdown.EndUpdate();
lvwShutdown.Refresh();
});
|
|
|
|
|
I am putting together a WCF example using queues.
So far the client pops a message on the service queue, and the service in turn pops an acknowledgement on the client queue.
There are two technical pieces still challenging me.
Each client nominates and creates its queue at run time. I am struggling to get at the endpoint in the client tags on the service side app.config to use the address passed up by the client for the response - not so much to edit the as to build an alternative programaticaly at run time.
The other was on the client side when the response comes back. I open a host using a client side contract in the client form. The neatest way to trigger an event in the form was inspired by this post: Events from Service
Ger
modified 3-Dec-12 18:14pm.
|
|
|
|
|
Hi.I want to add image to picturebox in swith case building.Could you help me?.I'm study on Windows Form.
|
|
|
|
|
Try:
Image myImage = null;
switch(imagenumber)
{
case 0: myImage = Image.FromFile(@"D:\Temp\CatPic.jpg"); break;
case 1: myImage = Image.FromFile(@"D:\Temp\DogPic.jpg"); break;
case 2: myImage = Image.FromFile(@"D:\Temp\LlamaPic.jpg"); break;
}
myPictureBox.Image = myImage; But it's bad practice to use magic numbers and fixed file names...
If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.
|
|
|
|
|
When I used to execute my code, I used to be able to step into the following line of code in my PC class, and it went to my GetProgramControl method, where I could step some more.
controls[i] = (Control)_type.InvokeMember("GetProgramControl", BindingFlags.Default | BindingFlags.InvokeMethod, null, _objectInstance, _parameters);
For some reason, I was stepping into that at one point, and it was having trouble finding my SN.cs and I hit the link to browse to show it where it was. Ever since then, every time I step into the line above, it goes directly to the later reference of my SN class and the debugger is in a method there. Any ideas how I can get the debugger to stop in the PC class GetProgramControl method? I can't put a breakpoint there because it's outside of my class that is calling it.
I looked at the following but it's different since my SN class isn't a child of PC, it's a reference used in it.
http://bytes.com/topic/c-sharp/answers/439984-cant-step-into[^]
I also saw this and it might be similar but it doesn't look like anyone had a solution for him: http://www.codeproject.com/Messages/2932838/Can-t-step-into-method-debug-with-F11-in-Visual-St.aspx[^]
|
|
|
|
|
I figured it out. My dll was out of date that was being referenced/called from the above line of code.
|
|
|
|
|
How can catch the exceptions if my parent and child pages are from different domains.
My agenda is to:
load content using iframes from a cross domain. If the loading fails, catch the exception and retry. If the retry fails too, catch the exception and throw exception.
I know it's easy to do it if the parent and child are from same domain.
Please help!!! Thanks in advance
modified 29-Nov-12 18:09pm.
|
|
|
|
|
Hello Every1. I have made a windows form application on server client methodology. This works good when I open reports on server but when I open reports on client side then I get the error "Load Report Failed".Please help me about fixing this error??
Thanks
|
|
|
|
|
I am getting the following error message in a C# 2008 application and I do not know what to look at to resolve the problem:
Error2Build failed due to validation errors in C:\RPT.dbml. Open the file and resolve the issues in the Error List, then try rebuilding the project.
There is nothing showing me where the exact error is coming from. There is a reference setup for System.Configuration.
The following code is from the RPT.designer.cs
namespace cli
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
using System.Configuration;
[System.Data.Linq.Mapping.DatabaseAttribute(Name="DEV")]
public partial class RPTDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
public RPTDataContext() :
base(ConfigurationManager.ConnectionStrings["DEVConnectionString"].ConnectionString.ToString(), mappingSource)
{
OnCreated();
}
The following code is from RPT.cs file:
namespace cli
{
partial class RPTDataContext
{
}
}
Here is the code in the app.config file:
<connectionStrings>
<add name="DEVConnectionString"
connectionString="Data Source=xxx;Initial Catalog=PROD1;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Thus can you tell me and/or show me in code how to fix this problem?
|
|
|
|
|
sc steinhayse wrote: Thus can you tell me and/or show me in code how to fix this problem?
What have you tried so far? Have you Googled it? When I did a quick Google, this[^] was the first thread - and it looks quite promising.
|
|
|
|
|
Hello!
I'm working on an application where you are able to see the chosen users outlook appointments for over 10 days. The program is supposed to be a gridview and it's supposed to loop through the users outlook for each day and add the appointments.
So far i'm getting all appointments from the selected user, but the program adds even the next days appointments in the first day.
I would be very thankful if someone could help me out with this. Maybe I'm supposed to change the loops? I'm getting all the columns created for the next 10 days.
Here's the code of my loops:
List<DateTime> NAME = new List<DateTime>();
DataRow drow = dt.NewRow();
for (int i = 0; i < 10; i++)
{
NAME.Add(DateTime.Now.AddDays(i));
DataColumn dcol = new DataColumn(NAME[i].ToString(), typeof(System.String));
dt.Columns.Add(dcol);
foreach (Appointment appt in findResults.Items)
{
if (NAME[i].Day == appt.Start.Day)
{ dt.Rows.Add(appt.Subject); }
}
}
I also wondering if there is some kind of way to calculate the duration of all appointment each day in minutes for example. To get the total amount of minutes of each day from the person. Is this possible?
Best regards,
Blenni
modified 29-Nov-12 9:29am.
|
|
|
|
|
I'm not sure what you're trying to do here. What you're actually doing is adding a new row for each appointment, with the subject in the first column.
I think what you want is
List<DateTime> days = new List<DateTime>();
for (int i = 0; i < 10; i++){
days.Add(DateTime.Now.AddDays(i));
DataColumn dcol = new DataColumn(NAME[i].ToString(), typeof(System.String));
dt.Columns.Add(dcol);
}
foreach (Appointment appt in findResults.Items){
int index = days.FindIndex(dt => dt.Day == appt.Start.Day);
if(index > 0) {
DataRow dr = dt.Rows.Add();
dr[index] = appt.Subject;
}
}
|
|
|
|
|
Big thanks!
The only problem now is that I'm not getting the appointments of the current day.
It shows the current day and 10 days forward but doesn't add the appointments for the current day, only the upcoming days.
Cheers blenni
modified 29-Nov-12 9:59am.
|
|
|
|
|
That can be an exercise in bug tracking
(It's a simple schoolboy error. It should be index >= 0.)
|
|
|
|
|
Yes sometimes u become blind in code. I found it hehe thanks.
I also wondering if there is some kind of way to calculate the duration of all appointment each day in minutes for example. To get the total amount of minutes of each day from the person. Is this possible?
Cheers!
|
|
|
|