Here are the examples of the csharp api System.Console.WriteLine(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2553 Examples
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Path to \"SqExpress\" project folder should be specified as the first argument");
return 1;
}
string projDir = args[0];
if (!Directory.Exists(projDir))
{
Console.WriteLine($"Directory \"{projDir}\" does not exist");
return 2;
}
IReadOnlyList<NodeModel> buffer;
try
{
buffer = BuildModelRoslyn(projDir);
}
catch (Exception e)
{
Console.WriteLine($"Could not build model: {e.Message}");
return 3;
}
try
{
Generate(projDir, @"SyntaxTreeOperations\ExprDeserializer.cs", buffer, GenerateDeserializer);
Generate(projDir, @"SyntaxTreeOperations\Internal\ExprModifier.cs", buffer, GenerateModifier);
Generate(projDir, @"SyntaxTreeOperations\Internal\ExprWalker.cs", buffer, GenerateWalker);
Generate(projDir, @"SyntaxTreeOperations\Internal\ExprWalkerPull.cs", buffer, GenerateWalkerPull);
Generate(projDir, @"SyntaxModifyExtensions.cs", buffer, GenerateSyntaxModify);
Console.WriteLine("Done!");
}
catch (Exception e)
{
Console.WriteLine(e);
return 4;
}
return 0;
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
static async Task Main()
{
Console.WriteLine("SqExpress - get started");
try
{
await RunMsSql("Data Source = (local); Initial Catalog = TestDatabase; Integrated Security = True");
await RunPostgreSql("Host=localhost;Port=5432;Username=postgres;Preplacedword=test;Database=test");
await RunMySql("server=127.0.0.1;uid=test;pwd=test;database=test");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
static async Task Main()
{
try
{
var scenario = new ScCreateTables()
.Then(new ScInsertUserData())
.Then(new ScSqlInjections())
.Then(new ScLike())
.Then(new ScDeleteCustomersByTopUser())
.Then(new ScInsertCompanies())
.Then(new ScUpdateUsers())
.Then(new ScUpdateUserData())
.Then(new ScAllColumnTypes())
.Then(new ScAllColumnTypesExportImport())
.Then(new ScSelectLogic())
.Then(new ScSelectTop())
.Then(new ScSelectSets())
.Then(new ScTempTables())
.Then(new ScCreateOrders())
.Then(new ScreplacedyticFunctionsOrders())
.Then(new ScTransactions(false))
.Then(new ScTransactions(true))
.Then(new ScMerge())
.Then(new ScModelSelector())
;
await ExecScenarioAll(
scenario: scenario,
msSqlConnectionString: "Data Source=(local);Initial Catalog=TestDatabase;Integrated Security=True",
pgSqlConnectionString: "Host=localhost;Port=5432;Username=postgres;Preplacedword=test;Database=test",
mySqlConnectionString: "server=127.0.0.1;uid=test;pwd=test;database=test");
}
catch (SqDatabaseCommandException commandException)
{
Console.WriteLine(commandException.CommandText);
Console.WriteLine(commandException.InnerException);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : Ecdsa.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public bool Verify(in ECPoint q, in Span<byte> r, in Span<byte> s, in Span<byte> hash)
{
try
{
var qCopy = new ECPointRef(stackalloc byte[20], stackalloc byte[20]);
qCopy.CopyFrom(q);
var rCopy = CloneAndExpand(r);
var sCopy = CloneAndExpand(s);
var eCopy = CloneAndExpand(hash);
point_to_mon(qCopy);
bn_reduce(eCopy, ecN, 21);
bn_to_mon(rCopy, ecN, 21);
bn_to_mon(sCopy, ecN, 21);
bn_to_mon(eCopy, ecN, 21);
Span<byte> sInv = stackalloc byte[21];
bn_mon_inv(sInv, sCopy, ecN, 21);
Span<byte> w1 = stackalloc byte[21];
Span<byte> w2 = stackalloc byte[21];
bn_mon_mul(w1, eCopy, sInv, ecN, 21);
bn_mon_mul(w2, rCopy, sInv, ecN, 21);
bn_from_mon(w1, ecN, 21);
bn_from_mon(w2, ecN, 21);
var r1 = new ECPointRef { X = stackalloc byte[20], Y = stackalloc byte[20] };
var r2 = new ECPointRef { X = stackalloc byte[20], Y = stackalloc byte[20] };
point_mul(r1, w1, ecG);
point_mul(r2, w2, qCopy);
point_add(r1, r1, r2);
point_from_mon(r1);
var rr = CloneAndExpand(r1.X);
bn_reduce(rr, ecN, 21);
bn_from_mon(rCopy, ecN, 21);
bn_from_mon(sCopy, ecN, 21);
return bn_compare(rr, rCopy, 21) == 0;
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
19
Source : TextEditorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void LoadRemoteFile(ShellForm _shellForm, string remoteFile, string localFile)
{
try
{
mode = "remote";
shellForm = _shellForm;
remote_file = remoteFile;
local_file = localFile;
shellForm.RunSftpShell("get", remoteFile, localFile, false, false);
org_content = YSTools.YSFile.readFileToString(localFile);
editor.Text = org_content;
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : Form1.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void button1_Click(object sender, EventArgs e)
{
try
{
string host = tb_host.Text;
string acc = tb_acc.Text;
string pwd = tb_pwd.Text;
shell = new SshShell(host, acc, pwd);
//shell.RedirectToConsole();
shell.Connect(22);
m_Channel = shell.getChannel();
string line = null;
ThreadPool.QueueUserWorkItem((a) =>
{
while (shell.ShellOpened)
{
System.Threading.Thread.Sleep(100);
while ((line = m_Channel.GetMessage()) != null)
{
ShowLogger(line);
}
}
Console.Write("Disconnecting...");
shell.Close();
Console.WriteLine("OK");
});
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
using (var fsql = new FreeSqlCloud<DbEnum>("app001"))
{
fsql.DistributeTrace += log => Console.WriteLine(log.Split('\n')[0].Trim());
fsql.Register(DbEnum.db1, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db1.db")
.Build());
fsql.Register(DbEnum.db2, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db2.db")
.Build());
fsql.Register(DbEnum.db3, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db3.db")
.Build());
//for (var a = 0; a < 1000; a++)
//{
//TCC
var tid = Guid.NewGuid().ToString();
fsql
.StartTcc(tid, "创建订单")
.Then<Tcc1>()
.Then<Tcc2>()
.Then<Tcc3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartTcc(tid, "支付购买",
new TccOptions
{
MaxRetryCount = 10,
RetryInterval = TimeSpan.FromSeconds(10)
})
.Then<Tcc1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Tcc2>()
.Then<Tcc3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute();
//Saga
tid = Guid.NewGuid().ToString();
fsql
.StartSaga(tid, "注册用户")
.Then<Saga1>()
.Then<Saga2>()
.Then<Saga3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartSaga(tid, "发表评论",
new SagaOptions
{
MaxRetryCount = 5,
RetryInterval = TimeSpan.FromSeconds(5)
})
.Then<Saga1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Saga2>()
.Then<Saga3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute();
Console.ReadKey();
}
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
async static Task Main(string[] args)
{
using (var fsql = new FreeSqlCloud<DbEnum>("app001"))
{
fsql.DistributeTrace += log => Console.WriteLine(log.Split('\n')[0].Trim());
fsql.Register(DbEnum.db1, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db1.db")
.Build());
fsql.Register(DbEnum.db2, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db2.db")
.Build());
fsql.Register(DbEnum.db3, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db3.db")
.Build());
//for (var a = 0; a < 1000; a++)
//{
//TCC
var tid = Guid.NewGuid().ToString();
await fsql
.StartTcc(tid, "创建订单")
.Then<Tcc1>()
.Then<Tcc2>()
.Then<Tcc3>()
.ExecuteAsync();
tid = Guid.NewGuid().ToString();
await fsql.StartTcc(tid, "支付购买",
new TccOptions
{
MaxRetryCount = 10,
RetryInterval = TimeSpan.FromSeconds(10)
})
.Then<Tcc1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Tcc2>()
.Then<Tcc3>(new LocalState { Id = 3, Name = "tcc3" })
.ExecuteAsync();
//Saga
tid = Guid.NewGuid().ToString();
await fsql
.StartSaga(tid, "注册用户")
.Then<Saga1>()
.Then<Saga2>()
.Then<Saga3>()
.ExecuteAsync();
tid = Guid.NewGuid().ToString();
await fsql.StartSaga(tid, "发表评论",
new SagaOptions
{
MaxRetryCount = 5,
RetryInterval = TimeSpan.FromSeconds(5)
})
.Then<Saga1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Saga2>()
.Then<Saga3>(new LocalState { Id = 3, Name = "tcc3" })
.ExecuteAsync();
Console.ReadKey();
}
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
using (var fsql = new FreeSqlCloud<DbEnum>("app001"))
{
fsql.DistributeTrace += log => Console.WriteLine(log.Split('\n')[0].Trim());
fsql.Register(DbEnum.db1, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db1.db")
.Build());
fsql.Register(DbEnum.db2, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db2.db")
.Build());
fsql.Register(DbEnum.db3, () => new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, @"Data Source=db3.db")
.Build());
//for (var a = 0; a < 1000; a++)
//{
//TCC
var tid = Guid.NewGuid().ToString();
fsql
.StartTcc(tid, "创建订单")
.Then<Tcc1>()
.Then<Tcc2>()
.Then<Tcc3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartTcc(tid, "支付购买",
new TccOptions
{
MaxRetryCount = 10,
RetryInterval = TimeSpan.FromSeconds(10)
})
.Then<Tcc1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Tcc2>()
.Then<Tcc3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute();
//Saga
tid = Guid.NewGuid().ToString();
fsql
.StartSaga(tid, "注册用户")
.Then<Saga1>()
.Then<Saga2>()
.Then<Saga3>()
.Execute();
tid = Guid.NewGuid().ToString();
fsql.StartSaga(tid, "发表评论",
new SagaOptions
{
MaxRetryCount = 5,
RetryInterval = TimeSpan.FromSeconds(5)
})
.Then<Saga1>(new LocalState { Id = 1, Name = "tcc1" })
.Then<Saga2>()
.Then<Saga3>(new LocalState { Id = 3, Name = "tcc3" })
.Execute()
;
Console.ReadKey();
}
}
19
Source : AliyunSmsManager.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public DefaultAcsClient InitSmsClient(string regionId="default")
{
IClientProfile profile = DefaultProfile.GetProfile(regionId, AliyunAccessConfigInfo.AccessKeyId, AliyunAccessConfigInfo.AccessKeySecret);
try
{
var client = new DefaultAcsClient(profile);
return client;
}
catch (Exception e)
{
Console.WriteLine(e);
throw new UserFriendlyException(e.Message);
}
}
19
Source : AliyunSmsManager.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public DefaultAcsClient InitSmsClient(string accessKeyId,string accessKeySecret, string regionId = "default")
{
IClientProfile profile = DefaultProfile.GetProfile(regionId, accessKeyId, accessKeySecret);
try
{
var client = new DefaultAcsClient(profile);
return client;
}
catch (Exception e)
{
Console.WriteLine(e);
throw new UserFriendlyException(e.Message);
}
}
19
Source : AliyunVodManager.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public DefaultAcsClient InitVodClient()
{
IClientProfile profile = DefaultProfile.GetProfile(AliyunVodConfigInfo.RegionId, AliyunAccessConfigInfo.AccessKeyId, AliyunAccessConfigInfo.AccessKeySecret);
try
{
var client = new DefaultAcsClient(profile);
return client;
}
catch (Exception e)
{
Console.WriteLine(e);
throw new UserFriendlyException(e.Message);
}
}
19
Source : AliyunVodManager.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public GetPlayInfoResponse GetPlayInfo(GetPlayInfoRequest input)
{
var client = InitVodClient();
// 发起请求,并得到 response
try
{
GetPlayInfoResponse response = client.GetAcsResponse(input);
return response;
}
catch (Exception e)
{
Console.WriteLine(e);
throw new UserFriendlyException($"获取视频信息报错:{e.Message}");
}
}
19
Source : ResourceRepository.cs
with MIT License
from 99x
with MIT License
from 99x
internal static void Initialize(replacedembly callingreplacedembly)
{
Repo = new ResourceRepository();
var ignorereplacedemblies = new string[] {"RadiumRest", "RadiumRest.Core", "RadiumRest.Selfhost", "mscorlib"};
var referencedreplacedemblies = callingreplacedembly.GetReferencedreplacedemblies();
var currentAsm = replacedembly.GetExecutingreplacedembly().GetName();
var scanreplacedemblies = new List<replacedemblyName>() { callingreplacedembly.GetName()};
foreach (var asm in referencedreplacedemblies)
{
if (asm == currentAsm)
continue;
if (!ignorereplacedemblies.Contains(asm.Name))
scanreplacedemblies.Add(asm);
}
foreach (var refAsm in scanreplacedemblies)
{
try
{
var asm = replacedembly.Load(refAsm.FullName);
foreach (var typ in asm.GetTypes())
{
if (typ.IsSubclreplacedOf(typeof(RestResourceHandler)))
{
var clreplacedAttribObj = typ.GetCustomAttributes(typeof(RestResource), false).FirstOrDefault();
string baseUrl;
if (clreplacedAttribObj != null)
{
var clreplacedAttrib = (RestResource)clreplacedAttribObj;
baseUrl = clreplacedAttrib.Path;
baseUrl = baseUrl.StartsWith("/") ? baseUrl : "/" + baseUrl;
}
else baseUrl = "";
var methods = typ.GetMethods();
foreach (var method in methods)
{
var methodAttribObject = method.GetCustomAttributes(typeof(RestPath), false).FirstOrDefault();
if (methodAttribObject != null)
{
var methodAttrib = (RestPath)methodAttribObject;
string finalUrl = baseUrl + (methodAttrib.Path ?? "");
var finalMethod = methodAttrib.Method;
PathExecutionInfo exeInfo = new PathExecutionInfo
{
Type = typ,
Method = method
};
AddExecutionInfo(finalMethod, finalUrl, exeInfo);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
19
Source : RecordStream.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
protected override async void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_disposed)
{
_disposed = true;
if (_recordFileData != null)
{
try
{
var filePath = _recordFileData.Name;
using (var recordFile = new FileStream(filePath.Substring(0, filePath.Length - 5) + ".flv", FileMode.OpenOrCreate))
{
recordFile.SetLength(0);
recordFile.Seek(0, SeekOrigin.Begin);
await recordFile.WriteAsync(FlvMuxer.MultiplexFlvHeader(true, true));
var metaData = _metaData.Data[1] as Dictionary<string, object>;
metaData["duration"] = ((double)_currentTimestamp) / 1000;
metaData["keyframes"] = _keyframes;
_metaData.MessageHeader.MessageLength = 0;
var dataTagLen = FlvMuxer.MultiplexFlv(_metaData).Length;
var offset = recordFile.Position + dataTagLen;
for (int i = 0; i < _keyframeFilePositions.Count; i++)
{
_keyframeFilePositions[i] = (double)_keyframeFilePositions[i] + offset;
}
await recordFile.WriteAsync(FlvMuxer.MultiplexFlv(_metaData));
_recordFileData.Seek(0, SeekOrigin.Begin);
await _recordFileData.CopyToAsync(recordFile);
_recordFileData.Dispose();
File.Delete(filePath);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
_recordFile?.Dispose();
}
}
19
Source : RecordStream.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
private async Task SeekAndPlay(double milliSeconds, CancellationToken ct)
{
await _playLock.WaitAsync();
Interlocked.Exchange(ref _playing, 1);
try
{
_recordFile.Seek(9, SeekOrigin.Begin);
FlvDemuxer.SeekNoLock(milliSeconds, _metaData == null ? null : _metaData.Data[2] as Dictionary<string, object>, ct);
await StartPlayNoLock(ct);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Interlocked.Exchange(ref _playing, 0);
_playLock.Release();
}
}
19
Source : ThroughputToFileBench.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public static void Run()
{
var dir = Path.GetFullPath(Guid.NewGuid().ToString());
Directory.CreateDirectory(dir);
try
{
Console.WriteLine("Initializing...");
BasicConfigurator.Configure(
new ZeroLogBasicConfiguration
{
Appenders = { new DateAndSizeRollingFileAppender(Path.Combine(dir, "Output")), },
LogEventQueueSize = 1000 * 4096 * 4,
LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
}
);
var log = LogManager.GetLogger(typeof(ThroughputToFileBench));
var duration = TimeSpan.FromSeconds(10);
Console.WriteLine("Starting...");
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var sw = Stopwatch.StartNew();
long counter = 0;
while (sw.Elapsed < duration)
{
counter++;
log.Debug().Append("Counter is: ").Append(counter).Log();
}
Console.WriteLine($"Log events: {counter:N0}, Time to append: {sw.Elapsed}");
Console.WriteLine("Flushing...");
LogManager.Shutdown();
Console.WriteLine($"Time to flush: {sw.Elapsed}");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Directory.Delete(dir, true);
}
Console.WriteLine("Done");
}
19
Source : CommandParameterHelpers.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool TryParsePosition(string[] parameters, out string errorMessage, out Position position, int startingElement = 0)
{
errorMessage = string.Empty;
position = null;
if (parameters.Length - startingElement - 1 < 1)
{
errorMessage = "not enough parameters";
return false;
}
string northSouth = parameters[startingElement].ToLower().Replace(",", "").Trim();
string eastWest = parameters[startingElement + 1].ToLower().Replace(",", "").Trim();
if (!northSouth.EndsWith("n") && !northSouth.EndsWith("s"))
{
errorMessage = "Missing n or s indicator on first parameter";
return false;
}
if (!eastWest.EndsWith("e") && !eastWest.EndsWith("w"))
{
errorMessage = "Missing e or w indicator on second parameter";
return false;
}
if (!float.TryParse(northSouth.Substring(0, northSouth.Length - 1), out float coordNS))
{
errorMessage = "North/South coordinate is not a valid number.";
return false;
}
if (!float.TryParse(eastWest.Substring(0, eastWest.Length - 1), out float coordEW))
{
errorMessage = "East/West coordinate is not a valid number.";
return false;
}
if (northSouth.EndsWith("s"))
{
coordNS *= -1.0f;
}
if (eastWest.EndsWith("w"))
{
coordEW *= -1.0f;
}
try
{
position = new Position(coordNS, coordEW);
position.AdjustMapCoords();
}
catch (Exception e)
{
Console.WriteLine(e);
errorMessage = $"There was a problem with that location (bad coordinates?).";
return false;
}
return true;
}
19
Source : ActionMap.cs
with MIT License
from active-logic
with MIT License
from active-logic
internal void Print(object arg){
if(!verbose) return;
#if UNITY_2018_1_OR_NEWER
Debug.Log(arg);
#else
System.Console.WriteLine(arg);
#endif
}
19
Source : RpcServiceTestHost.cs
with MIT License
from ad313
with MIT License
from ad313
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//var result = await _eventBusProvider.RpcClientAsync<int>("aaaaa", new object[] { "avalue1", 1, new clreplaced1 { Id = 1, Money = 11, Name = "sfsf" } });
//Console.WriteLine($"result1 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");
////await Task.Delay(2000);
//var result2 = await _eventBusProvider.RpcClientAsync<int>("test_aaaaa2", new object[] { "avalue2", 2, new clreplaced1 { Id = 2, Money = 11, Name = "sfsf" } });
//Console.WriteLine($"result2 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");
try
{
await _eventBusProvider.PublishAsync("tst-aaa", new EventMessageModel<clreplaced1>(new clreplaced1(){Money = 1111m}));
}
catch (Exception e)
{
Console.WriteLine(e);
}
await Task.Delay(3000);
try
{
await _eventBusProvider.PublishAsync("tst-aaa", new EventMessageModel<clreplaced1>(new clreplaced1() { Money = 1111m }));
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : EHHelper.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
private static bool BuildInternalPreserve(Type type)
{
try
{
const BindingFlags fl = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
var at = (string) typeof(Environment).InvokeMember("GetResourceString", fl, null, null, new object[] {"Word_At"});
var preserve = type.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
var field = type.GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
var stackTrace = type.GetProperty("StackTrace", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
var fmt = typeof(string).GetMethod("Format", new[] {typeof(string), typeof(object), typeof(object)});
var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)}, true);
var ilGen = dm.GetILGenerator();
var lbl = ilGen.DefineLabel();
var lbl2 = ilGen.DefineLabel();
var lbl3 = ilGen.DefineLabel();
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl2);
ilGen.Emit(System.Reflection.Emit.OpCodes.Callvirt, stackTrace);
ilGen.Emit(System.Reflection.Emit.OpCodes.Br, lbl3);
ilGen.MarkLabel(lbl2);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
ilGen.MarkLabel(lbl3);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Call, preserve);
ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
ilGen.Emit(System.Reflection.Emit.OpCodes.Brfalse, lbl);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldstr,
"{1}" + Environment.NewLine + " " + at + " DarksVM.Load() [{0}]" + Environment.NewLine);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Call, fmt);
ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);
ilGen.MarkLabel(lbl);
ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);
rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
}
catch(Exception ex)
{
Console.WriteLine(ex);
return false;
}
return true;
}
19
Source : Program.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static void Main(string[] args)
{
RegisterreplacedemblyResolveEvent();
ILogger<Program> logger = NullLogger<Program>.Instance;
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception e)
{
if (logger == NullLogger<Program>.Instance)
Console.WriteLine(e);
logger.LogCritical(e, "program crashed");
}
}
19
Source : XmlHelper.cs
with MIT License
from afaniuolo
with MIT License
from afaniuolo
public static string GetXmlElementValue(string fieldValue, string elementName, bool throwOnError = false)
{
if (!string.IsNullOrEmpty(fieldValue) && !string.IsNullOrEmpty(elementName))
{
XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
fieldValue = SanitizeFieldValue(fieldValue);
try
{
xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));
XmlNodeList elementsByTagName = xmlDoreplacedent.GetElementsByTagName(elementName);
if (elementsByTagName.Count > 0)
{
var element = elementsByTagName.Item(0);
return element?.InnerXml;
}
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("XmlHelper - GetXmlElementValue - Failed to parse Xml value - Value = " + fieldValue);
Console.WriteLine(e);
Console.WriteLine();
if (throwOnError)
{
Console.WriteLine("See logs for more details in the logs folder.");
Console.WriteLine();
throw;
}
}
}
return string.Empty;
}
19
Source : XmlHelper.cs
with MIT License
from afaniuolo
with MIT License
from afaniuolo
public static string StripHtml(string fieldValue)
{
if (!string.IsNullOrEmpty(fieldValue))
{
XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
fieldValue = SanitizeFieldValue(fieldValue);
try
{
xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));
return xmlDoreplacedent.InnerText;
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("XmlHelper - StripHtml - Failed to parse Xml value - Value = " + fieldValue);
Console.WriteLine(e);
Console.WriteLine();
}
}
return fieldValue;
}
19
Source : XmlHelper.cs
with MIT License
from afaniuolo
with MIT License
from afaniuolo
public static List<string> GetXmlElementNames(string fieldValue)
{
List<string> elementNames = new List<string>();
XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
fieldValue = SanitizeFieldValue(fieldValue);
try
{
xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));
foreach (XmlNode childNode in xmlDoreplacedent.ChildNodes.Item(0).ChildNodes)
{
elementNames.Add(childNode.Name);
}
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("XmlHelper - GetXmlElementNames - Failed to parse Xml value - Value = " + fieldValue);
Console.WriteLine(e);
Console.WriteLine();
Console.WriteLine("See logs for more details in the logs folder.");
Console.WriteLine();
throw;
}
return elementNames;
}
19
Source : XmlHelper.cs
with MIT License
from afaniuolo
with MIT License
from afaniuolo
public static XmlNode GetXmlElementNode(string fieldValue, string elementName, bool throwOnError = false)
{
if (!string.IsNullOrEmpty(fieldValue) && !string.IsNullOrEmpty(elementName))
{
XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
fieldValue = SanitizeFieldValue(fieldValue);
try
{
xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));
XmlNodeList elementsByTagName = xmlDoreplacedent.GetElementsByTagName(elementName);
if (elementsByTagName.Count > 0)
{
return elementsByTagName.Item(0);
}
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("XmlHelper - GetXmlElementNode - Failed to parse Xml value - Value = " + fieldValue);
Console.WriteLine(e);
Console.WriteLine();
if (throwOnError)
{
Console.WriteLine("See logs for more details in the logs folder.");
Console.WriteLine();
throw;
}
}
}
return null;
}
19
Source : XmlHelper.cs
with MIT License
from afaniuolo
with MIT License
from afaniuolo
public static XmlNodeList GetXmlElementNodeList(string fieldValue, string elementName, bool throwOnError = false)
{
if (!string.IsNullOrEmpty(fieldValue) && !string.IsNullOrEmpty(elementName))
{
XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
fieldValue = SanitizeFieldValue(fieldValue);
try
{
xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));
XmlNodeList elementsByTagName = xmlDoreplacedent.GetElementsByTagName(elementName);
if (elementsByTagName.Count > 0)
{
return elementsByTagName;
}
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("XmlHelper - GetXmlElementNodeList - Failed to parse Xml value - Value = " + fieldValue);
Console.WriteLine(e);
Console.WriteLine();
if (throwOnError)
{
Console.WriteLine("See logs for more details in the logs folder.");
Console.WriteLine();
throw;
}
}
}
return null;
}
19
Source : LogRecorder.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
internal static void RecordInner(LogLevel level, string name, string msg, LogType type, string typeName = null)
{
try
{
if (level < Level)
return;
if (type == LogType.None)
type = LogType.Message;
if (State == LogRecorderStatus.Shutdown)
{
SystemTrace(level, name, msg);
}
//else if (level < Level)
//{
// if (type != LogType.Monitor)
// SystemTrace(level, name, msg);
//}
else if (RecordInfos.WaitCount > 1024)
{
if ((DateTime.Now.Ticks % 10) == 1 || type != LogType.DataBase && type != LogType.Monitor && level >= LogLevel.Warning)
RecordInfos.Push(new RecordInfo
{
Local = InRecording,
RequestID = GetRequestId(),
Machine = GetMachineName(),
User = GetUserName(),
Name = name,
Type = type,
Message = msg,
Time = DateTime.Now,
ThreadID = Thread.CurrentThread.ManagedThreadId,
TypeName = typeName ?? LogEnumHelper.TypeToString(type)
});
}
else
{
RecordInfos.Push(new RecordInfo
{
Local = InRecording,
RequestID = GetRequestId(),
Machine = GetMachineName(),
User = GetUserName(),
Name = name,
Type = type,
Message = msg,
Time = DateTime.Now,
ThreadID = Thread.CurrentThread.ManagedThreadId,
TypeName = typeName ?? LogEnumHelper.TypeToString(type)
});
}
if (BackIsRuning == 0)
NewRecorderThread();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : IocScope.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
protected override void OnDispose()
{
if (DisposeFunc != null)
{
foreach (var func in DisposeFunc)
{
try
{
func();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Local.Value = null;
}
try
{
IocHelper.DisposeScope();
_scope.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e);
}
GC.Collect();
}
19
Source : LogRecorder.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private static void WriteRecordLoop()
{
bool success = true;
try
{
if (Interlocked.Increment(ref BackIsRuning) > 1)
{
return;
}
SystemTrace(LogLevel.System, "日志开始");
int cnt = 0;
while (State != LogRecorderStatus.Shutdown)
{
//Thread.Sleep(10);//让子弹飞一会
if (State < LogRecorderStatus.Initialized || !BaseRecorder.IsInitialized || !Recorder.IsInitialized)
{
Thread.Sleep(50);
continue;
}
var array = RecordInfos.Switch();
if (array.Count == 0)
{
Thread.Sleep(50);
continue;
}
foreach (var info in array)
{
if (info == null)
continue;
try
{
info.Index = ++_id;
if (_id == ulong.MaxValue)
_id = 1;
if (!_isTextRecorder && (info.Type >= LogType.System || info.Local))
BaseRecorder.RecordLog(info);
if (Listener != null || TraceToConsole)
DoTrace(info);
}
catch (Exception ex)
{
SystemTrace(LogLevel.Error, "日志写入发生错误", ex);
}
}
try
{
Recorder.RecordLog(array.ToList());
}
catch (Exception ex)
{
SystemTrace(LogLevel.Error, "日志写入发生错误", ex);
}
if (++cnt < 1024)
continue;
GC.Collect();
cnt = 0;
}
_syncSlim.Release();
}
catch (Exception e)
{
success = false;
Console.WriteLine(e);
}
finally
{
Interlocked.Decrement(ref BackIsRuning);
SystemTrace(LogLevel.System, "日志结束");
}
if (!success)
NewRecorderThread();
}
19
Source : ApiCounter.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
void Save()
{
try
{
File.WriteAllText(Path.Combine(ZeroApplication.Config.DataFolder, "ApiCount.json"), JsonConvert.SerializeObject(Root, Formatting.Indented));
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
19
Source : ApiCounter.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
void Load()
{
var file = Path.Combine(ZeroApplication.Config.DataFolder, "ApiCount.json");
if (!File.Exists(file))
return;
try
{
var json = File.ReadAllText(file);
if (string.IsNullOrWhiteSpace(json))
return;
_root = JsonConvert.DeserializeObject<Counreplacedem>(json) ?? new Counreplacedem();
RebuildItems(_root);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
19
Source : SyncBatchQueue.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public bool Load(string file)
{
if (!File.Exists(file))
{
index = 1;
now = Line1;
return false;
}
index = 2;
now = Line2;
try
{
var json = File.ReadAllText(file);
var inner = JsonConvert.DeserializeObject<List<TData>>(json);
if (inner != null)
foreach (var item in inner)
Line1.Add(item);
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
finally
{
File.Delete(file);
}
}
19
Source : RuntimeWaring.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public override void Handle(Publireplacedem args)
{
if (args.Subreplacedle == "Flush")
{
Flush();
return;
}
try
{
var data = JsonConvert.DeserializeObject<WaringItem>(args.Content);
Waring(data.Host, data.Api, data.Message);
}
catch (Exception e)
{
ZeroTrace.WriteException("RuntimeWaring", e, args.Content);
Console.WriteLine(e);
}
}
19
Source : BaseShimHandler.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public void Run(PairSocket shim)
{
string shimAdd = $"inproc://wsrouter-{Id}";
Monitor.Enter(this);
try
{
isRuning = true;
shim.SignalOK();
shim.ReceiveReady += OnShimReady;
MessagesPipe = new PairSocket();
MessagesPipe.Connect(shimAdd);
MessagesPipe.ReceiveReady += OnMessagePipeReady;
Stream = new StreamSocket();
Stream.Bind(Address);
Stream.ReceiveReady += OnStreamReady;
Poller = new NetMQPoller
{
MessagesPipe,
shim,
Stream
};
MessagesPipe.SignalOK();
Poller.Run();
shim.Dispose();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Monitor.Exit(this);
}
}
19
Source : AgoraVideoViewRenderer.cs
with MIT License
from AgoraIO-Community
with MIT License
from AgoraIO-Community
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(AgoraVideoView.StreamUID) || e.PropertyName == nameof(AgoraVideoView.Mode))
{
try
{
if (_callView.IsStatic)
{
_layout = new UIView(new RectangleF(0, 0, (float)Element.Width, (float)Element.Height)) { Hidden = false };
_videoService = Xamarin.Agora.Full.Forms.AgoraService.Current as AgoraServiceImplementation;
SetNativeControl(_layout);
_videoService.SetupView(UpdatedHolder());
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
_holder.NativeView?.RemoveFromSuperview();
}
}
base.OnElementPropertyChanged(sender, e);
}
19
Source : AgoraVideoViewRenderer.cs
with MIT License
from AgoraIO-Community
with MIT License
from AgoraIO-Community
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(AgoraVideoView.StreamUID) || e.PropertyName == nameof(AgoraVideoView.Mode))
{
try
{
if (_callView.IsStatic)
{
_layout = new NSView(new CoreGraphics.CGRect(0, 0, (nfloat)Element.Width, (nfloat)Element.Height)); //(new RectangleF(0, 0, width, height)) { Hidden = false };
_videoService = Xamarin.Agora.Full.Forms.AgoraService.Current as AgoraServiceImplementation;
SetNativeControl(_layout);
_videoService.SetupView(UpdatedHolder());
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
_holder.NativeView?.RemoveFromSuperview();
}
}
base.OnElementPropertyChanged(sender, e);
}
19
Source : SsdpClient.cs
with MIT License
from aguang-xyz
with MIT License
from aguang-xyz
private void SearchAndWaitForReplies(object sender, ElapsedEventArgs e)
{
var dgram = BuildSearchDgram(Convert.ToInt32(SearchInterval.TotalSeconds));
using var client = BuildUdpClientForSearch();
client.Send(dgram, dgram.Length, new IPEndPoint(MulticastAddress, MulticastPort));
var startedAt = DateTimeOffset.Now;
while (DateTimeOffset.Now < startedAt.AddMilliseconds(SearchInterval.TotalMilliseconds))
{
try
{
var endpoint = new IPEndPoint(IPAddress.Any, 0);
var message = Encoding.UTF8.GetString(client.Receive(ref endpoint));
var serviceInfo = ParseReplyMessage(message);
if (serviceInfo != null)
{
TryAddService(serviceInfo);
}
}
catch (SocketException)
{
// Ignored
}
catch (ObjectDisposedException)
{
// Ignored
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
}
19
Source : SsdpClient.cs
with MIT License
from aguang-xyz
with MIT License
from aguang-xyz
private void CheckNotifications(object sender, ElapsedEventArgs e)
{
var startedAt = DateTimeOffset.Now;
while (DateTimeOffset.Now < startedAt.AddMilliseconds(CheckInterval.TotalMilliseconds))
{
try
{
var endpoint = new IPEndPoint(IPAddress.Any, 0);
var message = Encoding.UTF8.GetString(_checkUdpClient.Receive(ref endpoint));
var (serviceInfo, alive) = ParseNotifyMessage(message);
if (serviceInfo != null)
{
if (alive)
{
TryAddService(serviceInfo);
}
else
{
TryRemoveService(serviceInfo);
}
}
}
catch (SocketException)
{
// Ignored
}
catch (ObjectDisposedException)
{
// Ignored
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
}
19
Source : Core.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
public async static Task SaveExceptionAsync(Exception e)
{
Console.WriteLine(e);
DateTime now = DateTime.Now;
string str = string.Concat(new object[] { now.Year, "-", now.Month, "-", now.Day, "//" });
if (!Directory.Exists($"{UserLocalAppFolderPath}..\\Logs"))
{
Directory.CreateDirectory($"{UserLocalAppFolderPath}..\\Logs");
}
if (!Directory.Exists($"{UserLocalAppFolderPath}..\\Logs\\{str}"))
{
Directory.CreateDirectory($"{UserLocalAppFolderPath}..\\Logs\\{str}");
}
await Task.Run(() =>
{
File.WriteAllLines(($"{UserLocalAppFolderPath}..\\Logs\\{str}\\") + string.Concat(new object[] { now.Hour, "-", now.Minute, "-", now.Second, "-", now.Ticks & 10L }) + ".txt", new List<string>
{
"----Exception message----",
e.Message,
"----End of exception message----\r\n",
"----Stack trace----",
e.StackTrace,
"----End of stack trace----\r\n"
}.ToArray());
});
}
19
Source : Core.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
public static void SaveException(Exception e)
{
lock (e)
{
Console.WriteLine(e);
DateTime now = DateTime.Now;
string str = string.Concat(new object[] { now.Year, "-", now.Month, "-", now.Day, "//" });
if (!Directory.Exists($"{UserLocalAppFolderPath}..\\Logs"))
{
Directory.CreateDirectory($"{UserLocalAppFolderPath}..\\Logs");
}
if (!Directory.Exists($"{UserLocalAppFolderPath}..\\Logs\\{str}"))
{
Directory.CreateDirectory($"{UserLocalAppFolderPath}..\\Logs\\{str}");
}
File.WriteAllLines(($"{UserLocalAppFolderPath}..\\Logs\\{str}\\") + string.Concat(new object[] { now.Hour, "-", now.Minute, "-", now.Second, "-", now.Ticks & 10L }) + ".txt", new List<string>
{
"----Exception message----",
e.Message,
"----End of exception message----\r\n",
"----Stack trace----",
e.StackTrace,
"----End of stack trace----\r\n"
}.ToArray());
}
}
19
Source : App.xaml.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
private async void Application_Startup(object sender, StartupEventArgs e)
{
await _host.StartAsync();
// if the app lost this data for some reason
// or the app runs for the first time
// it will load the default theme in App.xaml file
if (!string.IsNullOrEmpty(WPF.Properties.Settings.Default.PrimaryColor) && !string.IsNullOrEmpty(WPF.Properties.Settings.Default.AccentColor))
{
try
{
IEnumerable<Swatch> Swatches = new SwatchesProvider().Swatches;
PaletteSelectorViewModel.ApplyPrimary(Swatches.FirstOrDefault(x => x.Name == WPF.Properties.Settings.Default.PrimaryColor.ToLower()));
PaletteSelectorViewModel.ApplyAccent(Swatches.FirstOrDefault(x => x.Name == WPF.Properties.Settings.Default.AccentColor.ToLower()));
PaletteSelectorViewModel.ApplyBase(WPF.Properties.Settings.Default.IsDarkTheme);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
_host.Services
.GetRequiredService<IWindowManager>()
.ShowWindow<LoginViewModel>();
}
19
Source : DefaultLogger.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!this.IsEnabled(logLevel))
return;
lock (_lock)
{
var ename = eventId.Name;
ename = ename?.Length > 12 ? ename?.Substring(0, 12) : ename;
Console.Write($"[{DateTimeOffset.Now.ToString(this.TimestampFormat)}] [{eventId.Id,-4}/{ename,-12}] ");
switch (logLevel)
{
case LogLevel.Trace:
Console.ForegroundColor = ConsoleColor.Gray;
break;
case LogLevel.Debug:
Console.ForegroundColor = ConsoleColor.DarkMagenta;
break;
case LogLevel.Information:
Console.ForegroundColor = ConsoleColor.DarkCyan;
break;
case LogLevel.Warning:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case LogLevel.Error:
Console.ForegroundColor = ConsoleColor.Red;
break;
case LogLevel.Critical:
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
break;
}
Console.Write(logLevel switch
{
LogLevel.Trace => "[Trace] ",
LogLevel.Debug => "[Debug] ",
LogLevel.Information => "[Info ] ",
LogLevel.Warning => "[Warn ] ",
LogLevel.Error => "[Error] ",
LogLevel.Critical => "[Crit ]",
LogLevel.None => "[None ] ",
_ => "[?????] "
});
Console.ResetColor();
//The foreground color is off.
if (logLevel == LogLevel.Critical)
Console.Write(" ");
var message = formatter(state, exception);
Console.WriteLine(message);
if (exception != null)
Console.WriteLine(exception);
}
19
Source : AppResourceService.cs
with MIT License
from aimore
with MIT License
from aimore
public async static Task<bool> GetAppText()
{
var httpResponseMessage = await Client.GetAsync(_stringJsonUrl);
try
{
httpResponseMessage.EnsureSuccessStatusCode();
string jsonString = await httpResponseMessage.Content.ReadreplacedtringAsync();
TextResource = JsonConvert.DeserializeObject<AppResource>(jsonString);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
19
Source : InspectMessageType.cs
with GNU Affero General Public License v3.0
from ais-dotnet
with GNU Affero General Public License v3.0
from ais-dotnet
public void OnError(in ReadOnlySpan<byte> line, Exception error, int lineNumber)
{
Console.WriteLine(error);
}
19
Source : ContentsBrowser.cs
with MIT License
from alaabenfatma
with MIT License
from alaabenfatma
private void MakeThumbnail(string path)
{
try
{
var thumbnail = Template.FindName("Thumbnail", this) as Rectangle;
var bmp = new Bitmap(Path);
thumbnail.Fill = new ImageBrush(MagicLaboratory.ImageSourceForBitmap(bmp));
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : ContentsBrowser.cs
with MIT License
from alaabenfatma
with MIT License
from alaabenfatma
private void MakeThumbnail()
{
try
{
var thumbnail = Template.FindName("Thumbnail", this) as Rectangle;
var icon = System.Drawing.Icon.ExtractreplacedociatedIcon(Path);
var bmp = icon.ToBitmap();
thumbnail.Fill = new ImageBrush(MagicLaboratory.ImageSourceForBitmap(bmp));
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : Node.cs
with MIT License
from alaabenfatma
with MIT License
from alaabenfatma
public void FuncNodeInit()
{
ApplyTemplate();
_backgroundBorder = (Border) Template.FindName("BackgroundBorder", this);
IsSelected = true;
InExecPortsPanel = (StackPanel) Template.FindName("InExecPorts", this);
OutExecPortsPanel = (StackPanel) Template.FindName("OutExecPorts", this);
InputPortsPanel = (StackPanel) Template.FindName("InputPorts", this);
InputPortsControls = (StackPanel) Template.FindName("InputPortsControl", this);
OutputPortsPanel = (StackPanel) Template.FindName("OutputPorts", this);
BottomControl = (Control) Template.FindName("BottomControl", this);
foreach (var port in InExecPorts)
InExecPortsPanel?.Children.Add(port);
foreach (var port in OutExecPorts)
OutExecPortsPanel?.Children.Add(port);
foreach (var port in InputPorts)
if (!InputPortsPanel.Children.Contains(port))
InputPortsPanel?.Children.Add(port);
foreach (var port in OutputPorts)
if (!OutputPortsPanel.Children.Contains(port))
try
{
OutputPortsPanel.Children.Add(port);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
var inPortsPanel = (StackPanel) Template.FindName("InputPorts", this);
var outPortsPanel = (StackPanel) Template.FindName("OutputPorts", this);
if (OutExecPortsPanel != null) OutExecPortsPanel.SizeChanged += (sender, args) => OnChangedSize();
if (inPortsPanel != null) inPortsPanel.SizeChanged += (sender, args) => OnChangedSize();
if (outPortsPanel != null) outPortsPanel.SizeChanged += (sender, args) => OnChangedSize();
OnChangedSize();
}
19
Source : ListUtilities.cs
with MIT License
from alaabenfatma
with MIT License
from alaabenfatma
private void ConnectorsList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Validations
if (Count <= 0) return;
if (Count == 1)
for (var index = 0; index < Count; index++)
try
{
var c = this[index];
if (c.EndPort.ParentNode
.IsCollapsed)
{
c.StartPort.Linked = false;
c.Wire.Visibility = Visibility.Collapsed;
c.EndPort.Linked = false;
ClearConnectors();
break;
}
if (!c.StartPort.ParentNode
.IsCollapsed) continue;
c.StartPort.Linked = false;
c.EndPort.Linked = false;
c.Wire.Visibility = Visibility.Collapsed;
ClearConnectors();
break;
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
foreach (var c in this)
if (Equals(c.EndPort.ParentNode, c.StartPort.ParentNode))
c.Wire.Visibility = Visibility.Collapsed;
}
19
Source : ActionMods.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
public static Tuple<bool, string, bool> ExecuteModAction(string name, string parameter = "") {
MainProgram.DoDebug("[MOD ACTION] Running mod action \"" + name + "\"");
string actionErrMsg = "No error message set",
modLocation = Path.Combine(MainProgram.actionModsPath, modActions[name]),
infoJsonFile = Path.Combine(modLocation, "info.json");
if (File.Exists(infoJsonFile)) {
string modFileContent = ReadInfoFile(infoJsonFile);
if (modFileContent != null) {
try {
dynamic jsonTest = JsonConvert.DeserializeObject<dynamic>(modFileContent);
if (jsonTest != null) {
if (ValidateInfoJson(jsonTest)) {
//JSON is valid - get script file
string scriptFile = jsonTest["options"]["file_name"], scriptFileLocation = Path.Combine(modLocation, scriptFile);
bool actionIsFatal = jsonTest["options"]["is_fatal"] ?? false,
requiresParameter = jsonTest["options"]["requires_param"] ?? false,
requiresSecondaryParameter = jsonTest["options"]["require_second_param"] ?? false;
if (requiresParameter ? !String.IsNullOrEmpty(parameter) : true) {
Console.WriteLine("Requires parameter? " + requiresParameter);
Console.WriteLine("Has parameter? " + !String.IsNullOrEmpty(parameter));
string[] secondaryParameters = ActionChecker.GetSecondaryParam(parameter);
if (requiresSecondaryParameter ? secondaryParameters.Length > 1 : true) { //Also returns the first parameter
if (File.Exists(scriptFileLocation)) {
string accArg = requiresParameter && requiresSecondaryParameter ? JsonConvert.SerializeObject(ActionChecker.GetSecondaryParam(parameter)) : (requiresParameter ? parameter : "");
try {
ProcessStartInfo p = new ProcessStartInfo {
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
string theExtension = Path.GetExtension(scriptFile);
if (theExtension == ".ps1") {
//Is powershell - open it correctly
p.FileName = "powershell.exe";
p.Arguments = String.Format("-WindowStyle Hidden -file \"{0}\" \"{1}\"", scriptFileLocation, accArg);
} else if (theExtension == ".py") {
//Python - open it correctly
string minPythonVersion = (jsonTest["options"]["min_python_version"] ?? ""),
maxPythonVersion = (jsonTest["options"]["max_python_version"] ?? ""),
pythonPath = GetPythonPath(minPythonVersion, maxPythonVersion);
if (pythonPath != "") {
p.FileName = GetPythonPath();
p.Arguments = String.Format("{0} \"{1}\"", scriptFileLocation, accArg);
} else {
//No python version (or one with the min-max requirements) not found.
string pythonErr;
if (minPythonVersion == "" && maxPythonVersion == "") {
//Python just not found
pythonErr = "We could not locate Python on your computer. Please either download Python or specify its path in the ACC settings if it's already installed.";
} else {
if (minPythonVersion != "" && maxPythonVersion != "") {
//Both min & max set
pythonErr = "We could not locate a version of Python between v" + minPythonVersion + " and v" + maxPythonVersion + ". Please either download a version of Python in between the specified versions, or specify its path in the ACC settings if it's already installed.";
} else {
if (minPythonVersion != "") {
//Min only
pythonErr = "We could not locate a version of Python greater than v" + minPythonVersion + ". Please either download Python (min version " + minPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
} else {
//Max only
pythonErr = "We could not locate a version of Python lower than v" + maxPythonVersion + ". Please either download Python (max version " + maxPythonVersion + ") or specify its path in the ACC settings if it's already installed.";
}
}
}
return Tuple.Create(false, pythonErr, false);
}
} else if (theExtension == ".bat" || theExtension == ".cmd" || theExtension == ".btm") {
//Is batch - open it correctly (https://en.wikipedia.org/wiki/Batch_file#Filename_extensions)
p.FileName = "cmd.exe";
p.Arguments = String.Format("/c {0} \"{1}\"", scriptFileLocation, accArg);
} else {
//"Other" filetype. Simply open file.
p.FileName = scriptFileLocation;
p.Arguments = accArg;
}
Process theP = Process.Start(p);
if (!theP.WaitForExit(5000)) {
MainProgram.DoDebug("Action mod timed out");
theP.Kill();
}
string output = theP.StandardOutput.ReadToEnd();
using (StringReader reader = new StringReader(output)) {
string line;
while ((line = reader.ReadLine()) != null) {
if (line.Length >= 17) {
if (line.Substring(0, 12) == "[ACC RETURN]") {
//Return for ACC
string returnContent = line.Substring(13),
comment = returnContent.Contains(',') ? returnContent.Split(',')[1] : "";
bool actionSuccess = returnContent.Substring(0, 4) == "true";
if (comment.Length > 0 && char.IsWhiteSpace(comment, 0)) {
comment = comment.Substring(1);
}
if (actionSuccess) {
//Action was successfull
Console.WriteLine("Action successful!");
} else {
//Action was not successfull
Console.WriteLine("Action failed :(");
}
Console.WriteLine("Comment; " + comment);
return Tuple.Create(actionSuccess, (comment.Length > 0 ? comment : "Action mod returned no reason for failing"), actionIsFatal);
}
}
}
}
return Tuple.Create(false, "Action mod didn't return anything to ACC", false);
} catch (Exception e) {
//Process init failed - it shouldn't, but better safe than sorry
actionErrMsg = "Process initiation failed";
Console.WriteLine(e);
}
} else {
//Script file doesn't exist
actionErrMsg = "Action mod script doesn't exist";
}
} else {
actionErrMsg = "Action \"" + name + "\" requires a secondary parameter to be set";
}
} else {
actionErrMsg = "Action \"" + name + "\" requires a parameter to be set";
}
} else {
//JSON is not valid; validateErrMsg
actionErrMsg = validateErrMsg;
}
} else {
//JSON is invalid or failed
actionErrMsg = "Action mod JSON is invalid";
}
} catch (Exception e) {
//Failed to parse
actionErrMsg = "Failed to parse action mod JSON";
Console.WriteLine(e.Message);
}
} else {
//Couldn't read file
MainProgram.DoDebug("1");
}
} else {
MainProgram.DoDebug("0; " + modLocation);
}
return Tuple.Create(false, actionErrMsg, false);
}
See More Examples