get the list of source files from existing eclipse project using CDT - eclipse-cdt

i am working on CDT eclipse plug in development, i am trying to get the list of sources files which exist in eclipse project explorer using CDT code using following code ,which results null.
Case1:
IFile[] files2 = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(new URI("file:/"+workingDirectory));
for (IFile file : files2) {
System.out.println("fullpath " +file.getFullPath());
}
Case2:
IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(getProject().getRawLocationURI());
for (IFile file : files) {
System.out.println("fullpath " +file.getFullPath());
}
Case3:
IFile[] files3 = ResourceLookup.findFilesByName(getProject().getFullPath(),ResourcesPlugin.getWorkspace().getRoot().getProjects(),false);
for (IFile file : files3) {
System.out.println("fullpath " +file.getFullPath());
}
Case4:
IFolder srcFolder = project.getFolder("src");
Case 1 ,2,3 giving me output null, where i am expecting list of files;
in Case 4: i am getting the list of "helloworld/src" files, but i am expecting to get the files from the existing project mean main root ,ex:"helloworld"
please suggest me on this.

You can either walk through the worspace resources tree using IResourceVisitor - or you can walk through CDT model:
private void findSourceFiles(final IProject project) {
final ICProject cproject = CoreModel.getDefault().create(project);
if (cproject != null) {
try {
cproject.accept(new ICElementVisitor() {
#Override
public boolean visit(final ICElement element) throws CoreException {
if (element.getElementType() == ICElement.C_UNIT) {
ITranslationUnit unit = (ITranslationUnit) element;
if (unit.isSourceUnit()) {
System.out.printf("%s, %s, %s\n", element.getElementName(), element.getClass(), element
.getUnderlyingResource().getFullPath());
}
return false;
} else {
return true;
}
}
});
} catch (final CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Note there may be more source files then you actually want (e.g. you may not care system about headers) - you can filter them by checking what the underlying resource is.

Related

Is there any way to get the Active Solution Configuration name in C# Code?

I have three solution configurations in my UWP solution in Visual Studio:
Development
Staging
Production
Each is a associated with a different web service and auth provider in the configuration files. In my code, how do I tell which one is which? In the past I've explicitly provided DEFINE constants, but there must be a better way by now.
The active solution configuration is stored in the .suo file beneath the .vs directory at the root solution folder. The .suo file has a compound file binary format, which means you can't just parse it with text manipulation tools.
However, using OpenMcdf -- a tool that can be used to manipulate these types of files -- you can easily get the active solution configuration.
Here's a console app I wrote that works. Feel free to adapt the code to your situation:
using OpenMcdf;
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace GetActiveBuildConfigFromSuo
{
internal enum ProgramReturnCode
{
Success = 0,
NoArg = -1,
InvalidFileFormat = -2
}
internal class Program
{
private const string SolutionConfigStreamName = "SolutionConfiguration";
private const string ActiveConfigTokenName = "ActiveCfg";
internal static int Main(string[] args)
{
try
{
ValidateCommandLineArgs(args);
string activeSolutionConfig = ExtractActiveSolutionConfig(
new FileInfo(args.First()));
throw new ProgramResultException(
activeSolutionConfig, ProgramReturnCode.Success);
}
catch (ProgramResultException e)
{
Console.Write(e.Message);
return (int)e.ReturnCode;
}
}
private static void ValidateCommandLineArgs(string[] args)
{
if (args.Count() != 1) throw new ProgramResultException(
"There must be exactly one command-line argument, which " +
"is the path to an input Visual Studio Solution User " +
"Options (SUO) file. The path should be enclosed in " +
"quotes if it contains spaces.", ProgramReturnCode.NoArg);
}
private static string ExtractActiveSolutionConfig(FileInfo fromSuoFile)
{
CompoundFile compoundFile;
try { compoundFile = new CompoundFile(fromSuoFile.FullName); }
catch (CFFileFormatException)
{ throw CreateInvalidFileFormatProgramResultException(fromSuoFile); }
if (compoundFile.RootStorage.TryGetStream(
SolutionConfigStreamName, out CFStream compoundFileStream))
{
var data = compoundFileStream.GetData();
string dataAsString = Encoding.GetEncoding("UTF-16").GetString(data);
int activeConfigTokenIndex = dataAsString.LastIndexOf(ActiveConfigTokenName);
if (activeConfigTokenIndex < 0)
CreateInvalidFileFormatProgramResultException(fromSuoFile);
string afterActiveConfigToken =
dataAsString.Substring(activeConfigTokenIndex);
int lastNullCharIdx = afterActiveConfigToken.LastIndexOf('\0');
string ret = afterActiveConfigToken.Substring(lastNullCharIdx + 1);
return ret.Replace(";", "");
}
else throw CreateInvalidFileFormatProgramResultException(fromSuoFile);
}
private static ProgramResultException CreateInvalidFileFormatProgramResultException(
FileInfo invalidFile) => new ProgramResultException(
$#"The provided file ""{invalidFile.FullName}"" is not a valid " +
$#"SUO file with a ""{SolutionConfigStreamName}"" stream and an " +
$#"""{ActiveConfigTokenName}"" token.", ProgramReturnCode.InvalidFileFormat);
}
internal class ProgramResultException : Exception
{
internal ProgramResultException(string message, ProgramReturnCode returnCode)
: base(message) => ReturnCode = returnCode;
internal ProgramReturnCode ReturnCode { get; }
}
}
Download DTE nuget packages : EnvDTE.8.0.2
Add below code
EnvDTE.DTE DTE = Marshal.GetActiveObject("VisualStudio.DTE.15.0") as EnvDTE.DTE;
var activeConfig = (string)DTE.Solution.Properties.Item("ActiveConfig").Value;

Extracting requierement properties from Capella

I would like to extract the requirements data in capella using m2doc, requirements (SystemFunctionalRequirement) are located in a "RequirementsPkg" package in System analysis, thanks to the "m:RequirementsPkg.eContents().summary" command I managed to retrieve the summary of all requirements but I would like to retrieve the name and the summary of a specific requirement.
Can you help me ?
Thanks in advance
This mechanism is deprecated. You should use the requirement extension.
Starting from the root element, you can use something like:
{ m:system.ownedArchitectures->filter(la::LogicalArchitecture).ownedRequirementPkgs.ownedRequirements.name }
With the requirement extension the easiest way is to create a service:
public List<Requirement> getRequirements(ExtensibleElement element) {
List<Requirement> res = new ArrayList<>();
for (ElementExtension extension : element.getOwnedExtensions()) {
if (extension instanceof Requirement) {
res.add((Requirement) extension);
break;
} else if (extension instanceof CapellaOutgoingRelation) {
res.add(((CapellaOutgoingRelation) extension).getTarget());
}
}
return res;
}
and call it, for instance on a diagram:
{ m:for req | '[LAB] IFE System - All Components, CEs'.representationByName().eAllContents(viewpoint::DRepresentationElement).semanticElements->filter(emde::ExtensibleElement).getRequirements() }
{ m:req.ReqIFLongName }
{ m:endfor }

VS 2015: Running Unit Tests from console, Selenium ChromeDriver problems

I'm 100% new here, and I'm not sure if anything else is expected before I post this question. But I didn't find anything about this exact issue when searching, so here goes:
I have a Solution framework using Selenium ChromeDriver for automating a web site, and an included Unit Test project for running the tests.
The tests can be run fine from the VS Test Explorer. But when I try running them from the VS console with
MSTest.exe /testcontainer:d:\Source\Workspaces\QA\Automation\Tests\bin\Debug\Tests.dll /resultsfile:d:\QA\testresults\autotests\regressiontests\tests.trx
i get these errors in the results file:
Test method Tests.BasicTests.Data.GetSiteData.GetMyElementId threw exception:
System.Exception: File not found
at Bytescout.Spreadsheet.Spreadsheet.LoadFromFile(String FileName, CacheType Cache, String Delimiter, Encoding Encoding, String Password)
at Bytescout.Spreadsheet.Spreadsheet.LoadFromFile(String FileName)
at TestData.Readers.ExcelByteScout.ExcelFindRows(String url, String sheetname, String value, Int32 col) in d:\Source\Workspaces\QA\FlowAutomation\TestData\Readers\EscelByteScout.cs:line 113
at TestData.SiteData.MyElements.GetElementId(String location, String element) in d:\Source\Workspaces\QA\Automation\TestData\SiteData\MyElements.cs:line 27
at Tests.BasicTests.Data.GetSiteData.GetMyElementId() in d:\Source\Workspaces\QA\Automation\Tests\BasicTests\Data\GetSiteData.cs:line 13
This is complaining about a Project -> Class in the solution which reads test data (user logins, CSS elements...) from an excel file.
and
Initialization method Tests.TestTests.OpenTests.OpenMyLabDrop2.Init threw exception. OpenQA.Selenium.DriverServiceNotFoundException: OpenQA.Selenium.DriverServiceNotFoundException: The chromedriver.exe file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at http://chromedriver.storage.googleapis.com/index.html..
at OpenQA.Selenium.DriverService.FindDriverServiceExecutable(String executableName, Uri downloadUrl)
at OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService()
at Common.Selenium.GCDriver.Initialize() in d:\Source\Workspaces\QA\FlowAutomation\Common\Selenium\GCDriver.cs:line 19
at FlowTests.Base.MyLabDrop2Test.Init() in d:\Source\Workspaces\QA\FlowAutomation\FlowTests\Base\MyLabDrop2Test.cs:line 15
this complains about a missing ChromeDriver.exe which is definetely not missing.
I'm not COMPLETELY new to VS and Selenium, but this I don't get, since the tests run fine from VS but complain about missing references from the console.
So I'm pretty sure there's something I'm missing when running the tests from the console, but what?
EDIT:
The relevant code from ExceByteScout.cs:
using System;
using System.Collections.Generic;
using Bytescout.Spreadsheet;
namespace TestData.Readers {
public class ExcelByteScout {
public static List<string> ExcelReturnXYZ(string url, string sheetname, string cell1, string cell2, string cell3) {
Spreadsheet document = new Spreadsheet();
document.LoadFromFile(url);
Worksheet worksheet = document.Workbook.Worksheets.ByName(sheetname);
List<string> cellvalues = new List<string>();
string name = worksheet.Cell(cell1).Value.ToString();
string user = worksheet.Cell(cell2).Value.ToString();
string pass = worksheet.Cell(cell3).Value.ToString();
cellvalues.Add(name);
cellvalues.Add(user);
cellvalues.Add(pass);
document.Close();
return cellvalues;
}
public static string[] ExcelFindRows(string url, string sheetname, string value, int col) {
Spreadsheet document = new Spreadsheet();
Worksheet worksheet = null;
List<string> values = new List<string>();
string[] userdata = null;
try {
document.LoadFromFile(url);
}
catch (System.Exception ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
throw;
}
try {
worksheet = document.Workbook.Worksheets.ByName(sheetname);
}
catch (System.NullReferenceException nrex) {
System.Diagnostics.Debug.WriteLine(nrex.Message);
throw;
}
int i = 0;
while (!worksheet.Cell(i, col).ValueAsString.Equals("")) {
if (worksheet.Cell(i, col).ValueAsString.Equals(value)) {
int rowcellcount = 0;
for (int y = 0; !worksheet.Cell(i, y).ValueAsString.Equals(""); y++) {
rowcellcount++;
}
userdata = new string[rowcellcount];
for (int x = 0; x < rowcellcount; x++) {
userdata[x] = worksheet.Cell(i, x).ValueAsString;
}
break;
}
i++;
}
document.Close();
return userdata
}
UPDATE:
The FileNotFound problem was due to a relative path.
But the ChromeDriver not found issue is a mystery. Specifically because this has worked before, in a different solution but with the exact same way of running the tests from the console.
Also, I'm standing in the /Debug folder of the project when I run MSTest.exe, and chromedriver.exe IS in this folder. I cannot see where else it needs to be?
File not found usually means that the file is not found on the location you expect it to be. This can happen because you run from an other path or the file is not copied.
Check the url before the line document.LoadFromFile(url); by Console.WriteLine(url). Then copy the excel to the correct location or fix the url.

Ubuntu Java watchservice is broken

This is my code to using monitor change folder:
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("/home/user/test/");
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Begin monitor to test folder: ");
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
// The filename is the
// context of the event.
#SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
if (filename.toString().startsWith(".")) continue;
if (kind == OVERFLOW) {
continue;
} else if (kind == ENTRY_CREATE) {
System.out.println(kind.name() + ":" +filename);
} else if (kind == ENTRY_DELETE) {
System.out.println(kind.name() + ":" +filename);
} else if (kind == ENTRY_MODIFY) {
System.out.println(kind.name() + ":" +filename);
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
It's great on windown, Mac os, However when run on ubuntu 16.04, I to face the problem:
For existed files in watched folder: when I edit a file then I receiver create event, While i want to get modify event
Please help me
Thanks.
Make sure that the program you're using to edit the file with in Ubuntu doesn't create a hidden file. Some editors do this to make sure no changes are lost when the program crashes.
So make sure that your editor does not create a hidden file when you're editing the file and if it does use another program or handle the hidden "subfile".

How can I find corrupt files in a SharePoint 2013 ListItemCollection using CSOM

I have a CSOM program that transfers hundreds PDF files into SharePoint 2013 libraries. Once in a while one of those transferred files will be corrupt and can't be opened. The source file is good and the same file can be opened after having been transferred to other libraries but in one random library it will be corrupt.
I want to loop through the libraries, find the corrupt files and delete them but how can I tell using CSOM if the file is corrupt? I tried looping through and using File.OpenBinaryStream() but that succeeds on the corrupt files. Below is the code that reads the library and loops through the files. Any suggestions would be appreciated.
using (ClientContext destContext = new ClientContext(clientSite.Value))
{
destContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
destContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo(ClientSiteUsername, ClientSitePassword);
// get the new list
Web destWeb = destContext.Web;
ListCollection lists = destWeb.Lists;
List selectedList = lists.GetByTitle(clientLibraryName);
destContext.Load(lists);
destContext.Load(selectedList);
ListItemCollection clientCurrentItemsList = selectedList.GetItems(CamlQuery.CreateAllItemsQuery());
destContext.Load(clientCurrentItemsList,
eachItem => eachItem.Include(
item => item,
item => item["ID"],
item => item["FileLeafRef"]));
try
{
destContext.ExecuteQuery();
}
catch (Exception ex)
{
log.Warn(String.Format("Error in VerifyClientDocuments. Could not read client library: {0}", clientSite.Value), ex);
continue;
}
foreach (ListItem item in clientCurrentItemsList)
{
try
{
item.File.OpenBinaryStream();
}
catch (Exception ex)
{
var val = ex.Message;
//delete here
}
}
}
What worked was checking the size of the new file against the expected file size. The corrupt files actually report a 0 byte size so I deleted those then re-added them later.
for (var counter = clientCurrentItemsList.Count; counter > 0; counter--)
{
var clientFileSize = clientCurrentItemsList[counter - 1].FieldValues.
Where(x => x.Key == "File_x0020_Size").FirstOrDefault().Value.ToString();
var fileName = clientCurrentItemsList[counter - 1].FieldValues.
Where(x => x.Key == "FileLeafRef").FirstOrDefault().Value.ToString();
var serverFileSize = approvedDocumentList.Where(x => x.FieldValues["FileLeafRef"].ToString() ==
fileName).FirstOrDefault().FieldValues["File_x0020_Size"].ToString();
if (clientFileSize != serverFileSize)
{
clientCurrentItemsList[counter - 1].DeleteObject();
destContext.ExecuteQuery();
log.Info(String.Format("File [{0}] deleted from {1} File type {2} - Reason: Client file was corrupt",
fileName, clientSiteURL, documentType.ToString()));
}
}