HealthKit capabilities are not adding through unity c# script - c#

Can anyone help me to resolve my healthKit capability issue for a unity app.
I am trying to add healthKit capability to my unity app. I am using BEHEALTHKIT and HealthKitBuildProcessor.cs editor class to add capability and other dependencies. Following are the code I am using .But for some reason healthkit Capability and entitlements are not adding through this code (permission parameters are adding to plist), and returning null when I print Debug.Log("newEntitlements: " + newEntitlements);Also my build failing with an error saying "provisioning profile doesn't support the HealthKit Capability"
I have already added HealthKit capability for the profile from developer.apple.com.
Unity version: 2019.4.4f1
public class HealthKitBuildProcessor : IProcessSceneWithReport
{
private static string shareString = null;
private static string updateString = null;
private static string clinicalString = null;
/*! #brief required by the IProcessScene interface. Set high to let other postprocess scripts run first. */
public int callbackOrder {
get { return 100; }
}
/*! #brief Searches for HealthKitDataTypes objects & reads the usage strings for the OnPostprocessBuild phase.
#param scene the scene being processed.
#param report a report containing information about the current build
*/
public void OnProcessScene(Scene scene, BuildReport report) {
GameObject[] rootObjects = scene.GetRootGameObjects();
foreach (GameObject obj in rootObjects) {
HealthKitDataTypes types = obj.GetComponentInChildren<HealthKitDataTypes>();
if (types != null) {
if (types.AskForSharePermission()) {
HealthKitBuildProcessor.shareString = types.healthShareUsageDescription;
}
if (types.AskForUpdatePermission()) {
HealthKitBuildProcessor.updateString = types.healthUpdateUsageDescription;
}
/*if (types.AskForClinicalPermission()) {
HealthKitBuildProcessor.clinicalString = types.clinicalUsageDescription;
}*/
}
}
}
/*! #brief Updates the Xcode project.
#param buildTarget the target build platform
#param path the path of the target build
*/
[PostProcessBuildAttribute(10)]
public static void OnPostprocessBuild(BuildTarget buildTarget, string path) {
Debug.Log("--- BEHEALTHKIT POST-PROCESS BUILD ---");
if (buildTarget == BuildTarget.iOS) {
//string projPath = path + "/Unity-iPhone.xcodeproj/project.pbxproj";
//Debug.Log("BE:PROJECT PATH :" + projPath);
var projPath = PBXProject.GetPBXProjectPath(path);
var proj = new PBXProject();
proj.ReadFromString(System.IO.File.ReadAllText(projPath));
#if UNITY_2019_3_OR_NEWER
string mainTarget = proj.GetUnityMainTargetGuid();
string frameworkTarget = proj.GetUnityFrameworkTargetGuid();
Debug.Log("--- BE: UNITY_2019_3_OR_NEWER ---");
Debug.LogFormat("main target: {0}", mainTarget);
Debug.LogFormat("framework target: {0}", frameworkTarget);
#else
string targetName = PBXProject.GetUnityTargetName();
string mainTarget = proj.TargetGuidByName(targetName);
Debug.Log("---BE: ELSE UNITY_2019_3_OR_NEWER ---");
Debug.Log("main target: {0}", mainTarget);
Debug.Log("targetName: ", targetName);
#endif
bool addHealthRecordsCapability = (clinicalString != null);
//Debug.Log("addHealthRecordsCapability: ", addHealthRecordsCapability);
// Info.plist
//-----------
Debug.Log("---BE: PLIST ---");
var info = ProcessInfoPList(path, addHealthRecordsCapability);
// Entitlements
//--------------
Debug.Log("---BE: ProcessEntitlements ---");
string entitlementsRelative = ProcessEntitlements(path, proj, mainTarget, info, addHealthRecordsCapability);
#if UNITY_2019_3_OR_NEWER
// add HealthKit capability
Debug.Log("------projPath "+projPath);
ProjectCapabilityManager capabilities = new ProjectCapabilityManager(projPath, "Entitlements.entitlements", null, mainTarget);
capabilities.AddHealthKit();
Debug.Log("---BE:Capability UNITY_2019_3_OR_NEWER ---");
// add HealthKit Framework
//proj.AddFrameworkToProject(frameworkTarget, "HealthKit.framework", true);
// Set a custom link flag
//proj.AddBuildProperty(frameworkTarget, "OTHER_LDFLAGS", "-ObjC");
#else
// add HealthKit capability
Debug.Log("---ELSE BE:Capability UNITY_2019_3_OR_NEWER ---");
Debug.Log("projectPath:" + projPath);
Debug.Log("entitlementsRelative:" + entitlementsRelative);
Debug.Log("targetName:" + targetName);
ProjectCapabilityManager capabilities = new ProjectCapabilityManager(projPath, entitlementsRelative, targetName);
capabilities.AddHealthKit();
// add HealthKit Framework
proj.AddFrameworkToProject(mainTarget, "HealthKit.framework", true);
// Set a custom link flag
proj.AddBuildProperty(mainTarget, "OTHER_LDFLAGS", "-ObjC");
#endif
proj.WriteToFile(projPath);
}
}
// -------------------------------
internal static PlistDocument ProcessInfoPList(string path, bool addHealthRecordsCapability) {
string plistPath = Path.Combine(path, "Info.plist");
PlistDocument info = GetInfoPlist(plistPath);
PlistElementDict rootDict = info.root;
// // Add the keys
if (HealthKitBuildProcessor.shareString != null) {
rootDict.SetString("NSHealthShareUsageDescription", HealthKitBuildProcessor.shareString);
}
else {
Debug.LogError("unable to read NSHealthShareUsageDescription");
}
if (HealthKitBuildProcessor.updateString != null) {
rootDict.SetString("NSHealthUpdateUsageDescription", HealthKitBuildProcessor.updateString);
}
if (addHealthRecordsCapability) {
rootDict.SetString("NSHealthClinicalHealthRecordsShareUsageDescription", HealthKitBuildProcessor.clinicalString);
}
// Write the file
info.WriteToFile(plistPath);
return info;
}
internal static string ProcessEntitlements(string path, PBXProject proj, string target, PlistDocument info, bool addHealthRecordsCapability) {
string entitlementsFile;
string entitlementsRelative;
string entitlementsPath;
Debug.Log("PATH: " + path);
Debug.Log("TARGET: " + target);
String test= proj.GetUnityMainTargetGuid();
Debug.Log("TEST proj: " + test);
entitlementsRelative = proj.GetBuildPropertyForConfig(target, "CODE_SIGN_ENTITLEMENTS");
Debug.Log("entitlementsRelative: " + entitlementsRelative);
Debug.LogFormat("get build property [{0}, {1} = {2}]", target, "CODE_SIGN_ENTITLEMENTS", entitlementsRelative);
PlistDocument entitlements = new PlistDocument();
if (entitlementsRelative == null) {
string projectname = GetProjectName(info);
Debug.Log("projectname: " + projectname);
entitlementsFile = Path.ChangeExtension("Entitlements", "entitlements");
Debug.Log("entitlementsFile: " + entitlementsFile);
entitlementsRelative = Path.Combine(path, entitlementsFile);
Debug.Log("entitlementsRelative: " + entitlementsRelative);
entitlementsPath = Path.Combine(path, entitlementsRelative);
Debug.Log("entitlementsPath: " + entitlementsPath);
//proj.AddFileToBuild(target, proj.AddFile(entitlementsRelative, entitlementsRelative, PBXSourceTree.Source));
Debug.LogFormat("add build property [{0}, {1}] => {2}", target, "CODE_SIGN_ENTITLEMENTS", entitlementsRelative);
proj.AddBuildProperty(target, "CODE_SIGN_ENTITLEMENTS", entitlementsFile);
string newEntitlements = proj.GetBuildPropertyForConfig(target, "CODE_SIGN_ENTITLEMENTS");
Debug.Log("newEntitlements: " + newEntitlements);
Debug.LogFormat("=> {0}", newEntitlements);
}
else {
entitlementsPath = Path.Combine(path, entitlementsRelative);
Debug.Log("ELSE:entitlementsPath " + entitlementsPath);
}
ReadEntitlements(entitlements, entitlementsPath);
entitlements.root.SetBoolean("com.apple.developer.healthkit", true);
if (addHealthRecordsCapability) {
Debug.Log("addHealthRecordsCapability =TRUE ");
var healthkitAccess = entitlements.root.CreateArray("com.apple.developer.healthkit.access");
healthkitAccess.AddString("health-records");
}
SaveEntitlements(entitlements, entitlementsPath);
return entitlementsRelative;
}
// -------------------------------
internal static void ReadEntitlements(PlistDocument entitlements, string destinationPath) {
Debug.Log("READING Entitlements [ReadEntitlements]");
Debug.Log("READING from destinationPath [ReadEntitlements]"+ destinationPath);
if (System.IO.File.Exists(destinationPath)) {
try {
Debug.LogFormat("reading existing entitlements: '{0}'.", destinationPath);
entitlements.ReadFromFile(destinationPath);
}
catch (Exception e) {
Debug.LogErrorFormat("error reading from file: {0}", e);
}
}
}
internal static void SaveEntitlements(PlistDocument entitlements, string destinationPath) {
try {
Debug.Log("----SaveEntitlements---");
entitlements.WriteToFile(destinationPath);
}
catch (Exception e) {
Debug.LogErrorFormat("error writing to file: {0}", e);
}
}
internal static PlistDocument GetInfoPlist(string plistPath) {
// Get the plist file
PlistDocument plist = new PlistDocument();
plist.ReadFromFile(plistPath);
return plist;
}
internal static string GetProjectName(PlistDocument plist) {
string projectname = plist.root["CFBundleDisplayName"].AsString();
return projectname;
}
}

I don't know about Unity, but from Xcode when you add a capability for health kit it will update the entitlement file by itself

Related

StockFish Chess Engine won't work on Android Device but, works on Standalone Build and Unity editor perfectly

I have been working on a chess game and using the Stockfish chess engine to implement AI in it. I was successful in firing up the executable file, sending fen code as input and receiving the output from the engine. It works perfectly on unity editor and standalone build. But, It won't work for the android device. I have no idea why.
I have made sure that the file is copied/created to the right directory and is successful. Can someone please help me figure out this issue?
string fen;
public static Process mProcess;
void Start()
{
Setup();
}
public void Setup()
{
// since the apk file is archived this code retreives the stockfish binary data and
// creates a copy of it in the persistantdatapath location.
#if UNITY_EDITOR
string filepath = "D:\\Chess Projects\\StockFishTest\\Assets\\StreamingAssets\\stockfish_10_x64.exe";
#elif UNITY_ANDROID
string filepath = Application.persistentDataPath + "/" + "stockfish-10-armv7";
Debug.Log(filepath);
if (!File.Exists(filepath))
{
WWW executable = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "stockfish-10-armv7");
while (!executable.isDone)
{
}
File.WriteAllBytes(filepath, executable.bytes);
//change permissions via plugin
}
var plugin = new AndroidJavaClass("com.chessbattles.jeyasurya.consoleplugin.AndroidConsole");
string command = "chmod 777 "+filepath;
outPut = plugin.CallStatic<string>("ExecuteCommand",command);
#else
string filepath = Application.streamingAssetsPath+ "/" + "stockfish_10_x64.exe";
#endif
// creating the process and communicating with the engine
mProcess = new Process();
ProcessStartInfo si = new ProcessStartInfo()
{
FileName = filepath,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
mProcess.StartInfo = si;
mProcess.OutputDataReceived += new DataReceivedEventHandler(MProcess_OutputDataReceived);
mProcess.Start();
mProcess.BeginErrorReadLine();
mProcess.BeginOutputReadLine();
SendLine("uci");
SendLine("isready");
}
public void GetMove(string fen, int processTime = 0, int DepthValue = 1)
{
if(fen ==null || fen == ""){
UnityEngine.Debug.LogError("Enter proper Fen");
Debug.Log("Enter proper Fen");
return;
}
SendLine("position fen "+ fen);
if(processTime != 0){
SendLine("go movetime "+processTime);
}
else if(DepthValue != 0)
{
SendLine("go depth "+ DepthValue);
}
else
{
SendLine("go depth " + DepthValue);
}
}
public string output = "";
public bool moveReady = false;
public void SendLine(string command) {
mProcess.StandardInput.WriteLine(command);
mProcess.StandardInput.Flush();
}
void MProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
output = "";
// UnityEngine.Debug.Log("Output: " + e.Data);
output = e.Data;
if (output.Length != 0)
if (output[0] == 'b' && output[3] == 't')
{
output = e.Data.Substring(9, 4);
// Debug.Log(output);
moveReady = true;
}
else
{
moveReady = false;
}
}
I have managed to make this work like this. You need to update the package name in the file path.
using System.Diagnostics;
using System.IO;
using UnityEngine;
namespace Assets.Scripts
{
public class EngineCommunicator
{
public static Process mProcess;
public static string fileName = "stockfish.android.armv7";
public static void Communicate()
{
#if UNITY_EDITOR
string filepath = "E:\\Personal\\Unity\\Chess2d\\Assets\\Plugins\\Windows\\stockfish_13_win_x64";
#elif UNITY_ANDROID
string filepath = "/data/data/com.tiringbring.Chess2d/lib/stockfish.android.armv7.so";
UI.Instance.AddJob(() =>
{
UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text = filepath;
});
if (!File.Exists(filepath))
{
UI.Instance.AddJob(() =>
{
UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text =UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text +" "+ "file not found";
});
}else{
UI.Instance.AddJob(() =>
{
UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text =UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text +" "+ "file found";
});
}
#else
string filepath = Application.streamingAssetsPath+ "/" + "stockfish_13_x64.exe";
#endif
// creating the process and communicating with the engine
mProcess = new Process();
ProcessStartInfo si = new ProcessStartInfo()
{
FileName = filepath,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
mProcess.StartInfo = si;
mProcess.OutputDataReceived += new DataReceivedEventHandler(MProcess_OutputDataReceived);
mProcess.Start();
mProcess.BeginErrorReadLine();
mProcess.BeginOutputReadLine();
SendLine("uci");
SendLine("isready");
SendLine("ucinewgame");
SendLine("position startpos");
SendLine("go infinite searchmoves e2e4 d2d4");
}
private static void SendLine(string command)
{
mProcess.StandardInput.WriteLine(command);
mProcess.StandardInput.Flush();
}
private static void MProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string text = e.Data;
UI.Instance.AddJob(() =>
{
UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text = UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text +" "+ text;
});
UnityEngine.Debug.Log(text);
}
}
}
Put the file in Assets/Android directory with .so extension.
It will be copied automatically in lib folder on android mobile

Copy Files and Folders Checking for existence

(Newer to C#)
I have an application that I have built that copies files and folders from one location to another. I originally had issues with folders. For some reason, it would try to copy the file over without creating the directory. I solved that by adding a second section to check if the folder exists and if not create it. I am sure there is a better way to handle this, but this is what worked, so I went with it. The ultimate goal is this.
check if the file/folder exists in the destination location and is older than the source file/folder
If the file/folder doesn't exist, copy it over. If the file/folder is older than the source, copy it over.
If the file folder exists in the destination and not in the source (indicating it was deleted) move the file from the destination location to an archive folder
Below is what I have so far, and it does everything but what is described in #3 above. Any ideas in regards to how I can add the ability from #3 into the functionality, or simplify the copy of files and create the folder if it doesn't exist would be much appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileCopy
{
class Program
{
public static string dtnow = DateTime.Now.ToString("mmdd_hhmm");
public static string watch_path = string.Empty;
public static string copy_path = string.Empty;
public static string final_copy_path = string.Empty;
public static string log_folder = #"C:\copylogs";
//public static string log_file = "copy_log";
public static string log_file = Path.Combine(log_folder + "\\copy_log" + dtnow + ".txt");
public static int newer_count = 0;
public static int skip_count = 0;
public static int copy_count = 0;
public static int totalcount = 0;
public static int currentcount = 0;
static void Main(string[] args)
{
if (args == null || args.Length < 2)
{
Console.WriteLine("Invalid Syntax");
return;
}
else
{
watch_path = args[0];
copy_path = args[1];
log_start_Check(log_folder,log_file);
CopyFolder(watch_path, copy_path);
finalcount_statement();
}
}
// Log Folder check and creation
public static void log_start_Check(string log_folder, string log_file)
{
Console.Write("Checking Log Folder: ");
if (!Directory.Exists(log_folder))
{
try
{
Directory.CreateDirectory(log_folder);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create Directory" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.Write("Checking Log File: ");
//Console.WriteLine(log_file);
if (!File.Exists(log_file))
{
try
{
File.Create(log_file);
Console.WriteLine("Created!");
}
catch (Exception error)
{
Console.WriteLine("Unable to Create file" + error);
return;
}
}
else
{
Console.WriteLine("Exists");
}
Console.WriteLine();
}
// Copy Folder Functions
static public void CopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(destFolder))
Directory.CreateDirectory(destFolder);
totalcount = Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories).Count();
string[] files = Directory.GetFiles(sourceFolder);
totalcount = files.Length;
foreach (string file in files)
{
string name = Path.GetFileName(file);
FileInfo source_info = new FileInfo(file);
string dest = Path.Combine(destFolder, name);
FileInfo dest_info = new FileInfo(dest);
if (File.Exists(dest))
{
try
{
if (source_info.LastWriteTime > dest_info.LastWriteTime)
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
File.Copy(file, dest, true);
Console.Write("\rFile Newer, File Copied " + dest + " ");
Console.ResetColor();
newer_count++;
}
else
{
//Console.Write("\r" + currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("\r** - File Exists " + dest + " ");
Console.ResetColor();
skip_count++;
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
else
{
try
{
//Console.Write("\r"+currentcount + " of " + totalcount + " Completed ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
File.Copy(file, dest, false);
Console.Write("\rFile Copied " + dest + " ");
Console.ResetColor();
copy_count++;
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, dest, file);
}
}
currentcount++;
}
string[] folders = Directory.GetDirectories(sourceFolder);
foreach (string folder in folders)
{
string name = Path.GetFileName(folder);
string dest = Path.Combine(destFolder, name);
CopyFolder(folder, dest);
}
}
catch (Exception error)
{
error_handling("Error in Application " + error.Message, null, null);
}
}
// Error Handling to add messages to logs
public static void error_handling(string message, string fileident, string source)
{
using (System.IO.StreamWriter myFile = new System.IO.StreamWriter(log_file, true))
{
string finalMessage = string.Format("{0}: {1} SOURCE: {3} - DEST: {2}", DateTime.Now, message, fileident, source, Environment.NewLine);
myFile.WriteLine(finalMessage);
myFile.Close();
}
}
// Final Statement
public static void finalcount_statement()
{
Console.WriteLine("");
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("Total New Files Copied: " + copy_count);
Console.WriteLine("Total Newer Files Updated: " + newer_count);
Console.WriteLine("Total Files Skipped: " + skip_count);
Console.WriteLine("--------------------------------------------------------------------------------------------");
Console.WriteLine("");
Console.WriteLine("");
}
}
}
You can do it the same way around, maybe like this:
static public void ArchiveCopyFolder(string sourceFolder, string destFolder)
{
try
{
if (!Directory.Exists(sourceFolder))
{
Directory.CreateDirectory(archivefolder + destFolder);
//Copy folder and files
}
}
}

Driver is null when taking a screenshot

In my spec-flow project, I have created static Screenshot class. I have also created static methods to take screen shots. But at run time, my driver is consistently null. How can I solve this problem.
Below is the code snippet:
public static class Screenshot
{
public static void TakeScreenshots(this IWebDriver driver, string path = #"result")
{
var takescreenshot = (driver as ITakesScreenshot) != null;
if (!takescreenshot)
return;
var filename = string.Empty + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
filename = path + #"\" + filename + ".png";
var ss = ((ITakesScreenshot)driver).GetScreenshot();
var screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
ss.SaveAsFile(filename, ScreenshotImageFormat.Png);
}
}
I call in my afterstep hook like so:
[AfterStep()]
public static void AfterStep()
{
if (ScenarioContext.Current.TestError == null)
{
stepStatus = Status.Pass;
}
else
{
ScreenShot.TakeScreenshots(driver);
}
test.Log(stepStatus, stepLogText);
}

versioncontrol.GetAllTeamProjects() returning 0

I'm working on a project where I'll have a C# application search all TFS project's .cs files for a string or string patterns. I found some code that looks similar to what I was looking to do here.
namespace TFSSearch
{
class Program
{
static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" }; //Text to search
static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html",
"*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions
static void Main(string[] args)
{
try
{
var tfs = TfsTeamProjectCollectionFactory
.GetTeamProjectCollection(new Uri("https://{tfsserver}/tfs"));
tfs.EnsureAuthenticated();
var versionControl = tfs.GetService<VersionControlServer>();
StreamWriter outputFile = new StreamWriter(#"C:\Find.txt");
var allProjs = versionControl.GetAllTeamProjects(true);
foreach (var teamProj in allProjs)
{
foreach (var filePattern in filePatterns)
{
var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
.Where(i => !i.ServerItem.Contains("_ReSharper")); //skipping resharper stuff
foreach (var item in items)
{
List<string> lines = SearchInFile(item);
if (lines.Count > 0)
{
outputFile.WriteLine("FILE:" + item.ServerItem);
outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
outputFile.WriteLine();
}
foreach (string line in lines)
{
outputFile.WriteLine(line);
}
if (lines.Count > 0)
{
outputFile.WriteLine();
}
}
}
outputFile.Flush();
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
Console.WriteLine("========");
Console.Read();
}
// Define other methods and classes here
private static List<string> SearchInFile(Item file)
{
var result = new List<string>();
try
{
var stream = new StreamReader(file.DownloadFile(), Encoding.Default);
var line = stream.ReadLine();
var lineIndex = 0;
while (!stream.EndOfStream)
{
if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
result.Add("=== Line " + lineIndex + ": " + line.Trim());
line = stream.ReadLine();
lineIndex++;
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
return result;
}
}
}
The problem I'm having is when I try to get the projects using versionControl.GetAllTeamProjects(true); allProjs seems to get no information back. It is an empty array of TeamProject. When I debug, tfs.HasAuthenticated is true and it doesn't throw any exceptions. The TFS server is on a https domain. How can I make sure I'm exactly connecting to TFS?
I test at my side, everything works correctly.
Install the Nuget package
Microsoft.TeamFoundationServer.ExtendedClient by running below
command in Package Manager Console:
PM> Install-Package Microsoft.TeamFoundationServer.ExtendedClient -Version 15.112.1
Make sure you specify the correct TFS server,
eg : http://servername:8080/tfs/DefaultCollection
Then check it again.

Gurobi does not recognize LP file

When trying to open a Linear Programming problem from text with Gurobi+C# it throws the error: 10012 Unable to open file "Maximize" for input.
Maximise is the first word of the text and when using
foreach (string s in args)
{
Console.WriteLine(s);
}
i get the correct output from the text file. Please help!
using System;
using Gurobi;
class lp_cs
{
static void Main(string[] args)
{
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
foreach (string s in args)
{
Console.WriteLine(s);
}
if (args.Length < 1)
{
Console.Out.WriteLine("Please Wait..");
return;
}
try
{
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Optimize();
int optimstatus = model.Get(GRB.IntAttr.Status);
if (optimstatus == GRB.Status.INF_OR_UNBD)
{
model.GetEnv().Set(GRB.IntParam.Presolve, 0);
model.Optimize();
optimstatus = model.Get(GRB.IntAttr.Status);
}
if (optimstatus == GRB.Status.OPTIMAL)
{
double objval = model.Get(GRB.DoubleAttr.ObjVal);
Console.WriteLine("Optimal objective: " + objval);
}
else if (optimstatus == GRB.Status.INFEASIBLE)
{
Console.WriteLine("Model is infeasible");
model.ComputeIIS();
model.Write("model.ilp");
}
else if (optimstatus == GRB.Status.UNBOUNDED)
{
Console.WriteLine("Model is unbounded");
}
else
{
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
}
model.Dispose();
env.Dispose();
}
catch (GRBException e)
{
Console.WriteLine("Hibakód: " + e.ErrorCode + ". " + e.Message);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
you are overwriting the args parameter of your main() method with an array of all lines of the input file. That's why in
GRBModel model = new GRBModel(env, args[0]);
args[0] contains a string with the first line of your LP file instead of the filename.

Categories

Resources