public static void GetServices() {
var serviceList = new List<string>();
var servicePathList = new List<string>();
ServiceController[] services = ServiceController.GetServices();
foreach (var service in services)
{
serviceList.Add(service.DisplayName);
}
serviceList.Sort();
int serviceCount = 0;
foreach (var service in serviceList)
{
serviceCount++;
Console.WriteLine(serviceCount.ToString() + " - " + service);
}
}
Above code lists the names of the windows services installed. But I also want to get the Physical path of it. Any help?
Related
How to get the below high lighted data from windows services using c#?
I have tried the below code to get the path to executable
private string GetInstallationPath(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName)
{
return service.GetType().Assembly.Location.ToString();
}
}
return string.Empty;
}
But it does not return the exe exutable path.
AFAIK it can't be done via ServiceController API. You can use WMI:
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
var result = searcher.Get()
.OfType<ManagementBaseObject>()
.Select(mo => new
{
Name = mo["Name"] as string,
Path = mo["PathName"] as string
})
.ToArray();
I wanted to fetch all files from the document library one of my Online Sharepoint site.
For that, I have created 2 apps i.e. Console App and ASP.Net MVC apps
Below is the code,
using ASPNetDemo.Models;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web.Mvc;
namespace ASPNetDemo.Controllers
{
public class DocumentLibraryController : Controller
{
private readonly string baseURL;
private readonly string siteURL;
public DocumentLibraryController()
{
baseURL = "https://onevirtualoffice.sharepoint.com";
siteURL = $"{baseURL}/sites/mysite";
}
// GET: DocumentLibrary
public ActionResult Index()
{
var model = new FileUploadViewModel();
model.Username = "firstname.lastname#domain.com";
model.Password = "{password}";
var list = GetFiles(model);// get all files from
return View();
}
public List<string> GetFiles(FileUploadViewModel model)
{
try
{
using (var clientContext = new ClientContext(siteURL))
{
SecureString passWordSecure = new SecureString();
foreach (char c in model.Password.ToCharArray()) passWordSecure.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(model.Username, passWordSecure);
Web web = clientContext.Web;
#region get list
List<string> fileList = new List<string>();
var results = new Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.File>>();
var lists = clientContext.LoadQuery(clientContext.Web.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary));
clientContext.ExecuteQuery();
foreach (var list in lists)
{
if (list.Title.Equals("TestFolder"))
{
var items = list.GetItems(CreateAllFilesQuery());
clientContext.Load(items, icol => icol.Include(i => i.File));
results[list.Title] = items.Select(i => i.File);
}
}
clientContext.ExecuteQuery();
foreach (var result in results)
{
foreach (var file in result.Value)
{
var fileName = "";
if (string.IsNullOrEmpty(file.LinkingUri))
fileName = string.Concat(baseURL, file.ServerRelativeUrl);
else
fileName = file.LinkingUri;
fileList.Add(fileName);
}
}
return fileList;
#endregion
}
}
catch (Exception ex)
{
throw ex;
}
}
private CamlQuery CreateAllFilesQuery()
{
var qry = new CamlQuery();
qry.ViewXml = "<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FSObjType\" /><Value Type=\"Integer\">0</Value></Eq></Where></Query></View>";
return qry;
}
}
}
The above code is working fine in Console application and its fetching all the files under TestFolder document library. But When I tried the same code in ASP.Net MVC5 Framework 4.6.1 then it throwing an exception as The sign-in name or password does not match one in the Microsoft account system.
Could you please help to guide where I am wrong.
I have a ASP.NET MVC web application. I want to show the number of LIVE users from a website.
How can I read this from Google Analytics?
I have already followed this guide:
http://www.markwemekamp.com/blog/c/how-to-read-from-google-analytics-using-c/
But I can't get the code to work. It keeps on running and gives a System.NullReferenceException.
So I hope there are people with better idea's or guides here. And please, only complete guides with every detail in it. Not those half guide where you don't know what to do.
Thanks in Advance.
Update:
This is the code from the guide that I am using. I only added the date's. I am using the code in de Global.asax.cs file.
The Null exception occures on this piece of code:
foreach (var x in response.Reports.First().Data.Rows)
{
Debug.WriteLine("The next line doesn't appear: seee.....");
Debug.WriteLine(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
Code:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
UnityConfig.RegisterComponents();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<EFDbContext>(null);
MethodSomethingGoogle();
}
public void MethodSomethingGoogle()
{
string todaysDate = DateTime.Now.ToString("yyyy-MM-dd");
string tomorrowsDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
try
{
var filepath = #"C:\Users\ckersten\Downloads\Dashboard-Match-Online-b2f3f0b438a1.json";
var filepath2 = #"~\App_Data\Dashboard-Match-Online-b2f3f0b438a1.json";
// path to the json file for the Service account
var viewid = "109154097"; // id of the view you want to read from
Googl
eCredential credentials;
using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
var googleCredential = GoogleCredential.FromStream(stream);
credentials = googleCredential.CreateScoped(scopes);
}
var reportingService = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credentials
});
var dateRange = new DateRange
{
StartDate = todaysDate,
EndDate = tomorrowsDate
};
var sessions = new Metric
{
Expression = "ga:pageviews",
Alias = "Sessions"
};
var date = new Dimension { Name = "ga:date" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date },
Metrics = new List<Metric> { sessions },
ViewId = viewid
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach (var x in response.Reports.First().Data.Rows)
{
Debug.WriteLine("The next line doesn't appear: seee.....");
Debug.WriteLine(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
}
catch (Exception e)
{
Debug.WriteLine("Google Exception: " + e.ToString());
}
Debug.WriteLine(Console.ReadLine());
}
Your code uses the reporting api which isnt going to give you real time data. Data in the reporting api wont be done processing for 24 -48 hours .
You should be using the realtime api if you want to see whats going on now. Just remember that you can only make 10000 requests against the api a day per view.
DataResource.RealtimeResource.GetRequest request =
service.Data.Realtime.Get(String.Format("ga:{0}", profileId), "rt:activeUsers");
RealtimeData feed = request.Execute();
foreach (List row in realTimeData.Rows)
{
foreach (string col in row)
{
Console.Write(col + " "); // writes the value of the column
}
Console.Write("\r\n");
}
My tutorial on the realtime api here GitHub sample project can be found here you also might want to consider using a service account
Note:
The Real Time Reporting API, in limited beta, is available for developer preview only. Sign up to access the API.
I want to be able to publish a separate C# project programmatically. When I run the following code I want it to publish my Repair.csproj project.
What I'm doing here is I'm getting the version number from my code. I then increment it by one, delete everything in the publish folder and then try to publish my project.
However when I run this code it doesn't publish my Repair.csproj. I'm not sure where I'm going wrong.
My code is as follows
public const string publishLocation = #"C:\Workspace_User\Repair\MAIN\Publish";
public const string RepairLocation = #"C:\Workspace_User\Repair\MAIN\Repair.sln";
public const string repairproj = #"C:\Workspace_User\Repair\MAIN\Repair\Repair.csproj";
public const string r = #"C:\Workspace_User\Repair\MAIN\Repair\bin\Release\Repair.dll";
static void Main(string[] args)
{
Microsoft.Build.BuildEngine.Engine.GlobalEngine.BuildEnabled = true;
System.IO.DirectoryInfo di = new DirectoryInfo(publishLocation);
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(RepairLocation);
var version= AssemblyName.GetAssemblyName(r).Version;
var splitVersionNumber= version.ToString().Split('.');
var getNumber = splitVersionNumber[3];
var addInt=Convert.ToInt32(getNumber);
addInt++;
foreach (FileInfo file in di.GetFiles())
{
if (file.Name!="Working Folder")
{
file.Delete();
}
}
buildMethod();
}
public static object buildMethod()
{
var props = new Dictionary<string, string>();
props["Configuration"] = "Publish";
var request = new BuildRequestData(repairproj, props, null, new string[] { "Build" }, null);
var parms = new BuildParameters();
// parms.Loggers = ...;
var result = BuildManager.DefaultBuildManager.Build(parms, request);
Debug.Write(result);
return result.OverallResult == BuildResultCode.Success;
}
I am trying to find a txt files over computers of a domain network.
What I have done till now:
I have the list of all computers of the domain in an array.So I am iterating each computer with its corresponding address with the help of getfile command.
Where I am stuck :
There are some computers over which I don't have access.So my search is either taking a long time to leap those exceptions or it gets struck at some point.As there are more that 500 systems so I want to increase the speed and accuracy of my program.
I am mostly getting network not found error.
Here is my code:
namespace ABC
{
class Program
{
static void Main(string[] args)
{
List<string> cnames=new List<string>();
DirectoryEntry entry = new DirectoryEntry("LDAP://abc.com", "username", "password", AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)");
foreach (SearchResult resEnt in mySearcher.FindAll())
{
string name = resEnt.GetDirectoryEntry().Name;
if (name.StartsWith("CN="))
name = name.Remove(0, "CN=".Length);
cnames.Add(name);
}
int cnumbers=cnames.Count;
for (int i = 0; i < cnumbers;i++ )
{
string s = "\\\\" + cnames[i] + "\\ab\\cd";
string[] dirs = null;
Console.WriteLine("Name of Computer=" + cnames[i]);
try
{
dirs = Directory.GetFiles(s);
try
{
foreach (string dir in dirs)
{
Console.WriteLine(dir);
}
}
catch (Exception e)
{
}
}
catch (Exception)
{
}
}
}
}
}