Here are the examples of the csharp api Serilog.Log.Error(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
52 Examples
19
Source : FeaturesListViewModel.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
private void backgroundWorker_RunWorkerCompletedFeatures(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Log.Error( e.Error.Message);
}
else if (e.Cancelled)
{
Log.Warning( "Loading feature definitions cancelled");
}
else
{
var rawFeatures = e.Result as List<IFeatureDefinition>;
PopulateObservableCollection(rawFeatures);
// hard code 5% as progress, when feature definitions of a farm are loaded
_eventAggregator.GetEvent<SetProgressBarEvent>()
.Publish(5);
var msg = string.Format("Loaded {0} Feature Definitions", Features.Count);
_eventAggregator.GetEvent<SetStatusBarEvent>()
.Publish(msg);
Log.Information(msg);
}
}
19
Source : LocationsListViewModel.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
private void backgroundWorker_RunWorkerCompletedLocations(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Log.Error(e.Error.Message);
}
else if (e.Cancelled)
{
Log.Warning("Loading locations cancelled");
}
else
{
var loadedLocations = e.Result as List<LocationViewModel>;
if (loadedLocations != null && loadedLocations.Any())
{
foreach (LocationViewModel l in loadedLocations)
{
Locations.Add(l);
}
}
}
}
19
Source : Program.cs
with MIT License
from allisterb
with MIT License
from allisterb
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
LConfig = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}");
L = Log.Logger = LConfig.CreateLogger();
Type[] BindOptionTypes = replacedembly.GetExecutingreplacedembly().GetTypes().Where(t => t == typeof(Options) || t.IsSubclreplacedOf(typeof(Options))).ToArray();
MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments"
&& m.GetGenericArguments().Count() == BindOptionTypes.Count()).First();
Parser p = new Parser();
ParserResult<object> result = (ParserResult<object>)parseArgumentsMethod.MakeGenericMethod(BindOptionTypes).Invoke(p, new object[] { p, args });
result.WithNotParsed((IEnumerable<Error> errors) =>
{
HelpText help = GetAutoBuiltHelpText(result);
help.MaximumDisplayWidth = Console.WindowWidth;
help.Copyright = string.Empty;
help.Heading = new HeadingInfo("Compute.NET Bindings CLI", Version.ToString(3));
help.AddPreOptionsLine(string.Empty);
if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
{
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
{
HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
if (error.Type != null)
{
help.AddVerbs(error.Type);
}
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
{
help.AddVerbs(BindOptionTypes);
L.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
{
help.AddVerbs(BindOptionTypes);
help.AddPreOptionsLine("No library selected. Select a library or verb from the options below:");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
{
MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing: {error.NameInfo.NameText} The options and values for this benchmark category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError))
{
MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing. The options and values for this category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
{
UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"Unknown option: {error.Token}.");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(" ", errors.Select(e => e.Tag.ToString()).ToArray())}");
help.AddVerbs(BindOptionTypes);
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
})
.WithParsed<Options>(o =>
{
if (string.IsNullOrEmpty(o.ModuleName))
{
Log.Error($"You must select a MKL module to create bindings for. Use the --help option to get the list of available modules.");
Exit(ExitResult.INVALID_OPTIONS);
}
if (!string.IsNullOrEmpty(o.Root) && !Directory.Exists(o.Root))
{
Log.Error($"The library root directory specified {o.Root} does not exist.");
Exit(ExitResult.INVALID_OPTIONS);
}
else if (!string.IsNullOrEmpty(o.Root))
{
ProgramOptions.Add("RootDirectory", new DirectoryInfo(o.Root));
}
foreach (PropertyInfo prop in o.GetType().GetProperties())
{
ProgramOptions.Add(prop.Name, prop.GetValue(o));
}
})
.WithParsed<MKLOptions>(o =>
{
if (!ProgramOptions.ContainsKey("RootDirectory"))
{
string e = Environment.GetEnvironmentVariable("MKLROOT");
if (string.IsNullOrEmpty(e))
{
L.Error("The --root option was not specified and the MKLROOT environment variable was not found.");
Exit(ExitResult.INVALID_OPTIONS);
}
else if (!Directory.Exists(e))
{
L.Error("The --root option was not specified and the directory specified by the MKLROOT environment variable does not exist.");
Exit(ExitResult.INVALID_OPTIONS);
ProgramOptions.Add("Root", e);
}
else
{
ProgramOptions.Add("RootDirectory", new DirectoryInfo(e));
}
}
ProgramLibrary = new MKL(ProgramOptions);
ConsoleDriver.Run(ProgramLibrary);
if (ProgramLibrary.CleanAndFixup())
{
Exit(ExitResult.SUCCESS);
}
else
{
Exit(ExitResult.ERROR_DURING_CLEANUP);
}
})
.WithParsed<CUDAOptions>(o =>
{
if (!ProgramOptions.ContainsKey("RootDirectory"))
{
string e = Environment.GetEnvironmentVariable("CUDA_PATH");
if (string.IsNullOrEmpty(e))
{
L.Error("The --root option was not specified and the CUDA_PATH environment variable was not found.");
Exit(ExitResult.INVALID_OPTIONS);
}
else if (!Directory.Exists(e))
{
L.Error("The --root option was not specified and the directory specified by the CUDA_PATH environment variable does not exist.");
Exit(ExitResult.INVALID_OPTIONS);
ProgramOptions.Add("Root", e);
}
else
{
ProgramOptions.Add("RootDirectory", new DirectoryInfo(e));
}
}
ProgramLibrary = new CUDA(ProgramOptions);
ConsoleDriver.Run(ProgramLibrary);
if (ProgramLibrary.CleanAndFixup())
{
Exit(ExitResult.SUCCESS);
}
else
{
Exit(ExitResult.ERROR_DURING_CLEANUP);
}
});
}
19
Source : Program.cs
with MIT License
from allisterb
with MIT License
from allisterb
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
LConfig = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.Enrich.WithProcessId()
.MinimumLevel.Debug()
.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}");
L = Log.Logger = LConfig.CreateLogger();
Type[] BenchmarkOptionTypes = replacedembly.GetExecutingreplacedembly().GetTypes().Where(t => t.IsSubclreplacedOf(typeof(Options))).ToArray();
MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments" && m.GetGenericArguments().Count() == BenchmarkOptionTypes.Count()).First();
Parser p = new Parser();
ParserResult<object> result = (ParserResult<object>) parseArgumentsMethod.MakeGenericMethod(BenchmarkOptionTypes).Invoke(p , new object[] { p, args });
result.WithNotParsed((IEnumerable<Error> errors) =>
{
HelpText help = GetAutoBuiltHelpText(result);
help.MaximumDisplayWidth = Console.WindowWidth;
help.Copyright = string.Empty;
help.Heading = new HeadingInfo("jemalloc.NET", Version.ToString(3));
help.AddPreOptionsLine(string.Empty);
if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
{
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
{
HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
if (error.Type != null)
{
help.AddVerbs(error.Type);
}
Log.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
{
help.AddVerbs(BenchmarkOptionTypes);
L.Information(help);
Exit(ExitResult.SUCCESS);
}
else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
{
help.AddVerbs(BenchmarkOptionTypes);
help.AddPreOptionsLine("No category selected. Select a category from the options below:");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
{
MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError))
{
MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: ");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
{
UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
help.AddOptions(result);
help.AddPreOptionsLine($"Unknown option: {error.Token}.");
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(' ', errors.Select(e => e.Tag.ToString()).ToArray())}");
help.AddVerbs(BenchmarkOptionTypes);
L.Information(help);
Exit(ExitResult.INVALID_OPTIONS);
}
})
.WithParsed((Options o) =>
{
foreach (PropertyInfo prop in o.GetType().GetProperties())
{
BenchmarkOptions.Add(prop.Name, prop.GetValue(o));
}
if (o.ColdStart)
{
JemBenchmarkJobAttribute.ColdStartOverride = true;
}
if (o.TargetCount > 0)
{
JemBenchmarkJobAttribute.TargetCountOverride = o.TargetCount;
}
if (o.Once)
{
JemBenchmarkJobAttribute.ColdStartOverride = true;
JemBenchmarkJobAttribute.TargetCountOverride = 1;
}
})
.WithParsed<MallocBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.MALLOC);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Fragment)
{
BenchmarkOptions.Add("Operation", Operation.FRAGMENT);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --fill.");
Exit(ExitResult.SUCCESS);
}
else
{
Benchmark(o);
}
})
.WithParsed<FixedBufferBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.BUFFER);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Math)
{
BenchmarkOptions.Add("Operation", Operation.MATH);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --create or --fill.");
Exit(ExitResult.SUCCESS);
}
else
{
Benchmark(o);
}
})
.WithParsed<SafeArrayBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.NARRAY);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Math)
{
BenchmarkOptions.Add("Operation", Operation.MATH);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --create or --fill.");
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
Benchmark(o);
}
})
.WithParsed<HugeNativeArrayBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.HUGEARRAY);
if (o.Create)
{
BenchmarkOptions.Add("Operation", Operation.CREATE);
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select an operation to benchmark with --create or --fill or --math.");
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
Benchmark(o);
}
})
.WithParsed<VectorBenchmarkOptions>(o =>
{
BenchmarkOptions.Add("Category", Category.VECTOR);
if (o.Mandelbrot)
{
BenchmarkOptions.Add("Operation", Operation.MANDELBROT);
o.Float = true;
o.Int8 = o.Int16 = o.Int32 = o.Int64 = o.Double = o.String = o.Udt = false;
}
else if (o.Fill)
{
BenchmarkOptions.Add("Operation", Operation.FILL);
}
else if (o.Test)
{
BenchmarkOptions.Add("Operation", Operation.TEST);
}
if (!BenchmarkOptions.ContainsKey("Operation"))
{
Log.Error("You must select a vector operation to benchmark with --mandel or --fill or --test.");
Exit(ExitResult.INVALID_OPTIONS);
}
else
{
Benchmark(o);
}
});
}
19
Source : Program.cs
with MIT License
from allisterb
with MIT License
from allisterb
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception exception = (Exception)e.ExceptionObject;
Log.Error(exception, "An unhandled exception occurred. The program will now shutdown.");
Log.Error(exception.StackTrace);
Exit(ExitResult.UNHANDLED_EXCEPTION);
}
19
Source : NukiBridge2MqttLogic.cs
with Apache License 2.0
from bluewalk
with Apache License 2.0
from bluewalk
private void Initialize(string mqttHost, int? mqttPort, string mqttRootTopic, string callbackAddress,
int? callbackPort, string bridgeUrl, string token, bool hashToken, int? infoInterval)
{
_mqttRootTopic = !string.IsNullOrEmpty(mqttRootTopic) ? mqttRootTopic : "nukibridge";
_mqttHost = !string.IsNullOrEmpty(mqttHost) ? mqttHost : "localhost";
_mqttPort = mqttPort ?? 1883;
_bridgeUrl = !string.IsNullOrEmpty(bridgeUrl) ? bridgeUrl : NukiBridgeClient.DiscoverBridge();
_bridgeToken = token;
if (string.IsNullOrEmpty(_bridgeUrl) ||
string.IsNullOrEmpty(_bridgeToken))
throw new Exception("No Bridge_URL and/or Bridge_Token defined");
_hashToken = hashToken;
// Setup MQTT
_mqttClient = new MqttFactory().CreateManagedMqttClient();
_mqttClient.UseApplicationMessageReceivedHandler(e => MqttClientOnApplicationMessageReceived(e));
_mqttClient.UseConnectedHandler(e =>
{
Log.Information("MQTT: Connected");
SubscribeTopic("discover");
SubscribeTopic("reset");
SubscribeTopic("reboot");
SubscribeTopic("fw-upgrade");
});
_mqttClient.UseDisconnectedHandler(e =>
{
if (e.ClientWasConnected)
Log.Warning($"MQTT: Disconnected ({e.Exception?.Message ?? "clean"})");
else
Log.Error($"MQTT: Unable to connect ({e.Exception?.Message ?? "clean"})");
});
_nukiBridgeClient = new NukiBridgeClient(_bridgeUrl, _bridgeToken, _hashToken);
// Setup callback
_callbackAddress = callbackAddress ?? LocalIpAddress().ToString();
_callbackPort = callbackPort ?? 8080;
_httpListener = new HttpListener
{
Prefixes = { $"http://+:{_callbackPort}/" }
};
_devices = new List<Device>();
// Prevent info interval being set to 0
if ((infoInterval ?? 0) == 0)
infoInterval = 300;
// Setup info interval
_infoTimer = new Timer((infoInterval ?? 300) * 1000);
_infoTimer.Elapsed += async (sender, args) =>
{
_infoTimer.Stop();
await PublishBridgeInfo();
_infoTimer.Start();
};
}
19
Source : Cmd_ImportCityGML.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
{
Doreplacedent doc = revit.Application.ActiveUIDoreplacedent.Doreplacedent;
Prop_GeoRefSettings.SetInitialSettings(doc);
var dialog = new CityGML_ImportUI();
dialog.ShowDialog();
if (dialog.StartImport)
{
var importSettings = dialog.ImportSettings;
XDoreplacedent xdoc = null;
switch (importSettings.ImportSource)
{
case CitySource.File:
try
{
string path = importSettings.FilePath;
xdoc = XDoreplacedent.Load(path);
}
catch (Exception ex)
{
Log.Error("Probleme while loading specified file during CityGML import. Is file a XML-File?");
Log.Error(ex.ToString());
TaskDialog.Show("Error", ex.ToString());
}
break;
case CitySource.Server:
try
{
//client clreplaced for xml-POST request from WFS server
WFSClient client = new WFSClient(importSettings.serverURL);
//response with parameters: Site-Lon, Site-Lat, extent, max response of bldgs, CRS)
//Site coordinates from Revit.SiteLocation
//extent from used-defined def (default: 300 m)
//max response dependent of server settings (at VCS), currently 500
//CRS: supported from server are currently: Pseudo-Mercator (3857), LatLon (4326), German National Systems: West(25832), East(25833)
// supported by PlugIn are only the both German National Systems
if (Prop_GeoRefSettings.Epsg != "EPSG:25832" && Prop_GeoRefSettings.Epsg != "EPSG:25833")
TaskDialog.Show("EPSG not supported!", "Only EPSG:25832 or EPSG:25833 will be supported by server. Please change the EPSG-Code in Georeferencing window.");
xdoc = client.getFeaturesCircle(importSettings.CenterCoords[1], importSettings.CenterCoords[0], importSettings.Extent, 500, Prop_GeoRefSettings.Epsg);
if (importSettings.saveResponse)
{
xdoc.Save(importSettings.FolderPath + "\\" + Math.Round(importSettings.CenterCoords[0], 4) + "_" + Math.Round(importSettings.CenterCoords[1], 4) + ".gml");
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", "Could not process server request. See log-file for further information");
Log.Error("Error during processing of CityGML Server Request");
Log.Error(ex.ToString());
}
break;
default:
break;
}
if (xdoc != null)
{
importSettings.XDoc = xdoc;
CityGMLReader cityReader;
switch (importSettings.ImportGeomType)
{
case CityGeometry.Faces:
cityReader = new CityGMLReader(importSettings.XDoc, false);
break;
case CityGeometry.Solid:
cityReader = new CityGMLReader(importSettings.XDoc, true);
break;
default:
cityReader = new CityGMLReader(importSettings.XDoc, true);
break;
}
List<CityGml_Bldg> gmlBuildings = cityReader.GmlBuildings;
C2BPoint lowerCorner = cityReader.LowerCornerPt;
var attributes = cityReader.Attributes;
if (gmlBuildings.Count < 1)
{
TaskDialog.Show("Error", "No CityGML buildings read from file, canceling import!");
return Result.Failed;
}
//erstellt Revit-seitig die Geometrie und ordnet Attributwerte zu
RevitCityBuilder cityModel = new City2RVT.Builder.RevitCityBuilder(doc, gmlBuildings, lowerCorner, attributes, importSettings.CodeTranslate);
if (importSettings.ImportGeomType == CityGeometry.Solid)
cityModel.CreateBuildings();
else
cityModel.CreateBuildingsWithFaces();
}
TaskDialog.Show("Information", "Import process finished!");
}
return Result.Succeeded;
}
19
Source : LogWriter.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
public static void WriteLogFile(List<LogPair> messages, bool solid, double all, double success, double? error, double? errorLod1, double? fatalError)
{
//string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "City2BIM");
//string name = "Log_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";
//string path = Path.Combine(folder, name);
//if (!Directory.Exists(folder))
// Directory.CreateDirectory(folder);
//Serilog.Core.Logger result = new LoggerConfiguration().WriteTo.File(path).CreateLogger();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!
// The function requires a serilog logger set up at a different place!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!
Log.Information("Log-Protocol for CityGML-Import to BIM");
Log.Information("--------------------------------------------------");
if (solid)
{
Log.Information("Kind of transfered geometry: Solids");
Log.Information("Calculation parameters");
Log.Information("----------------------");
Log.Information("Equal Point distance = " + Math.Sqrt(City2BIM_prop.EqualPtSq) + " m.");
Log.Information("Equal Planes normal distance (normal length 1m) = " + Math.Sqrt(City2BIM_prop.EqualPlSq) + " m.");
Log.Information("Maximum deviation between calculated point and original point (if applicable) = " + Math.Sqrt(City2BIM_prop.MaxDevPlaneCutSq) + " m.");
Log.Information("----------------------");
Log.Information("----------------------");
}
else
Log.Information("Kind of transfered geometry: Surfaces");
Log.Information("Statistic");
Log.Information("----------------------");
double statSucc = success / all * 100;
Log.Information("Amount of Solids or Surfaces: " + all);
Log.Information("Success rate = " + statSucc + " percent = " + success + " objects");
if (error.HasValue)
{
double statErr = (double)error / all * 100;
Log.Warning("Failure rate (LOD1, correct contour) = " + statErr + " percent = " + error + " objects");
}
if (errorLod1.HasValue)
{
double statErr = (double)errorLod1 / all * 100;
Log.Warning("Failure rate (LOD1 Fallback, convex hull contour) = " + statErr + " percent = " + errorLod1 + " objects");
}
if (fatalError.HasValue)
{
double fatStatErr = (double)fatalError / all * 100;
Log.Error("Fatal error: no geometry at = " + fatStatErr + " percent = " + fatalError + " objects");
}
Log.Information("----------------------");
Log.Information("----------------------");
Log.Information("Protocol for each Building(Part)");
Log.Information("-------------------------------------");
foreach (var log in messages)
{
switch (log.Type)
{
case (LogType.error):
{
Log.Error(log.Message);
break;
}
case (LogType.warning):
{
Log.Warning(log.Message);
break;
}
case (LogType.info):
{
Log.Information(log.Message);
break;
}
}
}
}
19
Source : ImportDialogAlkis.xaml.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
private void importButton_click(object sender, RoutedEventArgs e)
{
var layersToImport = from layer in this.layerStatusList
where layer.Visibility == true
select layer.LayerName;
this.layerNamesToImport = layersToImport.ToList();
if (this.layerNamesToImport.Count > 0)
{
this.startImport = true;
if (drapeCheckBox.IsEnabled & (bool)drapeCheckBox.IsChecked)
{
this.drape = true;
}
else
{
this.drape = false;
}
if (this.filterCheckBox.IsChecked == true)
{
var pbp = utils.getProjectBasePointMeter(doc);
double distance;
try
{
distance = double.Parse(distanceTextBox.Text);
}
catch (Exception ex)
{
Log.Error("Cannot parse value for spatial filter \n" + ex.ToString());
TaskDialog.Show("Error", "Is value for distance/radius a number?");
return;
}
if (filterTypeBox.SelectedValue.ToString() == "Circle")
{
this.spatialFilter = new OGRCircularSpatialFilter(pbp.X, pbp.Y, distance);
}
else if (filterTypeBox.SelectedValue.ToString() == "Square")
{
this.spatialFilter = new OGRRectangularSpatialFilter(pbp.X, pbp.Y, distance, distance);
}
}
else
{
this.spatialFilter = null;
}
this.filePath = filePathBox.Text;
this.Close();
}
else
{
TaskDialog.Show("Error", "No layers to import!");
}
}
19
Source : Cmd_ImportXPlan.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
{
UIDoreplacedent uiDoc = revit.Application.ActiveUIDoreplacedent;
Doreplacedent doc = uiDoc.Doreplacedent;
Prop_GeoRefSettings.SetInitialSettings(doc);
//MetaInformation.createXPlanungSchema(doc);
ElementId terrainId = utils.getHTWDDTerrainID(doc);
// if a base dtm is loaded then terrainAvailable => true
bool terrainAvailable = (terrainId != null) ? true : false;
if (!utils.configureOgr())
{
Log.Error("Could not configure GDAL/OGR");
TaskDialog.Show("Error", "Could not configure GDAL/OGR");
return Result.Failed;
}
var dialog = new ImportXPlanDialog(terrainAvailable, doc);
dialog.ShowDialog();
if (dialog.StartImport)
{
var gmlReader = new OGRGMLReader(dialog.FilePath);
var geoObjBuilder = new GeoObjectBuilder(doc);
Log.Information("Starting XPLan import");
foreach (var layerName in dialog.LayerNamesToImport)
{
var layer = gmlReader.getLayerByName(layerName);
var GeoObjs = gmlReader.getGeoObjectsForLayer(layer, dialog.SpatialFilter);
Log.Information(string.Format("Total of {0} features in layer {1}", GeoObjs.Count, layerName));
var fieldList = gmlReader.getFieldNamesForLayer(layer);
try
{
geoObjBuilder.buildGeoObjectsFromList(GeoObjs, dialog.Drape, fieldList);
Log.Information(string.Format("Finished importing layer {0}", layerName));
}
catch (Exception ex)
{
Log.Error(string.Format("Error during import of layer {0}", layerName));
TaskDialog.Show("Error", ex.ToString());
Log.Error(ex.ToString());
continue;
}
}
gmlReader.destroy();
//XDoreplacedent xDoc = XDoreplacedent.Load(dialog.FilePath);
//XPlanungReader xPlanReader = new XPlanungReader(xDoc);
//xPlanReader.readData();
//var xPlanObjx = xPlanReader.XPlanungObjects;
//var layerNameList = dialog.LayerNamesToImport;
// https://stackoverflow.com/questions/10745900/filter-a-list-by-another-list-c-sharp :)
//filter object list based on usage type string in layer name list
//List<XPlanungObject> objsToBuild = xPlanObjx.Where(item => layerNameList.Any(category => category.Equals(item.UsageType))).ToList();
//XPlanBuilder xPlanBuilder = new XPlanBuilder(doc);
//xPlanBuilder.buildRevitObjects(objsToBuild, dialog.Drape);
}
return Result.Succeeded;
}
19
Source : Cmd_ReadALKIS.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIDoreplacedent uiDoc = commandData.Application.ActiveUIDoreplacedent;
Doreplacedent doc = uiDoc.Doreplacedent;
Prop_GeoRefSettings.SetInitialSettings(doc);
ElementId terrainId = utils.getHTWDDTerrainID(doc);
// if a base dtm is loaded then terrainAvailable => true
bool terrainAvailable = (terrainId != null) ? true : false;
if (!utils.configureOgr())
{
Log.Error("Could not configure GDAL/OGR");
TaskDialog.Show("Error", "Could not configure GDAL/OGR");
return Result.Failed;
}
var dialog = new ImportDialogAlkis(terrainAvailable, doc);
dialog.ShowDialog();
if (dialog.StartImport)
{
var layerNameList = dialog.LayerNamesToImport;
var ogrReader = new OGRALKISReader(dialog.FilePath);
var GeoObjBuilder = new GeoObjectBuilder(doc);
Log.Information("Starting ALKIS-Import");
foreach (var layerName in layerNameList)
{
var layer = ogrReader.getLayerByName(layerName);
var GeoObjs = ogrReader.getGeoObjectsForLayer(layer, dialog.SpatialFilter);
Log.Information(string.Format("Total of {0} features in layer {1}", GeoObjs.Count, layerName));
var fieldList = ogrReader.getFieldNamesForLayer(layer);
GeoObjBuilder.buildGeoObjectsFromList(GeoObjs, dialog.Drape, fieldList);
Log.Information(string.Format("Finished importing layer {0}", layerName));
}
ogrReader.destroy();
}
return Result.Succeeded;
}
19
Source : ConnectionInterface.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
public static Result mapProcess(Config config)
{
//init transfer clreplaced (DTM2BIM)
Result resTerrain = new Result();
switch (config.fileType)
{
case IfcTerrainFileType.DXF:
//read dxfFile via filepath
if (DXF.ReaderTerrain.readFile(config.filePath, out DxfFile dxfFile))
{
//read dtm
resTerrain = DXF.ReaderTerrain.readDxf(config, dxfFile);
}
break;
case IfcTerrainFileType.LandXML:
resTerrain = LandXML.ReaderTerrain.readDtmData(config);
break;
case IfcTerrainFileType.CityGML:
resTerrain = CityGML.CityGMLReaderTerrain.readTin(config);
break;
case IfcTerrainFileType.Grafbat:
resTerrain = GEOgraf.ReadOUT.readOutData(config);
break;
case IfcTerrainFileType.PostGIS:
resTerrain = PostGIS.ReaderTerrain.readPostGIS(config);
break;
case IfcTerrainFileType.Grid:
resTerrain = ElevationGrid.ReaderTerrain.readGrid(config);
break;
case IfcTerrainFileType.REB:
resTerrain = REB.ReaderTerrain.readDtm(config);
break;
case IfcTerrainFileType.GeoJSON:
resTerrain = geojson.readGeoJson(config);
break;
}
//error handling
if (resTerrain == null)
{
Log.Error("[READER] File reading failed (result is null) - processing canceld!");
return null;
}
else if (resTerrain.pointList == null || resTerrain.pointList.Count.Equals(0))
{
Log.Error("[READER] File reading failed(point list is empty) - processing canceld!");
return null;
}
if(resTerrain.currentConversion != DtmConversionType.conversion)
{
Log.Information("A Delaunay triangulation will be calculated...");
Triangulator.DelaunayTriangulation.triangulate(resTerrain);
}
Log.Information("File readed. Result => Faces (Triangles): " + resTerrain.triMap.Count + " Points: " + resTerrain.pointList);
return resTerrain;
}
19
Source : GeoObjectBuilder.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
public void buildGeoObjectsFromList(List<GeoObject> geoObjects, bool drapeOnTerrain, List<string> fieldList)
{
var queryGroups = from geoObject in geoObjects
group geoObject by geoObject.UsageType into usageGroup
select usageGroup;
ElementId terrainID = utils.getHTWDDTerrainID(doc);
var refPlaneDataStorage = utils.getRefPlaneDataStorageObject(doc);
foreach (var group in queryGroups)
{
ElementId RefPlaneId = (terrainID == null) ? null : terrainID;
string groupName = group.Key;
List<GeoObject> objList = group.ToList();
//When no DTM is availabe -> GeoObjects are mapped flat
if (RefPlaneId == null || drapeOnTerrain == false)
{
var refSurfPts = createRefSurfacePointsForObjGroup(objList);
List<C2BPoint> reducedPoints = refSurfPts.Select(p => GeorefCalc.CalcUnprojectedPoint(p, true)).ToList();
List<XYZ> RevitPts = reducedPoints.Select(p => Revit_Build.GetRevPt(p)).ToList();
using (Transaction trans = new Transaction(doc, "Create RefPlane"))
{
trans.Start();
TopographySurface refSurf = TopographySurface.Create(doc, RevitPts);
refSurf.Pinned = true;
var enreplacedy = refPlaneDataStorage.GetEnreplacedy(utils.getSchemaByName("HTWDD_RefPlaneSchema"));
IDictionary<ElementId, string> value = enreplacedy.Get <IDictionary<ElementId, string>>("RefPlaneElementIdToString");
value.Add(refSurf.Id, groupName);
enreplacedy.Set<IDictionary<ElementId, string>>("RefPlaneElementIdToString", value);
refPlaneDataStorage.SetEnreplacedy(enreplacedy);
RefPlaneId = refSurf.Id;
trans.Commit();
}
}
//When GeoObjects should be mapped on DTM data
else
{
using (Transaction trans = new Transaction(doc, "Copy DTM as new RefPlane"))
{
trans.Start();
TopographySurface refSurf = doc.GetElement(RefPlaneId) as TopographySurface;
var copyOfRefSurfId = ElementTransformUtils.CopyElement(doc, refSurf.Id, new XYZ(0, 0, 0));
TopographySurface copiedRefSurf = doc.GetElement(copyOfRefSurfId.First()) as TopographySurface;
copiedRefSurf.Pinned = true;
var enreplacedy = refPlaneDataStorage.GetEnreplacedy(utils.getSchemaByName("HTWDD_RefPlaneSchema"));
IDictionary<ElementId, string> value = enreplacedy.Get<IDictionary<ElementId, string>>("RefPlaneElementIdToString");
value.Add(copiedRefSurf.Id, groupName);
enreplacedy.Set("RefPlaneElementIdToString", value);
refPlaneDataStorage.SetEnreplacedy(enreplacedy);
RefPlaneId = copiedRefSurf.Id;
trans.Commit();
}
}
using (Transaction trans = new Transaction(doc, "Create alkisObjs"))
{
trans.Start();
Schema currentSchema = utils.getSchemaByName(groupName);
if (currentSchema == null)
{
currentSchema = addSchemaForUsageType(groupName, fieldList);
}
bool processingErrors = false;
foreach (var GeoObj in objList)
{
Enreplacedy ent = new Enreplacedy(currentSchema);
foreach(KeyValuePair<string, string> prop in GeoObj.Properties)
{
//is needed because some attribute are using the | symbol for long attribute names
if (prop.Key.Contains("|"))
{
string firstPart = prop.Key.Split('|')[0];
ent.Set<string>(firstPart, prop.Value);
continue;
}
ent.Set<string>(prop.Key, prop.Value);
}
switch (GeoObj.GeomType)
{
case wkbGeometryType.wkbPolygon:
{
List<C2BSegment> outerSegments = getOuterRingSegmentsFromPolygon(GeoObj.Geom);
var siteSubRegion = createSiteSubRegionFromSegments(outerSegments, RefPlaneId);
siteSubRegion.TopographySurface.SetEnreplacedy(ent);
break;
}
case wkbGeometryType.wkbMultiPolygon:
{
List<List<C2BSegment>> outerSegmentsMultiPoly = getOuterRingSegmentsFromMultiPolygon(GeoObj.Geom);
foreach(var poly in outerSegmentsMultiPoly)
{
var currentSiteSubRegion = createSiteSubRegionFromSegments(poly, RefPlaneId);
currentSiteSubRegion.TopographySurface.SetEnreplacedy(ent);
}
break;
}
case wkbGeometryType.wkbCurvePolygon:
{
if (GeoObj.Geom.HasCurveGeometry(1) == 0)
{
List<C2BSegment> outerSegments = getOuterRingSegmentsFromPolygon(GeoObj.Geom);
var siteSubRegion = createSiteSubRegionFromSegments(outerSegments, RefPlaneId);
siteSubRegion.TopographySurface.SetEnreplacedy(ent);
break;
}
List<C2BSegment> outerSegmentsCurvePoly = getOuterRingSegmentsFromCurvePolygon(GeoObj.Geom);
var siteSubRegionCurvePoly = createSiteSubRegionFromSegments(outerSegmentsCurvePoly, RefPlaneId);
siteSubRegionCurvePoly.TopographySurface.SetEnreplacedy(ent);
break;
}
case wkbGeometryType.wkbMultiSurface:
{
for (int i=0; i<GeoObj.Geom.GetGeometryCount(); i++)
{
var subGeom = GeoObj.Geom.GetGeometryRef(i);
switch (subGeom.GetGeometryType())
{
case wkbGeometryType.wkbPolygon:
{
List<C2BSegment> outerSegments = getOuterRingSegmentsFromPolygon(subGeom);
var siteSubRegion = createSiteSubRegionFromSegments(outerSegments, RefPlaneId);
siteSubRegion.TopographySurface.SetEnreplacedy(ent);
break;
}
case wkbGeometryType.wkbMultiPolygon:
{
List<List<C2BSegment>> outerSegmentsMultiPoly = getOuterRingSegmentsFromMultiPolygon(subGeom);
foreach (var poly in outerSegmentsMultiPoly)
{
var currentSiteSubRegion = createSiteSubRegionFromSegments(poly, RefPlaneId);
currentSiteSubRegion.TopographySurface.SetEnreplacedy(ent);
}
break;
}
case wkbGeometryType.wkbCurvePolygon:
{
List<C2BSegment> outerSegmentsCurvePoly = getOuterRingSegmentsFromCurvePolygon(subGeom);
var siteSubRegionCurvePoly = createSiteSubRegionFromSegments(outerSegmentsCurvePoly, RefPlaneId);
siteSubRegionCurvePoly.TopographySurface.SetEnreplacedy(ent);
break;
}
default:
Log.Error("Could not create GeoObject from MultiSurface. GeometryType is: " + GeoObj.GeomType.ToString() + " gmlId: " + GeoObj.GmlID);
processingErrors = true;
break;
}
}
break;
}
case wkbGeometryType.wkbCompoundCurve:
{
List<C2BSegment> lineSegs = getSegmentsFromCompoundCurve(GeoObj.Geom);
var modelCurveList = createModelCurveFromSegments(lineSegs, drapeOnTerrain, terrainID);
foreach (var modelCurve in modelCurveList)
{
modelCurve.SetEnreplacedy(ent);
}
break;
}
case wkbGeometryType.wkbLineString:
{
if (GeoObj.Geom.HasCurveGeometry(1) == 1)
{
Log.Error("Could not create GeoObject. Object has curve geometry in wkbLineString. This is not implemented");
}
var segments = getSegmentsFromLinearLineString(GeoObj.Geom);
var modelCurveList = createModelCurveFromSegments(segments, drapeOnTerrain, terrainID);
foreach (var modelCurve in modelCurveList)
{
modelCurve.SetEnreplacedy(ent);
}
break;
}
default:
Log.Error("Could not create GeoObject. GeometryType is: " + GeoObj.GeomType.ToString() + " gmlId: " + GeoObj.GmlID);
processingErrors = true;
break;
}
}
// delete refPlane if for object type only line geometrys are added --> modeld as model lines --> no topography surfaces needed
var refTopoSurface = this.doc.GetElement(RefPlaneId) as TopographySurface;
if (refTopoSurface.GetHostedSubRegionIds().Count < 1)
{
refTopoSurface.Pinned = false;
var deletedElementIds = this.doc.Delete(RefPlaneId);
}
trans.Commit();
if (processingErrors)
{
TaskDialog.Show("Warning", string.Format("Some Objects of layer {0} could not be imported into Revit. See log-file for further information", groupName));
}
}
}
}
19
Source : ImportXPlanDialog.xaml.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
private void importButton_click(object sender, RoutedEventArgs e)
{
var layersToImport = from layer in this.layerStatusList
where layer.Visibility == true
select layer.LayerName;
this.layerNamesToImport = layersToImport.ToList();
if (this.layerNamesToImport.Count > 0)
{
this.startImport = true;
if (drapeCheckBox.IsEnabled & (bool)drapeCheckBox.IsChecked)
{
this.drape = true;
}
else
{
this.drape = false;
}
if (this.filterCheckBox.IsChecked == true)
{
var pbp = utils.getProjectBasePointMeter(doc);
double distance;
try
{
distance = double.Parse(distanceTextBox.Text);
}
catch (Exception ex)
{
Log.Error("Cannot parse value for spatial filter \n" + ex.ToString());
TaskDialog.Show("Error", "Is value for distance/radius a number?");
return;
}
if (filterTypeBox.SelectedValue.ToString() == "Circle")
{
this.spatialFilter = new OGRCircularSpatialFilter(pbp.X, pbp.Y, distance);
}
else if (filterTypeBox.SelectedValue.ToString() == "Square")
{
this.spatialFilter = new OGRRectangularSpatialFilter(pbp.X, pbp.Y, distance, distance);
}
}
else
{
this.spatialFilter = null;
}
this.filePath = filePathBox.Text;
this.Close();
}
else
{
TaskDialog.Show("Error", "No layers to import!");
}
}
19
Source : GeoObjectBuilder.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
private static List<C2BSegment> getOuterRingSegmentsFromCurvePolygon(OSGeo.OGR.Geometry geom)
{
List<C2BSegment> segments = new List<C2BSegment>();
var outerRing = geom.GetGeometryRef(0);
double[] geoPoint = { 0, 0, 0 };
for (int i=0; i<outerRing.GetGeometryCount(); i++)
{
var sectionGeom = outerRing.GetGeometryRef(i);
switch (sectionGeom.GetGeometryType())
{
case wkbGeometryType.wkbCircularString:
//The number of control points in the arc string must be 2 * numArc + 1.
int nrOfPoints = sectionGeom.GetPointCount();
int nrOfArcSegments = (nrOfPoints - 1) / 2;
for (int j = 0, l = 0; j < nrOfArcSegments; j++, l += 2)
{
sectionGeom.GetPoint(l, geoPoint);
var startPoint = new C2BPoint(geoPoint[0], geoPoint[1], 0);
sectionGeom.GetPoint(l + 1, geoPoint);
var midPoint = new C2BPoint(geoPoint[0], geoPoint[1], 0);
sectionGeom.GetPoint(l + 2, geoPoint);
var endPoint = new C2BPoint(geoPoint[0], geoPoint[1], 0);
segments.Add(new C2BSegment(startPoint, endPoint, midPoint));
}
break;
case wkbGeometryType.wkbLineString:
for (var j = 1; j < sectionGeom.GetPointCount(); j++)
{
sectionGeom.GetPoint(j - 1, geoPoint);
C2BPoint startSeg = new C2BPoint(geoPoint[0], geoPoint[1], 0);
sectionGeom.GetPoint(j, geoPoint);
C2BPoint endSeg = new C2BPoint(geoPoint[0], geoPoint[1], 0);
segments.Add(new C2BSegment(startSeg, endSeg));
}
break;
default:
Log.Error(string.Format("Could not process geometry within CurvePolygon! Geometry is of type {0}", sectionGeom.GetGeometryType()));
break;
}
}
return segments;
}
19
Source : GeoObjectBuilder.cs
with GNU General Public License v3.0
from dd-bim
with GNU General Public License v3.0
from dd-bim
private static List<C2BSegment> getSegmentsFromCompoundCurve(OSGeo.OGR.Geometry geom)
{
List<C2BSegment> segments = new List<C2BSegment>();
double[] geoPoint = { 0, 0 };
List<C2BSegment> segs = new List<C2BSegment>();
for (int i=0; i<geom.GetGeometryCount(); i++)
{
var sectionGeom = geom.GetGeometryRef(i);
switch (sectionGeom.GetGeometryType())
{
case wkbGeometryType.wkbCircularString:
segs = getSegmentsFromCircularLineString(sectionGeom);
break;
case wkbGeometryType.wkbLineString:
segs = getSegmentsFromLinearLineString(sectionGeom);
break;
default:
Log.Error(string.Format("Could not process geometry from Compound Curve!"));
break;
}
segments.AddRange(segs);
}
return segments;
}
19
Source : Redcap.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public async Task<string> ExportInstrumentsAsync(string token, Content content = Content.Instrument, ReturnFormat format = ReturnFormat.json)
{
try
{
/*
* Check for presence of token
*/
this.CheckToken(token);
var payload = new Dictionary<string, string>
{
{ "token", token },
{ "content", content.GetDisplayName() },
{ "format", format.GetDisplayName() }
};
// Execute request
return await this.SendPostRequestAsync(payload, _uri);
}
catch (Exception Ex)
{
/*
* We'll just log the error and return the error message.
*/
Log.Error($"{Ex.Message}");
return Ex.Message;
}
}
19
Source : Redcap.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public async Task<string> ExportRecordAsync(string token, Content content, string record, ReturnFormat format = ReturnFormat.json, RedcapDataType redcapDataType = RedcapDataType.flat, string[] fields = null, string[] forms = null, string[] events = null, RawOrLabel rawOrLabel = RawOrLabel.raw, RawOrLabelHeaders rawOrLabelHeaders = RawOrLabelHeaders.raw, bool exportCheckboxLabel = false, OnErrorFormat onErrorFormat = OnErrorFormat.json, bool exportSurveyFields = false, bool exportDataAccessGroups = false, string filterLogic = null)
{
try
{
this.CheckToken(token);
var payload = new Dictionary<string, string>
{
{ "token", token },
{ "records", record },
{ "content", content.GetDisplayName() },
{ "format", format.GetDisplayName() },
{ "returnFormat", onErrorFormat.GetDisplayName() },
{ "type", redcapDataType.GetDisplayName() }
};
// Optional
if (fields?.Length > 0)
{
payload.Add("fields", await this.ConvertArraytoString(fields));
}
if (forms?.Length > 0)
{
payload.Add("forms", await this.ConvertArraytoString(forms));
}
if (events?.Length > 0)
{
payload.Add("events", await this.ConvertArraytoString(events));
}
/*
* Pertains to CSV data only
*/
var _rawOrLabelValue = rawOrLabelHeaders.ToString();
if (!IsNullOrEmpty(_rawOrLabelValue))
{
payload.Add("rawOrLabel", _rawOrLabelValue);
}
// Optional (defaults to false)
if (exportCheckboxLabel)
{
payload.Add("exportCheckboxLabel", exportCheckboxLabel.ToString());
}
// Optional (defaults to false)
if (exportSurveyFields)
{
payload.Add("exportSurveyFields", exportSurveyFields.ToString());
}
// Optional (defaults to false)
if (exportDataAccessGroups)
{
payload.Add("exportDataAccessGroups", exportDataAccessGroups.ToString());
}
if (!IsNullOrEmpty(filterLogic))
{
payload.Add("filterLogic", filterLogic);
}
return await this.SendPostRequestAsync(payload, _uri);
}
catch (Exception Ex)
{
/*
* We'll just log the error and return the error message.
*/
Log.Error($"{Ex.Message}");
return Ex.Message;
}
}
19
Source : Redcap.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public async Task<string> ExportRecordsAsync(string token, Content content, ReturnFormat format = ReturnFormat.json, RedcapDataType redcapDataType = RedcapDataType.flat, string[] records = null, string[] fields = null, string[] forms = null, string[] events = null, RawOrLabel rawOrLabel = RawOrLabel.raw, RawOrLabelHeaders rawOrLabelHeaders = RawOrLabelHeaders.raw, bool exportCheckboxLabel = false, OnErrorFormat onErrorFormat = OnErrorFormat.json, bool exportSurveyFields = false, bool exportDataAccessGroups = false, string filterLogic = null)
{
try
{
this.CheckToken(token);
var payload = new Dictionary<string, string>
{
{ "token", token },
{ "content", content.GetDisplayName() },
{ "format", format.GetDisplayName() },
{ "returnFormat", onErrorFormat.GetDisplayName() },
{ "type", redcapDataType.GetDisplayName() }
};
// Optional
if (records?.Length > 0)
{
payload.Add("records", await this.ConvertArraytoString(records));
}
if (fields?.Length > 0)
{
payload.Add("fields", await this.ConvertArraytoString(fields));
}
if (forms?.Length > 0)
{
payload.Add("forms", await this.ConvertArraytoString(forms));
}
if (events?.Length > 0)
{
payload.Add("events", await this.ConvertArraytoString(events));
}
/*
* Pertains to CSV data only
*/
var _rawOrLabelValue = rawOrLabelHeaders.ToString();
if (!IsNullOrEmpty(_rawOrLabelValue))
{
payload.Add("rawOrLabel", _rawOrLabelValue);
}
// Optional (defaults to false)
if (exportCheckboxLabel)
{
payload.Add("exportCheckboxLabel", exportCheckboxLabel.ToString());
}
// Optional (defaults to false)
if (exportSurveyFields)
{
payload.Add("exportSurveyFields", exportSurveyFields.ToString());
}
// Optional (defaults to false)
if (exportDataAccessGroups)
{
payload.Add("exportDataAccessGroups", exportDataAccessGroups.ToString());
}
if (!IsNullOrEmpty(filterLogic))
{
payload.Add("filterLogic", filterLogic);
}
return await this.SendPostRequestAsync(payload, _uri);
}
catch (Exception Ex)
{
/*
* We'll just log the error and return the error message.
*/
Log.Error($"{Ex.Message}");
return Ex.Message;
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<string> ConvertArraytoString<T>(this RedcapApi redcapApi, T[] inputArray)
{
try
{
if (inputArray.IsNullOrEmpty())
{
throw new ArgumentNullException("Please provide a valid array.");
}
StringBuilder builder = new StringBuilder();
foreach (T v in inputArray)
{
builder.Append(v);
// We do not need to append the , if less than or equal to a single string
if (inputArray.Length <= 1)
{
return await Task.FromResult(builder.ToString());
}
builder.Append(",");
}
// We trim the comma from the string for clarity
return await Task.FromResult(builder.ToString().TrimEnd(','));
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(String.Empty);
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<string> ConvertIntArraytoString(this RedcapApi redcapApi, int[] inputArray)
{
try
{
StringBuilder builder = new StringBuilder();
foreach (var v in inputArray)
{
builder.Append(v);
// We do not need to append the , if less than or equal to a single string
if (inputArray.Length <= 1)
{
return await Task.FromResult(builder.ToString());
}
builder.Append(",");
}
// We trim the comma from the string for clarity
return await Task.FromResult(builder.ToString().TrimEnd(','));
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(String.Empty);
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<string> HandleReturnContent(this RedcapApi redcapApi, ReturnContent returnContent = ReturnContent.count)
{
try
{
var _returnContent = returnContent.ToString();
switch (returnContent)
{
case ReturnContent.ids:
_returnContent = ReturnContent.ids.ToString();
break;
case ReturnContent.count:
_returnContent = ReturnContent.count.ToString();
break;
default:
_returnContent = ReturnContent.count.ToString();
break;
}
return await Task.FromResult(_returnContent);
}
catch (Exception Ex)
{
Log.Error(Ex.Message);
return await Task.FromResult(String.Empty);
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<(string format, string onErrorFormat, string redcapDataType)> HandleFormat(this RedcapApi redcapApi, ReturnFormat? format = ReturnFormat.json, OnErrorFormat? onErrorFormat = OnErrorFormat.json, RedcapDataType? redcapDataType = RedcapDataType.flat)
{
// default
var _format = ReturnFormat.json.ToString();
var _onErrorFormat = OnErrorFormat.json.ToString();
var _redcapDataType = RedcapDataType.flat.ToString();
try
{
switch (format)
{
case ReturnFormat.json:
_format = ReturnFormat.json.ToString();
break;
case ReturnFormat.csv:
_format = ReturnFormat.csv.ToString();
break;
case ReturnFormat.xml:
_format = ReturnFormat.xml.ToString();
break;
default:
_format = ReturnFormat.json.ToString();
break;
}
switch (onErrorFormat)
{
case OnErrorFormat.json:
_onErrorFormat = OnErrorFormat.json.ToString();
break;
case OnErrorFormat.csv:
_onErrorFormat = OnErrorFormat.csv.ToString();
break;
case OnErrorFormat.xml:
_onErrorFormat = OnErrorFormat.xml.ToString();
break;
default:
_onErrorFormat = OnErrorFormat.json.ToString();
break;
}
switch (redcapDataType)
{
case RedcapDataType.flat:
_redcapDataType = RedcapDataType.flat.ToString();
break;
case RedcapDataType.eav:
_redcapDataType = RedcapDataType.eav.ToString();
break;
case RedcapDataType.longitudinal:
_redcapDataType = RedcapDataType.longitudinal.ToString();
break;
case RedcapDataType.nonlongitudinal:
_redcapDataType = RedcapDataType.nonlongitudinal.ToString();
break;
default:
_redcapDataType = RedcapDataType.flat.ToString();
break;
}
return await Task.FromResult((_format, _onErrorFormat, _redcapDataType));
}
catch (Exception Ex)
{
Log.Error(Ex.Message);
return await Task.FromResult((_format, _onErrorFormat, _redcapDataType));
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<string> ExtractBehaviorAsync(this RedcapApi redcapApi, OverwriteBehavior overwriteBehavior)
{
try
{
var _overwriteBehavior = OverwriteBehavior.normal.ToString();
switch (overwriteBehavior)
{
case OverwriteBehavior.overwrite:
_overwriteBehavior = OverwriteBehavior.overwrite.ToString();
break;
case OverwriteBehavior.normal:
_overwriteBehavior = OverwriteBehavior.normal.ToString();
break;
default:
_overwriteBehavior = OverwriteBehavior.overwrite.ToString();
break;
}
return await Task.FromResult(_overwriteBehavior);
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(String.Empty);
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<Dictionary<string, string>> GetProperties(this RedcapApi redcapApi, object input)
{
try
{
if (input != null)
{
// Get the type
var type = input.GetType();
var obj = new Dictionary<string, string>();
// Get the properties
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] properties = input.GetType().GetProperties();
foreach (var prop in properties)
{
// get type of column
// The the type of the property
Type columnType = prop.PropertyType;
// We need to set lower case for REDCap's variable nameing convention (lower casing)
string propName = prop.Name.ToLower();
// We check for null values
var propValue = type.GetProperty(prop.Name).GetValue(input, null)?.ToString();
if (propValue != null)
{
var t = columnType.GetGenericArguments();
if (t.Length > 0)
{
if (columnType.GenericTypeArguments[0].FullName == "System.DateTime")
{
var dt = DateTime.Parse(propValue);
propValue = dt.ToString();
}
if (columnType.GenericTypeArguments[0].FullName == "System.Boolean")
{
if (propValue == "True")
{
propValue = "1";
}
else
{
propValue = "0";
}
}
}
obj.Add(propName, propValue);
}
else
{
// We have to make sure we handle for null values.
obj.Add(propName, null);
}
}
return await Task.FromResult(obj);
}
return await Task.FromResult(new Dictionary<string, string> { });
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(new Dictionary<string, string> { });
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<List<string>> ExtractEventsAsync(this RedcapApi redcapApi, string events, char[] delimiters)
{
if (!String.IsNullOrEmpty(events))
{
try
{
var formItems = events.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
List<string> eventsResult = new List<string>();
foreach (var form in formItems)
{
eventsResult.Add(form);
}
return await Task.FromResult(eventsResult);
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(new List<string> { });
}
}
return await Task.FromResult(new List<string> { });
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<List<string>> ExtractFieldsAsync(this RedcapApi redcapApi, string fields, char[] delimiters)
{
if (!String.IsNullOrEmpty(fields))
{
try
{
var fieldItems = fields.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
List<string> fieldsResult = new List<string>();
foreach (var field in fieldItems)
{
fieldsResult.Add(field);
}
return await Task.FromResult(fieldsResult);
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(new List<string> { });
}
}
return await Task.FromResult(new List<string> { });
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<List<string>> ExtractRecordsAsync(this RedcapApi redcapApi, string records, char[] delimiters)
{
if (!String.IsNullOrEmpty(records))
{
try
{
var recordItems = records.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
List<string> recordResults = new List<string>();
foreach (var record in recordItems)
{
recordResults.Add(record);
}
return await Task.FromResult(recordResults);
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(new List<string> { });
}
}
return await Task.FromResult(new List<string> { });
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<List<string>> ExtractFormsAsync(this RedcapApi redcapApi, string forms, char[] delimiters)
{
if (!String.IsNullOrEmpty(forms))
{
try
{
var formItems = forms.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
List<string> formsResult = new List<string>();
foreach (var form in formItems)
{
formsResult.Add(form);
}
return await Task.FromResult(formsResult);
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(new List<string> { });
}
}
return await Task.FromResult(new List<string> { });
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<Stream> GetStreamContentAsync(this RedcapApi redcapApi, Dictionary<string, string> payload, Uri uri)
{
try
{
Stream stream = null;
using (var client = new HttpClient())
{
// Encode the values for payload
var content = new FormUrlEncodedContent(payload);
using (var response = await client.PostAsync(uri, content))
{
if (response.IsSuccessStatusCode)
{
stream = await response.Content.ReadreplacedtreamAsync();
return stream;
}
}
}
return null;
}
catch (Exception Ex)
{
Log.Error(Ex.Message);
return null;
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<string> SendRequestAsync(this RedcapApi redcapApi, MultipartFormDataContent payload, Uri uri)
{
try
{
using (var client = new HttpClient())
{
using (var response = await client.PostAsync(uri, payload))
{
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadreplacedtringAsync();
}
}
}
return Empty;
}
catch (Exception Ex)
{
Log.Error(Ex.Message);
return Empty;
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<string> SendPostRequestAsync(this RedcapApi redcapApi, Dictionary<string, string> payload, Uri uri, bool isLargeDataset = false)
{
try
{
string _responseMessage = Empty;
using (var client = new HttpClient())
{
// extract the filepath
var pathValue = payload.Where(x => x.Key == "filePath").FirstOrDefault().Value;
var pathkey = payload.Where(x => x.Key == "filePath").FirstOrDefault().Key;
if (!string.IsNullOrEmpty(pathkey))
{
// the actual payload does not contain a 'filePath' key
payload.Remove(pathkey);
}
/*
* Encode the values for payload
* Add in ability to process large data set, using StringContent
* Thanks to Ibrahim for pointing this out.
* https://stackoverflow.com/questions/23703735/how-to-set-large-string-inside-httpcontent-when-using-httpclient/23740338
*/
if (isLargeDataset)
{
/*
* Send request with large data set
*/
var serializedPayload = JsonConvert.SerializeObject(payload);
using (var content = new StringContent(serializedPayload, Encoding.UTF8, "application/json"))
{
using (var response = await client.PostAsync(uri, content))
{
if (response.IsSuccessStatusCode)
{
// Get the filename so we can save with the name
var headers = response.Content.Headers;
var fileName = headers.ContentType.Parameters.Select(x => x.Value).FirstOrDefault();
if (!string.IsNullOrEmpty(fileName))
{
var contentDisposition = response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
}
if (!string.IsNullOrEmpty(pathValue))
{
// save the file to a specified location using an extension method
await response.Content.ReadAsFileAsync(fileName, pathValue, true);
_responseMessage = fileName;
}
else
{
_responseMessage = await response.Content.ReadreplacedtringAsync();
}
}
else
{
_responseMessage = await response.Content.ReadreplacedtringAsync();
}
}
}
return _responseMessage;
}
else
{
/*
* Maximum character limit of 32,000 using FormUrlEncodedContent
* Send request using small data set
*/
using (var content = new FormUrlEncodedContent(payload))
{
using (var response = await client.PostAsync(uri, content))
{
if (response.IsSuccessStatusCode)
{
// Get the filename so we can save with the name
var headers = response.Content.Headers;
var fileName = headers.ContentType.Parameters.Select(x => x.Value).FirstOrDefault();
if (!string.IsNullOrEmpty(fileName))
{
var contentDisposition = response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
}
if (!string.IsNullOrEmpty(pathValue))
{
var fileExtension = payload.Where(x => x.Key == "content" && x.Value == "pdf").SingleOrDefault().Value;
if (!string.IsNullOrEmpty(fileExtension))
{
// pdf
fileName = payload.Where(x => x.Key == "instrument").SingleOrDefault().Value;
// to do , make extensions for various types
// save the file to a specified location using an extension method
await response.Content.ReadAsFileAsync(fileName, pathValue, true, fileExtension);
}
else
{
await response.Content.ReadAsFileAsync(fileName, pathValue, true, fileExtension);
}
_responseMessage = fileName;
}
else
{
_responseMessage = await response.Content.ReadreplacedtringAsync();
}
}
else
{
_responseMessage = await response.Content.ReadreplacedtringAsync();
}
}
}
}
return _responseMessage;
}
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return Empty;
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static async Task<List<string>> ExtractArmsAsync<T>(this RedcapApi redcapApi, string arms, char[] delimiters)
{
if (!String.IsNullOrEmpty(arms))
{
try
{
var _arms = arms.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
List<string> armsResult = new List<string>();
foreach (var arm in _arms)
{
armsResult.Add(arm);
}
return await Task.FromResult(armsResult);
}
catch (Exception Ex)
{
Log.Error($"{Ex.Message}");
return await Task.FromResult(new List<string> { });
}
}
return await Task.FromResult(new List<string> { });
}
19
Source : Redcap.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public async Task<string> ExportMetaDataAsync(string token, Content content = Content.MetaData, ReturnFormat format = ReturnFormat.json, string[] fields = null, string[] forms = null, OnErrorFormat onErrorFormat = OnErrorFormat.json)
{
try
{
/*
* Check for presence of token
*/
this.CheckToken(token);
var payload = new Dictionary<string, string>
{
{ "token", token },
{ "content", content.GetDisplayName() },
{ "format", format.GetDisplayName() },
{ "returnFormat", onErrorFormat.GetDisplayName() }
};
// Optional
if (fields?.Length > 0)
{
for (var i = 0; i < fields.Length; i++)
{
payload.Add($"fields[{i}]", fields[i].ToString());
}
}
if (forms?.Length > 0)
{
for (var i = 0; i < forms.Length; i++)
{
payload.Add($"forms[{i}]", forms[i].ToString());
}
}
return await this.SendPostRequestAsync(payload, _uri);
}
catch (Exception Ex)
{
/*
* We'll just log the error and return the error message.
*/
Log.Error($"{Ex.Message}");
return Ex.Message;
}
}
19
Source : Utils.cs
with Apache License 2.0
from Epi-Info
with Apache License 2.0
from Epi-Info
public static Task ReadAsFileAsync(this HttpContent httpContent, string fileName, string path, bool overwrite, string fileExtension = "pdf")
{
if (!overwrite && File.Exists(Path.Combine(fileName + fileExtension?.SingleOrDefault(), path)))
{
throw new InvalidOperationException($"File {fileName} already exists.");
}
FileStream filestream = null;
try
{
fileName = fileName.Replace("\"", "");
/*
* Add extension
*/
if (!string.IsNullOrEmpty(fileExtension))
{
fileName = fileName + "." + fileExtension;
}
filestream = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.Write, FileShare.None);
return httpContent.CopyToAsync(filestream).ContinueWith(
(copyTask) =>
{
filestream.Flush();
filestream.Dispose();
}
);
}
catch (Exception Ex)
{
Log.Error(Ex.Message);
if (filestream != null)
{
filestream.Flush();
}
throw new InvalidOperationException($"{Ex.Message}");
}
}
19
Source : FileOpenController.cs
with MIT License
from Figglewatts
with MIT License
from Figglewatts
public void OpenFile(string filePath)
{
_configController.AddRecentFile(filePath);
Log.Information($"Loading file from: {filePath}");
var ext = Path.GetExtension(filePath)?.ToLowerInvariant();
switch (ext)
{
case ".lbd":
_lbdController.Load(filePath);
break;
case ".tmd":
_tmdController.Load(filePath);
break;
case ".mom":
_momController.Load(filePath);
break;
case ".tim":
_timController.Load(filePath);
break;
case ".tix":
_tixController.Load(filePath);
break;
default:
Log.Error($"Unable to open file {filePath}, unsupported type.");
break;
}
}
19
Source : DraftPicksCalculator.cs
with MIT License
from ibiza240
with MIT License
from ibiza240
public ICollection<CardForDraftPick> GetCardsForDraftPick(
ICollection<int> cardPool,
ICollection<int> pickedCards,
string source,
Dictionary<int, int> collection,
ICollection<CardCompareInfo> raredraftingInfo
)
{
if (cardPool.Any() == false)
return new CardForDraftPick[0];
var weights = raredraftingInfo.ToDictionary(i => i.GrpId, i => i);
var byCard = cardPool
.Where(i => allCards.ContainsKey(i))
.Select(i => allCards[i]);
var maxWeight = byCard.Max(i => weights.ContainsKey(i.grpId) ? weights[i.grpId].MissingWeight : 0f);
var dataUnordered = byCard
.Select(i =>
{
var card = new CardForDraftPick { Card = i };
try
{
if (source == null)
Log.Error("GetCardsForDraftPick Source is null");
if (i.set == null)
Log.Error("GetCardsForDraftPick Card set is null {grpId}", i.grpId);
if (i.name == null)
Log.Error("GetCardsForDraftPick Card name is null", i.grpId);
card.NbMissingCollection = calculateMissingAmount(collection, i, pickedCards);
if (weights.ContainsKey(i.grpId))
{
card.NbMissingTrackedDecks = weights[i.grpId].NbMissing;
card.Weight = weights[i.grpId].MissingWeight;
card.NbDecksUsedMain = weights[i.grpId].NbDecksMain;
card.NbDecksUsedSideboard = weights[i.grpId].NbDecksSideboardOnly;
}
Dictionary<string, DraftRating> ratings;
Dictionary<string, ICollection<DraftRatingTopCard>> topCardsByColor;
if (ratingsBySourceSet.ContainsKey(source) &&
ratingsBySourceSet[source].ContainsKey(i.set))
{
(ratings, topCardsByColor) = ratingsBySourceSet[source][i.set];
}
else
{
// This source does not have ratings for this set; use the first source that does
var sourceWithSet = ratingsBySourceSet.FirstOrDefault(s => s.Value.ContainsKey(i.set));
(ratings, topCardsByColor) = sourceWithSet.Value[i.set];
source = sourceWithSet.Key;
}
if (!ratings.ContainsKey(i.name))
// Rating not found for card
return card;
var draftRating = ratings[i.name];
card.Description = draftRating.Description;
card.RatingValue = draftRating.RatingValue;
card.RatingToDisplay = draftRating.RatingToDisplay;
card.RatingSource = source;
var cardColors = string.Join("", i.colors);
if (topCardsByColor?.ContainsKey(cardColors) == true)
{
var rank = topCardsByColor[i.colors.First()]
.FirstOrDefault(x => x.Name == i.name)?.Rank ?? 0;
card.TopCommonCard = new DraftRatingTopCard(rank, cardColors);
}
}
catch (Exception ex)
{
Log.Error(ex, "ERROR IN DRAFTPICK");
System.Diagnostics.Debugger.Break();
}
return card;
});
var data = dataUnordered
.OrderByDescending(i => i.RatingValue)
.ThenByDescending(i => i.Weight)
.ThenByDescending(i => i.Card.name)
.ToArray();
var isMissingRareLand = data.FirstOrDefault(i => i.Card.type.Contains("Land") && i.Card.GetRarityEnum() == RarityEnum.Rare && i.NbMissingCollection > 0);
if (isMissingRareLand != null)
isMissingRareLand.IsRareDraftPick = RaredraftPickReasonEnum.RareLandMissing;
else if (maxWeight > 0 && data.Any(i => i.Weight == maxWeight))
data.First(i => i.Weight == maxWeight).IsRareDraftPick = RaredraftPickReasonEnum.HighestWeight;
else if (data.Any(i => basicLandIdentifier.IsBasicLand(i.Card) == false && i.NbMissingCollection > 0))
{
var r = data
.Where(i => basicLandIdentifier.IsBasicLand(i.Card) == false)
.Where(i => i.NbMissingCollection > 0)
.OrderBy(i => i.Card.GetRarityEnum())
.ThenByDescending(i => i.NbMissingCollection)
.First();
r.IsRareDraftPick = RaredraftPickReasonEnum.MissingInCollection;
}
else
{
var bestRarity = data.Select(c => c.Card.GetRarityEnum()).Min();
var cardsMatching = data
.Where(i => i.Card.GetRarityEnum() == bestRarity)
.Where(i => basicLandIdentifier.IsBasicLand(i.Card) == false);
foreach (var c in cardsMatching)
c.IsRareDraftPick = RaredraftPickReasonEnum.BestVaultRarity;
}
return data;
}
19
Source : Program.cs
with Apache License 2.0
from kevinkovalchik
with Apache License 2.0
from kevinkovalchik
static int Run(Dictionary<string, object> opts)
{
if ((bool)opts["ExampleCommands"] == true)
{
Examples.CommandLineUsage();
Environment.Exit(0);
}
if ((bool)opts["ExampleModifications"] == true)
{
Examples.ExampleMods();
Environment.Exit(0);
}
List<string> files = new List<string>();
QcDataCollection qcDataCollection = new QcDataCollection();
WorkflowParameters parameters = new WorkflowParameters(opts);
if (parameters.InputFiles != null) // did the user give us a list of files?
{
List<string> problems = new List<string>();
files = parameters.InputFiles.ToList();
// check if the list provided contains only .raw files
foreach (string file in files)
{
if (!file.EndsWith(".raw", StringComparison.OrdinalIgnoreCase))
{
problems.Add(file);
}
}
if (problems.Count() == 1)
{
Console.WriteLine("\nERROR: {0} does not appear to be a .raw file. Invoke '>RawTools --help' if you need help.", problems.ElementAt(0));
Log.Error("Invalid file provided: {0}", problems.ElementAt(0));
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
if (problems.Count() > 1)
{
Console.WriteLine("\nERROR: The following {0} files do not appear to be .raw files. Invoke '>RawTools --help' if you need help." +
"\n\n{1}", problems.Count(), String.Join("\n", problems));
Log.Error("Invalid files provided: {0}", String.Join(" ", problems));
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
files = RawFileInfo.RemoveInAcquistionFiles(files);
// if the file location(s) are relative, we need to get the absolute path to them
files.EnsureAbsolutePaths();
Log.Information("Files to be processed, provided as list: {0}", String.Join(" ", files));
}
else if (!String.IsNullOrEmpty(parameters.RawFileDirectory)) // did the user give us a directory?
{
// if QC is being done, use the QC method snf get the qc data collection at the same time
if (parameters.QcParams.QcDirectory != null)
{
(files, qcDataCollection) = QcWorkflow.GetFileListAndQcFile(parameters, parameters.IncludeSubdirectories);
}
// if not, the parse method
else if (Directory.Exists(parameters.RawFileDirectory))
{
files = Directory.GetFiles(parameters.RawFileDirectory, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".raw", StringComparison.OrdinalIgnoreCase)).ToList();
}
else
{
Console.WriteLine("ERROR: The provided directory does not appear to be valid.");
Log.Error("Invalid directory provided: {0}", parameters.RawFileDirectory);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
files = RawFileInfo.RemoveInAcquistionFiles(files);
// if the file location(s) are relative, we need to get the absolute path to them
files.EnsureAbsolutePaths();
Log.Information("Files to be processed, provided as directory: {0}", String.Join(" ", files));
}
else
{
Console.WriteLine("ERROR: At least one of the following arguments is required: -f, -d");
Log.Error("No raw files or directory specified.");
return 1;
}
if (parameters.ParseParams.Quant)
{
List<string> possible = new List<string>() { "TMT0", "TMT2", "TMT6", "TMT10", "TMT11", "TMT16", "iTRAQ4", "iTRAQ8" };
if (!possible.Contains(parameters.ParseParams.LabelingReagents))
{
Console.WriteLine("ERROR: For quantification, the labeling reagent must be one of {TMT0, TMT2, TMT6, TMT10, TMT11, TMT16, iTRAQ4, iTRAQ8}");
Log.Error("Invalid labeling reagent provided: {0}", parameters.ParseParams.LabelingReagents);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
}
if (parameters.ParseParams.Chromatogram != null)
{
List<string> possible = new List<string>() { "1", "2", "3", "T", "B" };
foreach (var x in parameters.ParseParams.Chromatogram)
{
if (!possible.Contains(x.ToString()))
{
Console.WriteLine("ERROR: Incorrect format for -chro. See help.");
Log.Error("Invalid chromatogram argument provided: {Chro}", parameters.ParseParams.Chromatogram);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
}
}
System.Diagnostics.Stopwatch singleFileTime = new System.Diagnostics.Stopwatch();
System.Diagnostics.Stopwatch totalTime = new System.Diagnostics.Stopwatch();
totalTime.Start();
foreach (string file in files)
{
singleFileTime.Start();
Console.WriteLine("\nProcessing: {0}\n", file);
//using (IRawDataPlus rawFile = RawFileReaderFactory.ReadFile(fileName:file))
using (IRawFileThreadManager rawFile = RawFileReaderFactory.CreateThreadManager(file))
{
if (parameters.ParseParams.OutputDirectory == null)
{
parameters.ParseParams.OutputDirectory = Path.GetDirectoryName(file);
}
WorkFlowsDDA.UniversalDDA(rawFile, parameters, qcDataCollection);
}
singleFileTime.Stop();
Console.WriteLine("\nElapsed time: {0} s", Math.Round(Convert.ToDouble(singleFileTime.ElapsedMilliseconds) / 1000.0, 2));
singleFileTime.Reset();
}
if (parameters.LogDump)
{
Write.LogDump.WriteToDisk(parameters);
}
totalTime.Stop();
Console.WriteLine("\nTime to process all {0} files: {1}", files.Count(), totalTime.Elapsed);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 0;
}
19
Source : App.xaml.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
static void GlobalExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Log.Error(e.Message);
}
19
Source : TwitchService.cs
with Apache License 2.0
from prom3theu5
with Apache License 2.0
from prom3theu5
private void Client_OnConnectionError(object sender, TwitchLib.Events.Client.OnConnectionErrorArgs e)
{
Log.Error("An error occured connecting to Twitch. Please check your details in config.json");
}
19
Source : BuySellFaultHandler.cs
with GNU General Public License v3.0
from Winster332
with GNU General Public License v3.0
from Winster332
public Task Consume(ConsumeContext<Fault<BuyCurrency>> context)
{
return Task.Factory.StartNew(() =>
{
Log.Error($"FAULT [BuyCurrency]: {context.Message.Message}");
});
}
19
Source : BuySellFaultHandler.cs
with GNU General Public License v3.0
from Winster332
with GNU General Public License v3.0
from Winster332
public Task Consume(ConsumeContext<Fault<SellCurrency>> context)
{
return Task.Factory.StartNew(() =>
{
Log.Error($"FAULT [SellCurrency]: {context.Message.Message}");
});
}
19
Source : RegistryProvider.cs
with MIT License
from WinTenDev
with MIT License
from WinTenDev
public static void Init()
{
RegistryBase.CreateSubKey(rootPath);
_registryRoot = RegistryBase.OpenSubKey(rootPath, true);
if (_registryRoot != null)
{
_registryRoot.CreateSubKey("General");
_registryRoot.CreateSubKey("Database");
_registryRoot.CreateSubKey("Style");
}
else
{
Log.Error("You must execute RegistryProvider.Init() on startup.");
}
}
19
Source : ReportGeneratorService.cs
with GNU General Public License v3.0
from Winster332
with GNU General Public License v3.0
from Winster332
public ReportResult Generate(DateTime from, DateTime to)
{
try
{
var events = _protocolService.Get(from, to);
var lines = new List<string>();
foreach (var e in events)
{
var line = new List<string>();
line.Add(e.Id.ToString());
line.Add(e.Created.ToString());
foreach (var keyValuePair in e.Fields)
{
var value = keyValuePair.Value;
line.Add(value.ToString());
}
line.Add(e.Description);
}
var fileSource = string.Join(",", lines);
using (var stream = new FileStream($"report {from.Day}.{from.Month}.{from.Year}-{to.Day}.{to.Month}.{to.Year}", FileMode.Create))
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(fileSource);
}
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
return null;
}
19
Source : TelegramIntegrations.cs
with GNU General Public License v3.0
from Winster332
with GNU General Public License v3.0
from Winster332
public async Task Start(Func<string> callbackCodeAuth)
{
if (!_settings.Enabled)
{
return;
}
_client = new TelegramClient(_settings.ApiKey, _settings.ApiHash, _store, "session");
var isUserAuthorized = _client.IsUserAuthorized();
Log.Information("Begin connect to telegram");
try
{
await _client.ConnectAsync();
var hash = await _client.SendCodeRequestAsync(_settings.PhoneNumber);
var code = callbackCodeAuth();
_user = await _client.MakeAuthAsync(_settings.PhoneNumber, hash, code);
Log.Information("Telegram api connected");
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
19
Source : TelegramIntegrations.cs
with GNU General Public License v3.0
from Winster332
with GNU General Public License v3.0
from Winster332
public async Task SendInfo(string text)
{
if (!_settings.Enabled)
{
return;
}
try
{
await _client.SendMessageAsync(new TLInputPeerSelf(), $"{GetFormatDateTime()} [INFO] {text}");
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
19
Source : TelegramIntegrations.cs
with GNU General Public License v3.0
from Winster332
with GNU General Public License v3.0
from Winster332
public async Task SendWarn(string text)
{
if (!_settings.Enabled)
{
return;
}
try
{
await _client.SendMessageAsync(new TLInputPeerSelf(), $"{GetFormatDateTime()} [WARN] {text}");
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
19
Source : TelegramIntegrations.cs
with GNU General Public License v3.0
from Winster332
with GNU General Public License v3.0
from Winster332
public async Task SendError(Exception ex)
{
if (!_settings.Enabled)
{
return;
}
try
{
await _client.SendMessageAsync(new TLInputPeerSelf(), $"{GetFormatDateTime()} [ERROR] {ex.ToString()}");
}
catch (Exception e)
{
Log.Error(e.ToString());
}
}
19
Source : TimeUtil.cs
with MIT License
from WinTenDev
with MIT License
from WinTenDev
public static DateTimeOffset ConvertUtcTimeToTimeZone(this DateTime dateTime, string toTimeZoneDesc)
{
if (dateTime.Kind != DateTimeKind.Utc)
{
// throw new Exception("dateTime needs to have Kind property set to Utc");
Log.Error("dateTime needs to have Kind property set to Utc");
}
var toUtcOffset = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc).GetUtcOffset(dateTime);
var convertedTime = DateTime.SpecifyKind(dateTime.Add(toUtcOffset), DateTimeKind.Unspecified);
return new DateTimeOffset(convertedTime, toUtcOffset);
}
19
Source : WoaDeployerConsole.cs
with MIT License
from WOA-Project
with MIT License
from WOA-Project
public async Task Deploy(Device device, bool autoDetect)
{
DisplayInfo();
device = await GetDevice(device, autoDetect);
try
{
Log.Information("Starting deployment for {Device}...", device);
await woaDeployer.Deploy(device);
Log.Information("Deployment finished");
}
catch (RequirementException re)
{
Log.Error($"The script requires the following variables to be defined:\n{string.Join("\n", re.Requirements.Select(s => "-" + s))}\n\nPlease, specify them using the --variables argument");
}
}
See More Examples