I'm using C# (Visual Studio 2010) to programmatically create a DHCP reservation.
I've used the information in this post to get the DHCPOBJECTS.DLL. Connecting to the DHCP server works well. I'm also able to create a new reservation or enumerate through existing reservations.
class CDHCP
{
private Manager dhcpmgr;
private Server dhcpsrvr;
public CDHCP()
{
dhcpmgr = new Manager();
dhcpsrvr = dhcpmgr.Servers.Connect("192.168.1.3");
}
public void create_reservation(string sName, string sAddress, string sDescription, string sMAC)
{
Reservation DHCPReservation = dhcpsrvr.Scopes["192.168.1.0"].Reservation.CreateNew();
DHCPReservation.Name = sName;
DHCPReservation.UniqueID = sMAC;
DHCPReservation.Address = sAddress;
DHCPReservation.Comment = sDescription;
DHCPReservation.Update();
}
public void get_reservations()
{
List<Reservation> reservations = new List<Reservation>();
for(int i = 1; i <= dhcpsrvr.Scopes.Count; i++)
{
for(int j = 1; j <= dhcpsrvr.Scopes[i].Reservations.Count; j++)
{
reservations.Add(dhcpsrvr.Scopes[i].Reserations[j]);
}
}
}
}
Unfortunately when creating a new reservation the supported type is always set to "both". In our network we have to use only DHCP.
Anyone knows how to set the supported type to DHCP via the DHCPOBJECTS.DLL?
EDIT:
Okay it seems that I'm not able to change this option via DHCPOBJECTS.DLL.
Now I will try to realize this via the microsoft dhcp server management api
Related
Solved - thanks to Steve. The problem was that the App Pool I used was using the default App Pool Identity, which doesn't have sufficient privileges. Changing to an App Pool that used an account with sufficient privileges fixed the problem.
I have a simple C# class to get a list of available printers. When called from within a simple Console app, it returns the complete list of locally defined printers (9 printers). When called from the code behind in an aspx web app, it only returns the default printer. The web app is installed and runs as a user that is a local administrator on the server, and all printers are defined within that user's profile.
Note - I remote desktop to the server and run the console exe app there and it shows all the printers. I am trying to get a list of all the printers defined on the server.
Is there some security issue that I am missing?
Class code:
using System.Management;
/// <summary>
/// Returns a list of printers available on the current system.
/// </summary>
public static class PrinterList
{
public class Printer
{
public string name { get; set; }
public string server { get; set; }
public string location { get; set; }
public string portname { get; set; }
public string sharename { get; set; }
}
public static Printer[] GetInstalledPrinterList()
{
Printer[] printers = new Printer[0];
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * from Win32_Printer");
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject printer in coll)
{
string name = printer.GetPropertyValue("Name").ToString();
if ((!name.ToLower().Contains("send to onenote")) &&
(!name.ToLower().Contains("xps document writer")) &&
(!name.ToLower().Contains("print to pdf")) &&
(!name.ToLower().Contains(" fax")) &&
(!name.ToLower().Equals("fax")))
{
string server = "";
if (printer.GetPropertyValue("ServerName") != null)
server = printer.GetPropertyValue("ServerName").ToString();
string location = "";
if (printer.GetPropertyValue("Location") != null)
location = printer.GetPropertyValue("Location").ToString();
string portname = "";
if (printer.GetPropertyValue("PortName") != null)
portname = printer.GetPropertyValue("PortName").ToString();
string sharename = "";
if (printer.GetPropertyValue("ShareName") != null)
sharename = printer.GetPropertyValue("ShareName").ToString();
Printer newPrinter = new Printer();
newPrinter.name = name;
newPrinter.server = server;
newPrinter.location = location;
newPrinter.portname = portname;
newPrinter.sharename = sharename;
Printer[] newlist = new Printer[printers.Length + 1];
for (int i = 0;i < printers.Length; i++)
{
newlist[i] = printers[i];
}
newlist[printers.Length] = newPrinter;
printers = newlist;
}
}
return printers;
}
}
Your asp.net c# code runs on your server not on client's computer. This is really important fact to remember.
By calling get printers on asp.net you are basically getting the available printers connected to your server not the ones from client.
Edit: Turns out that you were using the default account for the app pool. By using an account with admin right for the app pool solves the problem.
i have problem with displaying image in my web app. It took photo from database, and should dispay in web app.
protected void btnShowPhoto_Click(object sender, EventArgs e)
{
string adresURL = #"~/Content";
string camPath = "";
string[] tab = new string[10];
CheckBox[] _boxes = new CheckBox[] { this.CheckBox1, this.CheckBox2, this.CheckBox3, this.CheckBox4, this.CheckBox5, this.CheckBox6, this.CheckBox7, this.CheckBox8 };
System.Web.UI.WebControls.Image[] _images = new System.Web.UI.WebControls.Image[] { this.Image1, this.Image2, this.Image3, this.Image4, this.Image5, this.Image6, this.Image7, this.Image8 };
Label[] _labels = new Label[] { this.lblCameraName1, this.lblCameraName2, this.lblCameraName3, this.lblCameraName4, this.lblCameraName5, this.lblCameraName6, this.lblCameraName7, this.lblCameraName8 };
System.Web.UI.HtmlControls.HtmlAnchor[] _linkscontrol = new System.Web.UI.HtmlControls.HtmlAnchor[] { this.imagelink1, this.imagelink2, this.imagelink3, this.imagelink4, this.imagelink5, this.imagelink6, this.imagelink7, this.imagelink8 };
for (int i = 0; i < 8; i++)
{
_images[i].Visible = false;
_labels[i].Visible = false;
_linkscontrol[i].HRef = "";
}
for (int i = 0; i < 8; i++)
{
if (_boxes[i].Checked)
{
camPath = null;
tab = null;
camPath = this.GridView2.Rows[i].Cells[0].Text;
tab = camPath.Split(new string[] { "StoredPhotos" }, StringSplitOptions.None);
//Virtual Path'a
camPath = adresURL + tab[1].Replace(#"\", "/");
_labels[i].Visible = true;
_labels[i].Text = this.GridView2.Rows[i].Cells[1].Text;
_linkscontrol[i].HRef = camPath;
_images[i].ImageUrl = camPath;
_images[i].Visible = true;
}
else
_images[i].Visible = false;
}
}
I have problem with my virtual path probably. CamPath(Virtual Path) becomes from : E:\Photo\StoredPhotos\20151010\000003819619_201512021335_1_C1, and finally looks: ~/20151010/000003819619_201512021335_1_C1
This path means nothing to a web browser:
~/20151010/000003819619_201512021335_1_C1
It doesn't know what to do with that ~ directory. That's a server-side concept, not a client-side concept. So your server-side code needs to resolve that to an actual path.
It could be as simple as just explicitly starting from the root of the server:
string adresURL = #"/Content";
So the resulting URL would start with /Content/..... and the browser would check for the image in that path.
But if the application isn't (or might not be) the root of the server domain then you'd need to either manually account for that or use a server-side helper of some sort. There are a variety of ways to go about that, for example:
_images[i].ImageUrl = System.Web.VirtualPathUtility.ToAbsolute(camPath);
The browser expect access to image via http protocol, if you want view the image you have 2 diffrerent way:
(simple) Create a virtual directory under iis that point to a phisical folder E:\Photo\StoredPhotos\ and called StoredPhotos, in _images[i].ImageUrl you may set the value /StoredPhotos/20151010/000003819619_201512021335_1_C1.jpg
(complex) Build a class that read the file on the disk and write it to the response (use IHttpHandler interface), add this handler to web.config and set _images[i].ImageUrl the value of 'NameOfHandler.aspx?20151010/000003819619_201512021335_1_C1
All I need is a more reliable and stable way of logging into multiple account (not all at once) using a loop that's all. I have already an example code that works but isn't all that stable.
string email_1 = "email_1";
string password_1 = "password_1";
string email_2 = "email_2";
string password_2 = "password_2";
int k = 1;
do
{
string e = null;
string p = null;
if (k == 1)
{
e = email_2;
p = password_2;
}
if (k == 2)
{
e = email_1;
p = password_1;
}
_driver.FindElement.(id("submit_email")).sendkeys(e);
IWebElement s = _driver.FindElement.(id("submit_password"));
s.Sendkeys(p);
s.Submit();
//do stuff
_driver.FindElement(id("logout")).Click();
k++;
} while (k <= 2);
Any ideas on how to make it more stable and reliable, or maybe a better approach to it?
You're gonna need to completely refactor this code. Have you ever practiced object oriented design?
Create this class:
public class Account // Stores the email and password of each account
{
public string Email;
public string Password;
public Account(string email, string password) // Constructor
{
Email = email;
Password = password;
}
}
Then use this class like so:
// Keep all the accounts in one place
List<Account> accounts = new List<Account>()
{
new Account("email_1", "password_1"), // Create a new account
new Account("email_2", "password_2") // Create another account
};
foreach(Account account in accounts)
{
_driver.FindElement.(id("submit_email)).sendkeys(account.Email);
IWebElement s = _driver.FindElement.(id("submit_password"));
s.Sendkeys(account.Password);
s.Submit();
// do stuff
_driver.FindElement(id("logout")).Click();
}
This code is highly expandable and reusable. If you want to add another account, you use the new Account(string, string), statement in the List and that's the only change that needs to be made.
I'm not a developer so maybe the answer is out there for a different solution but I can't really translate it from python or something else.
I'm trying to use the AWS .NET SDK to find an instance and then get the instance's tags. I've gotten as far as being able to determine if an instance is up and running or not. I also see how I can create and delete tags (not in code example below). But I don't see an easy way to actually check if a tag exists and get the value of the tag if it does exist.
Sorry if I'm missing the obvious but this is all new to me. Here's an example of the code I'm using to check if an instance is running.
instanceID = "i-myInstanceID";
do {
var myrequest = new DescribeInstanceStatusRequest();
DescribeInstanceStatusResponse myresponse = ec2.DescribeInstanceStatus(myrequest);
int isCount = myresponse.DescribeInstanceStatusResult.InstanceStatuses.Count;
for (int isc=0; isc < isCount; isc++) {
InstanceStatus instanceStatus = myresponse.DescribeInstanceStatusResult.InstanceStatuses[isc];
if (instanceStatus.InstanceId.Contains(instanceID)) {
Console.WriteLine("It looks like instance "+instanceID+" is running.");
idIdx = isc;
foundID = true;
break;
}
}
if ((foundID==false) && (secondCounter==1)) {
Console.Write("Looking for instance "+instanceID);
} else {
Console.Write(".");
}
Thread.Sleep(1000);
secondCounter++;
if (secondCounter > 5) {
break;
}
} while (foundID == false) ;
First send a DescribeInstancesRequest to get the list of Instances:
public DescribeInstancesResult GetInstances(Ec2Key ec2Key)
{
_logger.Debug("GetInstances Start.");
AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);
var ec2Request = new DescribeInstancesRequest();
DescribeInstancesResponse describeInstancesResponse = ec2.DescribeInstances(ec2Request);
DescribeInstancesResult result = describeInstancesResponse.DescribeInstancesResult;
_logger.Debug("GetInstances End.");
return result;
}
Then loop through the instances until you find the one you want, and then use the Tag.GetTagValueByKey method:
// This just calls the above code
DescribeInstancesResult ec2Instances = _ec2ResourceAccess.GetInstances(ec2Key);
var returnInstances = new List<Ec2UtilityInstance>();
foreach (var reservation in ec2Instances.Reservation)
{
foreach (var runningInstance in reservation.RunningInstance)
{
var returnInstance = new Ec2UtilityInstance();
returnInstance.InstanceId = runningInstance.InstanceId;
returnInstance.InstanceName = runningInstance.Tag.GetTagValueByKey("Name");
returnInstance.Status = (Ec2UtilityInstanceStatus)Enum.Parse(typeof(Ec2UtilityInstanceStatus), runningInstance.InstanceState.Name, true);
returnInstance.DefaultIp = runningInstance.Tag.GetTagValueByKey("DefaultIp");
returnInstance.InstanceType = runningInstance.InstanceType;
returnInstance.ImageId = runningInstance.ImageId;
returnInstances.Add(returnInstance);
}
}
Here is the link for full source that this was taken from:
https://github.com/escherrer/EC2Utilities
Common\Manager
and
Common\ResourceAccess
How can I get a process send/receive bytes? the preferred way is doing it with C#.
I've searched this a lot and I didn't find any simple solution for this. Some solutions suggested to install the WinPCap on the machine and to work with this lib.
Like this guy asked: Need "Processes with Network Activity" functionality in managed code - Like resmon.exe does it
I don't want the overhead of the lib.
Is there a simple solution for this?
Actually I want the exactly data that the Resource Monitor of Windows gives under the "Processes with Network Activity" tab:
How does the Resource Monitor of Windows gets this information?
Any example?
Also, tried to use the counter method which is mentioned over here:
Missing network sent/received
but with no success - as not every process is shown under this counter.
And again I'm wondering how the Resource Monitor gets this information even without using this counter...
Resource monitor uses ETW - thankfully, Microsoft have created a nice nuget .net wrapper to make it easier to use.
I wrote something like this recently to report back my process's network IO:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Session;
namespace ProcessMonitoring
{
public sealed class NetworkPerformanceReporter : IDisposable
{
private DateTime m_EtwStartTime;
private TraceEventSession m_EtwSession;
private readonly Counters m_Counters = new Counters();
private class Counters
{
public long Received;
public long Sent;
}
private NetworkPerformanceReporter() { }
public static NetworkPerformanceReporter Create()
{
var networkPerformancePresenter = new NetworkPerformanceReporter();
networkPerformancePresenter.Initialise();
return networkPerformancePresenter;
}
private void Initialise()
{
// Note that the ETW class blocks processing messages, so should be run on a different thread if you want the application to remain responsive.
Task.Run(() => StartEtwSession());
}
private void StartEtwSession()
{
try
{
var processId = Process.GetCurrentProcess().Id;
ResetCounters();
using (m_EtwSession = new TraceEventSession("MyKernelAndClrEventsSession"))
{
m_EtwSession.EnableKernelProvider(KernelTraceEventParser.Keywords.NetworkTCPIP);
m_EtwSession.Source.Kernel.TcpIpRecv += data =>
{
if (data.ProcessID == processId)
{
lock (m_Counters)
{
m_Counters.Received += data.size;
}
}
};
m_EtwSession.Source.Kernel.TcpIpSend += data =>
{
if (data.ProcessID == processId)
{
lock (m_Counters)
{
m_Counters.Sent += data.size;
}
}
};
m_EtwSession.Source.Process();
}
}
catch
{
ResetCounters(); // Stop reporting figures
// Probably should log the exception
}
}
public NetworkPerformanceData GetNetworkPerformanceData()
{
var timeDifferenceInSeconds = (DateTime.Now - m_EtwStartTime).TotalSeconds;
NetworkPerformanceData networkData;
lock (m_Counters)
{
networkData = new NetworkPerformanceData
{
BytesReceived = Convert.ToInt64(m_Counters.Received / timeDifferenceInSeconds),
BytesSent = Convert.ToInt64(m_Counters.Sent / timeDifferenceInSeconds)
};
}
// Reset the counters to get a fresh reading for next time this is called.
ResetCounters();
return networkData;
}
private void ResetCounters()
{
lock (m_Counters)
{
m_Counters.Sent = 0;
m_Counters.Received = 0;
}
m_EtwStartTime = DateTime.Now;
}
public void Dispose()
{
m_EtwSession?.Dispose();
}
}
public sealed class NetworkPerformanceData
{
public long BytesReceived { get; set; }
public long BytesSent { get; set; }
}
}
You can use PerformanceCounter. Sample code:
//Define
string pn = "MyProcessName.exe";
var readOpSec = new PerformanceCounter("Process","IO Read Operations/sec", pn);
var writeOpSec = new PerformanceCounter("Process","IO Write Operations/sec", pn);
var dataOpSec = new PerformanceCounter("Process","IO Data Operations/sec", pn);
var readBytesSec = new PerformanceCounter("Process","IO Read Bytes/sec", pn);
var writeByteSec = new PerformanceCounter("Process","IO Write Bytes/sec", pn);
var dataBytesSec = new PerformanceCounter("Process","IO Data Bytes/sec", pn);
var counters = new List<PerformanceCounter>
{
readOpSec,
writeOpSec,
dataOpSec,
readBytesSec,
writeByteSec,
dataBytesSec
};
// get current value
foreach (PerformanceCounter counter in counters)
{
float rawValue = counter.NextValue();
// display the value
}
And this is to get performance counters for the Network card. Note it is not process specific
string cn = "get connection string from WMI";
var networkBytesSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", cn);
var networkBytesReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", cn);
var networkBytesTotal = new PerformanceCounter("Network Interface", "Bytes Total/sec", cn);
Counters.Add(networkBytesSent);
Counters.Add(networkBytesReceived);
Counters.Add(networkBytesTotal);
Have a look at the IP Helper API. There is an implementation in C# by Simon Mourier that sums transferred bytes per process: https://stackoverflow.com/a/25650933/385513
It would be interesting to know how this compares with Event Tracing for Windows (ETW)...