Mount Network Drive with WMI - c#

Trying to write a WMI class function to mount a network drive on any computer (remote or local) using the credentials of the logged in computer.
This is a class for a larger project that I wrote for help desk staff to do first line fixes on remote PC's. The tech types in the the machine name or ip address and the app connects to it and allows to tech to click a couple of buttons and fix some basic items without having to remote(VNC) into the PC.
I've read all over the internet that it is much easier ways than WMI, but due to the remote nature of the app I would rather not use local API calls, nor do I want to worry about uploading script and executing it though a process start. Also other functions are already in WMI so I'd like to keep the code base the same.
The basic idea is to mount H: to //fileserver.example.com/$username
NetFixer is already in production use so I'm trying to keep my code nice and neat
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace WMIcontrols
{
public class Remote
{
public string target;
//Some code skipped here for simplicity sake...
public bool MountNetDrive(string DriveLetter, string MountLocation)
{
try
{
//Mount the network drive
return true;
}
catch
{
//Mount Failed
return false;
}
}
}
}

This is not using WMI but will accomplish what you want and is very simple
System.Diagnostics.Process.Start("cmd", "/c net use x: \\fileserver.example.com /user:Username Password");

Related

Can I delete files from "Windows" folder in Windows Server 2016 using C# (MVC or Core)?

In windows server 2016, I create a text file inside "Windows" folder for some reasons, and in special cases I need to delete it from my website which is built in C# MVC, is there any way to do that using C# (MVC or Core)? I know that it is illogical but I need that if applicable.
The answer for your solution is fairly simple, yes it is indeed possible to remove a Windows file or folder. However, this is costly! Allowing an application to have Administrator permissions can lead to malicious behaviors. Such as UAC Bypassing from other malware.
All you need to do in order to delete that file programming using C# is to first off run your application with administrator rights. Here's source the code for it:
using System;
using System.IO;
public class Program {
public static void Main() {
String myPath = #"<DRIVE_LETTER>:\Windows\<FILENAME>"; // E.g: #"C:\Windows\MyText.txt";
try{ // For stability purposes,
File.Delete(myPath);
} catch (IOException ERROR){ // If any errors occurs, it will print it out!
Console.WriteLine(ERROR.Message);
}
}
}
Documentation for Permission(s) Risks: Risks of Admin Rights
Documentation for File.Delete: File.Delete(String) Method C#

System.Windows.Forms - RemoteWebDriver -> Access is denied

We have a problem with my team for several weeks.
We currently have a test in MSTest v1 and Selenium 3.11 that is dedicated to upload a photo when filling out a profile.
In local works perfectly (hehehe), but in remote (RemoteWebdriver) the server of Build & Releases (VSTS) throws an error just in the step where I interact with this window, of the Access Denied type.
It is not really Selenium who acts there, but the System.Windows.Forms library and the SendWait method of the SendKeys class that gives the error when it is launched remotely.
Screenshot of the element in question >>> UploadFile
Example code:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Windows.Forms;
using OpenQA.Selenium;
using System.IO;
//...
public class EditarFotoUsuarioAdministrador
{
public static void Execute(IWebDriver driver, string foto)
{
driver.FindElement(By.XPath("//button[#id='upload']")).Click();
System.Threading.Thread.Sleep(2000);
SendKeys.SendWait(Directory.GetCurrentDirectory() + foto);
SendKeys.SendWait(#"{Enter}");
System.Threading.Thread.Sleep(2000);
driver.FindElement(By.XPath("//button[#id='save']")).Click();
System.Threading.Thread.Sleep(500);
}
}
As I said, this in local works perfectly, but when it runs on the remote server, the whole test goes well until it reaches the SendKeys line:
AccessIsDenied
Hopefully someone has an answer, thank you very much !!
The agent need to be running as interactive mode.
I've fixed it using AutoIT3.
Loading the nuget and using its methods to send the path of the file, you can perfectly interact with any pop-up browser window.
And best of all, the remote server does it too.
Thank you very much to all !
AutoIT3 or AutoItX.Dotnet ?
can you please send the code snippet. i used below code
` AutoItX.WinActivate("Open");
AutoItX.ControlGetFocus("Open");
AutoItX.Send(file);
System.Threading.Thread.Sleep(2000);
AutoItX.ControlClick("Open", " ", "Button1");`
It works fine in local but not in remote

Windows Network Information Manipulation

I am working as a trainee engineer in a networking firm and am getting annoyed by having to change the IP information from time to time.
I am in need of building a software to help me change these details easily. I have managed to set the IP information. But I still have problems.
I need to run the program as Administrator [right click], is there a way to program to prompt for it at startup?
How can I change adapter to DHCP?
The code is quite long, and I hope not to fill bore you with it. But I have been using Management
Management Class
Management Base Object
Management Object Collection in my development.
I'd prefer to make my own program to develop my programming skills. But if there is an application to do it, I don't mind knowing.
I hope this answer gives you some insisght and direction to go.
Okay, the network adapter one isn't that straight forward, but I believe you can achieve it with WMI, specially this WMI object here. The MSDN documentation tells you all the properties, methods (which there are for setting DHCP etc) and the datatypes and values it takes. This may be one approach as using WMI through C# is pretty easy. I wish I could provide you an example, but I've never used that specific WMI class before. You can also access the above WMI class through the Visual Studio Server Explorer, which you can see here. ..and it has your "EnableDHCP" method you are probably looking for.
As far as asking for your program to run with administrative priviledges, here is the code from my setup project in my framework. What this does is before it runs any sort of form or logic, requests the "runas" verb which invokes UAC (if Windows has its Vista/7, and requests admin priviledges from the user)
namespace Setup {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Setup.Forms;
using System.Security.Principal;
using System.Diagnostics;
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!administrativeMode) {
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Verb = "runas";
startInfo.FileName = Application.ExecutablePath;
try {
Process.Start(startInfo);
}
catch {
return;
}
return;
}
Application.Run(new ShellForm());
}
}
}
As far as a program to do it, Windows Network Connection Manager? I know its cumbersome because of all the dialogs, but.. its already there.
I once had to write a very similar program. I used some of the source code from these two projects to help me get started: Chameleon Project and Configuring TCP/IP Settings using WMI and C#
The Chameleon Project is a C# project to help change network settings of a particular adapter. The other project is a tutorial on how to use C# to change network settings using WMI and C#. You can look at the source code and learn from it to help you make your own software that does what you need.

HTTPWebRequest.GetResponse() throws connection failure exception

I'm trying to create a simple application that does a HTTP
request/response on a button click. Here's the entire code which I got
from a reference book:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace emulator2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
Uri l_Uri = new Uri("http://www.testing.com");
HttpWebRequest l_WebReq = (HttpWebRequest)WebRequest.Create(l_Uri);
HttpWebResponse l_WebResponse =
(HttpWebResponse)l_WebReq.GetResponse();
Stream l_responseStream = l_WebResponse.GetResponseStream();
StreamReader l_SReader = new StreamReader(l_responseStream);
string resultstring = l_SReader.ReadToEnd();
Console.WriteLine(resultstring);
}
}
}
The thing that puzzles me is that when I shift the entire chunk of code
to a Windows Application, it works fine. But when I use it on a Device
Application, it just throws me an error. Here are the details of the
error:
System.Net.WebException was unhandled Message="Could not establish
connection to network." StackTrace: at
System.Net.HttpWebRequest.finishGetResponse() at
System.Net.HttpWebRequest.GetResponse() at
emulator2.Form1.button1_Click() at
System.Windows.Forms.Control.OnClick() at
System.Windows.Forms.Button.OnClick() at
System.Windows.Forms.ButtonBase.WnProc() at
System.Windows.Forms.Control._InternalWnProc() at
Microsoft.AGL.Forms.EVL.EnterMainLoop() at
System.Windows.Forms.Application.Run() at emulator2.Program.Main()
The error points at this line:
HttpWebResponse l_WebResponse = (HttpWebResponse)l_WebReq.GetResponse();
Does anyone have any idea on how to solve this? I need to get this
solved real quick..so any help given is greatly appreciated! Thanks!
My guess is that the emulator doesn't have proper network connectivity. It can be a pain (and hit-and-miss in my experience) getting networking up and running on the old Windows Mobile emulators. (It's easy in Windows Phone 7.)
Load up Internet Explorer and see if that can make a connection to the same URL...
Additionally, you're not disposing of any of your resources (and if this code is really in a reference book exactly as you wrote it, that's a significant black mark against the book). For example, you should be disposing of the web response:
using (HttpWebResponse response = ...)
{
}
Likewise I would personally dispose of the response stream and the stream reader, just on general principle. I suspect that when the response is disposed, the stream will be too - but it makes sense to dispose of all streams etc unless you know you need to leave them undisposed.
If you're running in the emulator you'll ned to "cradle" the emulator and then create a partnership with ActiveSync (Win XP) or Windows Mobile Device Center (Vista or 7).
This will allow the emulator to share the network connection with the PC. You also need to do this even if you want to connect from the emulator to the PC.
As Jon mentions, in WP7 you don't need to make a connection in this way, the WP7 emulator automatically shares the network connection of the host PC.
Use IE Mobile (on the emulator) to check that the device can connect to the site.
Edit
To cradle the emulator, in VS2008 select "Device Emulator Manager" from the Tools menu. Select the emulator that's running, right click and select "Cradle".
Mobile Device Center should start automatically and ask if you want to create a partnership, just as if you'd connected a real device.

Get Windows Service Description ASP .NET

I'm writing a service monitoring ASP .NET app and I'm having issues particularly with getting the service descriptions. My current method (reading from registry) is not going to work due to registry read permissions on the production server.
For example:
Microsoft.Win32.RegistryKey system, currentControlSet, services, service;
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
currentControlSet = system.OpenSubKey("CurrentControlSet");
services = currentControlSet.OpenSubKey("Services");
service = services.OpenSubKey(scTemp.ServiceName, true);
row["service_description"] = service.GetValue("Description");
Produces:
System.Security.SecurityException: Requested registry access is not allowed.
My question is:
Is there a work-around with another .NET class (maybe under System.ServiceProcess namespace?) or will it always end with a security exception error?
I have no issues getting Service names and states with the System.ServiceProcess namespace but I can't find any classes contained to get descriptions which is why I resorted to reading from registry.
I think this should work.
EDIT: I should read questions closer. The code below gets the description for the first service in the array.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Management;
namespace ServiceNames
{
class Program
{
static void Main(string[] args)
{
ServiceController[] services = ServiceController.GetServices();
string serviceName = services[0].ServiceName;
string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
{
Console.WriteLine(service["Description"]);
}
Console.Read();
}
}
}
The previous answer showing the WMI solution is a good alternative and worth trying first.
--
I am not aware of a .NET Framework class that exposes the service description.
The first thing I would consider is requiring authenticated connections (e.g. NTLM) and impersonate the caller. As long as you don't do a double-hop (i.e. make a remote call with your impersonated credentials) you may find that you are able to successfully make the registery read.
If that is not possible then making a P/Invoke call may work.
If the credentials your web service has the SERVICE_QUERY_CONFIG permission you could do the following:
Find the service you are interested in using the ServiceController class
Using the ServiceHandle property make a P/Invoke call to QueryServiceConfig2 using the SERVICE_CONFIG_DESCRIPTION info level passing in null for the buffer and 0 for the lenght, reading the required buffer length from pcbBytesNeeded.
Allocate the proper buffer length and call QueryServiceConfig2 a second time getting the service description.
Obviously reading from the registery is a little more straight-forward (and in the end the permissions issues may be similar in both cases) - but using a supported API seems like a less fragile solution.
Side question: is there something you are trying to accomplish that PerfMon and logging can't tell you?

Categories

Resources