Here are the examples of the csharp api System.IO.Directory.GetCurrentDirectory() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3512 Examples
19
Source : TriggerTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestOSSTrigger()
{
tf.Client.CreateService(new CreateServiceRequest(Service));
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));
string triggerName = "my-oss-trigger";
string[] events = { "oss:ObjectCreated:PostObject", "oss:ObjectCreated:PutObject" };
var ossTriggerConfig = new OSSTriggerConfig(events, "pre", ".zip");
string sourceArn = string.Format("acs:oss:{0}:{1}:{2}", tf.Region, tf.AccountID, tf.CodeBucket);
var response = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "oss",
sourceArn, tf.InvocationRole, ossTriggerConfig, "oss trigger desc"));
this.Triggers.Add(triggerName);
replacedert.Equal(triggerName, response.Data.TriggerName);
replacedert.Equal("oss trigger desc", response.Data.Description);
replacedert.Equal("oss", response.Data.TriggerType);
replacedert.Equal(sourceArn, response.Data.SourceArn);
replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
replacedert.Equal(JsonConvert.DeserializeObject<OSSTriggerConfig>(response.Data.TriggerConfig.ToString()), ossTriggerConfig);
}
19
Source : TriggerTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestLogTrigger()
{
tf.Client.CreateService(new CreateServiceRequest(Service));
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));
string triggerName = "my-log-trigger";
SouceConfig source = new SouceConfig(tf.LogStore + "_source");
LogConfig logConfig = new LogConfig(tf.LogProject, tf.LogStore);
JobConfig jobConfig = new JobConfig(60, 10);
var functionParameter = new Dictionary<string, object> { };
var logTriggerConfig = new LogTriggerConfig(source, jobConfig, functionParameter, logConfig, false);
string sourceArn = string.Format("acs:log:{0}:{1}:project/{2}", tf.Region, tf.AccountID, tf.LogProject);
var response = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "log",
sourceArn, tf.InvocationRole, logTriggerConfig, "log trigger desc"));
this.Triggers.Add(triggerName);
replacedert.Equal(triggerName, response.Data.TriggerName);
replacedert.Equal("log trigger desc", response.Data.Description);
replacedert.Equal("log", response.Data.TriggerType);
replacedert.Equal(sourceArn, response.Data.SourceArn);
replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
replacedert.Equal(JsonConvert.DeserializeObject<LogTriggerConfig>(response.Data.TriggerConfig.ToString()), logTriggerConfig);
}
19
Source : TriggerTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestTriggerCRUD()
{
tf.Client.CreateService(new CreateServiceRequest(Service));
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));
string triggerName = "my-http-trigger";
var httpTriggerConfig = new HttpTriggerConfig(HttpAuthType.ANONYMOUS, new HttpMethod[] { HttpMethod.GET, HttpMethod.POST });
var response1 = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "http", "dummy_arn", "", httpTriggerConfig));
this.Triggers.Add(triggerName);
replacedert.Equal(triggerName, response1.Data.TriggerName);
replacedert.Equal("", response1.Data.Description);
replacedert.Equal("http", response1.Data.TriggerType);
replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response1.Data.TriggerConfig.ToString()), httpTriggerConfig);
var newHttpTriggerConfig = new HttpTriggerConfig(HttpAuthType.ANONYMOUS, new HttpMethod[] { HttpMethod.GET });
var response2 = tf.Client.UpdateTrigger(new UpdateTriggerRequest(Service, Function, triggerName, newHttpTriggerConfig));
replacedert.Equal(triggerName, response2.Data.TriggerName);
replacedert.Equal("", response2.Data.Description);
replacedert.Equal("http", response2.Data.TriggerType);
replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response2.Data.TriggerConfig.ToString()), newHttpTriggerConfig);
var response3 = tf.Client.GetTrigger(new GetTriggerRequest(Service, Function, triggerName));
replacedert.Equal(triggerName, response3.Data.TriggerName);
replacedert.Equal("", response3.Data.Description);
replacedert.Equal("http", response3.Data.TriggerType);
replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response3.Data.TriggerConfig.ToString()), newHttpTriggerConfig);
var response4 = tf.Client.ListTriggers(new ListTriggersRequest(Service, Function));
Console.WriteLine(response4.Content);
replacedert.Equal(1, response4.Data.Triggers.GetLength(0));
replacedert.Equal(triggerName, response4.Data.Triggers[0].TriggerName);
replacedert.Equal("", response4.Data.Triggers[0].Description);
replacedert.Equal("http", response4.Data.Triggers[0].TriggerType);
replacedert.Equal(JsonConvert.DeserializeObject<HttpTriggerConfig>(response4.Data.Triggers[0].TriggerConfig.ToString()), newHttpTriggerConfig);
var response5 = tf.Client.DeleteTrigger(new DeleteTriggerRequest(Service, Function, triggerName));
replacedert.Equal(204, response5.StatusCode);
this.Triggers.Remove(triggerName);
}
19
Source : TriggerTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestTimerTrigger()
{
tf.Client.CreateService(new CreateServiceRequest(Service));
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
tf.Client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));
string triggerName = "my-timer-trigger";
var timerTriggerConfig = new TimeTriggerConfig("@every 5m", "awesome-fc", true);
var response1 = tf.Client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "timer", "dummy_arn", "", timerTriggerConfig));
this.Triggers.Add(triggerName);
replacedert.Equal(triggerName, response1.Data.TriggerName);
replacedert.Equal("", response1.Data.Description);
replacedert.Equal("timer", response1.Data.TriggerType);
replacedert.Equal(JsonConvert.DeserializeObject<TimeTriggerConfig>(response1.Data.TriggerConfig.ToString()), timerTriggerConfig);
}
19
Source : TriggerTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestCDNEventsTrigger()
{
var client = tf.Client;
client.CreateService(new CreateServiceRequest(Service));
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));
string triggerName = "my-cdn-trigger";
var filter = new Dictionary<string, string[]>
{
{ "filter", new string[] { "www.taobao.com”,”www.tmall.com" }},
};
var cdnTriggerConfig = new CdnEventsTriggerConfig("LogFileCreated", "1.0.0", "cdn events trigger test", filter);
string sourceArn = string.Format("acs:cdn:*:{0}", tf.AccountID);
var response = client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "cdn_events",
sourceArn, tf.InvocationRole, cdnTriggerConfig, "cdn events trigger desc"));
this.Triggers.Add(triggerName);
replacedert.Equal(triggerName, response.Data.TriggerName);
replacedert.Equal("cdn events trigger desc", response.Data.Description);
replacedert.Equal("cdn_events", response.Data.TriggerType);
replacedert.Equal(sourceArn, response.Data.SourceArn);
replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
replacedert.Equal(JsonConvert.DeserializeObject<CdnEventsTriggerConfig>(response.Data.TriggerConfig.ToString()), cdnTriggerConfig);
}
19
Source : FunctionTests.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestFunctionCRUD()
{
tf.Client.CreateService(new CreateServiceRequest(Service));
string name = "test-csharp-func" + TestConfig.RandomString(8);
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
var response = tf.Client.CreateFunction(new CreateFunctionRequest(Service, name, "python3", "index.handler", code, "desc"));
//Console.WriteLine(response.Content);
replacedert.True(200 == response.StatusCode);
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(response.Data.FunctionName, name);
replacedert.Equal("python3", response.Data.Runtime);
replacedert.Equal("index.handler", response.Data.Handler);
replacedert.Equal("desc", response.Data.Description);
replacedert.True(!string.IsNullOrEmpty(response.Data.FunctionId));
replacedert.True(!string.IsNullOrEmpty(response.Data.CodeChecksum));
replacedert.True(!string.IsNullOrEmpty(response.Data.CreatedTime));
replacedert.True(!string.IsNullOrEmpty(response.Data.LastModifiedTime));
replacedert.True(response.Data.CodeSize > 0);
replacedert.True(response.Data.MemorySize == 256);
var response2 = tf.Client.GetFunction(new GetFunctionRequest(Service, name));
replacedert.Equal(response.Data.FunctionName, name);
replacedert.Equal("python3", response.Data.Runtime);
replacedert.Equal("index.handler", response.Data.Handler);
replacedert.Equal("desc", response.Data.Description);
replacedert.True(!string.IsNullOrEmpty(response.Data.FunctionId));
replacedert.True(!string.IsNullOrEmpty(response.Data.CodeChecksum));
replacedert.True(!string.IsNullOrEmpty(response.Data.CreatedTime));
replacedert.True(!string.IsNullOrEmpty(response.Data.LastModifiedTime));
replacedert.True(response.Data.CodeSize > 0);
replacedert.True(response.Data.MemorySize == 256);
var resp = tf.Client.GetFunctionCode(new GetFunctionCodeRequest(Service, name));
replacedert.False(resp.Data.Url.Contains(@"\u0026"));
var response3 = tf.Client.UpdateFunction(new UpdateFunctionRequest(Service, name, "python3", "index.handler", code, "new-desc"));
//Console.WriteLine(response3.Content);
replacedert.Equal("new-desc", response3.Data.Description);
var response4 = tf.Client.DeleteFunction(new DeleteFunctionRequest(Service, name));
replacedert.Equal(204, response4.StatusCode);
}
19
Source : TriggerTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestMNSTopicTrigger()
{
var client = tf.Client;
client.CreateService(new CreateServiceRequest(Service));
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
client.CreateFunction(new CreateFunctionRequest(Service, Function, "python3", "index.handler", code, "desc"));
string triggerName = "my-mns-trigger";
var mnsTriggerConfig = new MnsTopicTriggerConfig("JSON", "BACKOFF_RETRY", "");
string sourceArn = string.Format("acs:mns:{0}:{1}:/topics/testTopic", tf.Region, tf.AccountID);
var response = client.CreateTrigger(new CreateTriggerRequest(Service, Function, triggerName, "mns_topic",
sourceArn, tf.InvocationRole, mnsTriggerConfig, "mns trigger desc"));
this.Triggers.Add(triggerName);
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(triggerName, response.Data.TriggerName);
replacedert.Equal("mns trigger desc", response.Data.Description);
replacedert.Equal("mns_topic", response.Data.TriggerType);
replacedert.Equal(sourceArn, response.Data.SourceArn);
replacedert.Equal(tf.InvocationRole, response.Data.InvocationRole);
replacedert.Equal(JsonConvert.DeserializeObject<MnsTopicTriggerConfig>(response.Data.TriggerConfig.ToString()), mnsTriggerConfig);
}
19
Source : VersionTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestGetFunction()
{
tf.Client.CreateService(new CreateServiceRequest(Service));
string name = "test-csharp-func" + TestConfig.RandomString(8);
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
var response = tf.Client.CreateFunction(new CreateFunctionRequest(Service, name, "python3", "index.handler", code, "desc"));
replacedert.Equal(200, response.StatusCode);
var response2 = tf.Client.PublishVersion(new PublishVersionRequest(Service, "C# fc sdk 1"));
replacedert.Equal(200, response2.StatusCode);
var response3 = tf.Client.CreateAlias(new CreateAliasRequest(Service, "staging", response2.Data.VersionId, "alias desc"));
replacedert.Equal(200, response3.StatusCode);
var resp1 = tf.Client.PutProvisionConfig(new PutProvisionConfigRequest(Service, "staging", name, 10));
replacedert.Equal(200, resp1.StatusCode);
replacedert.Equal(10, resp1.Data.Target);
var resp2 = tf.Client.GetProvisionConfig(new GetProvisionConfigRequest(Service, "staging", name));
replacedert.Equal(200, resp2.StatusCode);
replacedert.Equal(10, resp2.Data.Target);
var resp3 = tf.Client.ListProvisionConfigs(new ListProvisionConfigsRequest(Service, "staging"));
replacedert.Equal(200, resp3.StatusCode);
replacedert.Equal(1, resp3.Data.ProvisionConfigs.GetLength(0));
replacedert.Equal(10, resp3.Data.ProvisionConfigs[0].Target);
replacedert.True(string.IsNullOrEmpty(resp3.Data.NextToken));
resp1 = tf.Client.PutProvisionConfig(new PutProvisionConfigRequest(Service, "staging", name, 0));
replacedert.Equal(200, resp1.StatusCode);
replacedert.Equal(0, resp1.Data.Target);
var response4 = tf.Client.GetFunction(new GetFunctionRequest(Service, name));
replacedert.Equal("desc", response4.Data.Description);
var response5 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, response2.Data.VersionId));
replacedert.Equal("desc", response5.Data.Description);
var response6 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, "staging"));
replacedert.Equal("desc", response6.Data.Description);
tf.Client.UpdateFunction(new UpdateFunctionRequest(Service, name, "python3", "index.handler", code, "new-desc"));
var response7 = tf.Client.PublishVersion(new PublishVersionRequest(Service, "C# fc sdk 2"));
tf.Client.CreateAlias(new CreateAliasRequest(Service, "prod", response7.Data.VersionId, "alias desc 2"));
var response8 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, response7.Data.VersionId));
replacedert.Equal("new-desc", response8.Data.Description);
var response9 = tf.Client.GetFunction(new GetFunctionRequest(Service, name, "prod"));
replacedert.Equal("new-desc", response9.Data.Description);
}
19
Source : VersionTest.cs
with MIT License
from aliyun
with MIT License
from aliyun
[Fact]
public void TestInvokeFunction()
{
tf.Client.CreateService(new CreateServiceRequest(Service));
string name = "test-csharp-func" + TestConfig.RandomString(8);
byte[] contents = File.ReadAllBytes(Directory.GetCurrentDirectory() + "/hello.zip");
var code = new Code(Convert.ToBase64String(contents));
tf.Client.CreateFunction(new CreateFunctionRequest(Service, name, "python3", "index.handler", code, "desc"));
byte[] hello = Encoding.UTF8.GetBytes("hello csharp world");
var response = tf.Client.InvokeFunction(new InvokeFunctionRequest(Service, name, null, hello));
replacedert.Equal("hello csharp world", response.Content);
replacedert.Equal(hello, response.Data);
var response2 = tf.Client.PublishVersion(new PublishVersionRequest(Service, "C# fc sdk 1"));
replacedert.Equal(200, response2.StatusCode);
var response3 = tf.Client.CreateAlias(new CreateAliasRequest(Service, "staging", response2.Data.VersionId, "alias desc"));
replacedert.Equal(200, response3.StatusCode);
var response4 = tf.Client.InvokeFunction(new InvokeFunctionRequest(Service, name, "staging", hello));
replacedert.Equal("hello csharp world", response4.Content);
replacedert.Equal(hello, response4.Data);
var response5 = tf.Client.InvokeFunction(new InvokeFunctionRequest(Service, name, response2.Data.VersionId, hello));
replacedert.Equal("hello csharp world", response5.Content);
replacedert.Equal(hello, response5.Data);
}
19
Source : Updater.xaml.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private async void ButtonUpdateRav1e_Click(object sender, RoutedEventArgs e)
{
ToggleAllButtons(false);
// Creates the rav1e folder if not existent
if (!Directory.Exists(Path.Combine(CurrentDir, "Apps", "rav1e")))
Directory.CreateDirectory(Path.Combine(CurrentDir, "Apps", "rav1e"));
// Downloads rav1e
await Task.Run(() => DownloadBin("https://jeremylee.sh/data/bin/rav1e.7z", Path.Combine(CurrentDir, "Apps", "rav1e.7z")));
if (File.Exists(Path.Combine(CurrentDir, "Apps", "rav1e.7z")))
{
// Extracts rav1e
ExtractFile(Path.Combine(CurrentDir, "Apps", "rav1e.7z"), Path.Combine(Directory.GetCurrentDirectory(), "Apps", "rav1e"));
// Writes the version to file
if (File.Exists(Path.Combine(CurrentDir, "Apps", "rav1e", "rav1e.exe")))
{
// Deletes txt file
if (File.Exists(Path.Combine(CurrentDir, "Apps", "rav1e", "rav1e.txt")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "rav1e", "rav1e.txt"));
}
File.WriteAllText(Path.Combine(CurrentDir, "Apps", "rav1e", "rav1e.txt"), Rav1eUpdateVersion);
}
// Deletes downloaded archive
if (File.Exists(Path.Combine(CurrentDir, "Apps", "rav1e.7z")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "rav1e.7z"));
}
CompareLocalVersion();
}
ToggleAllButtons(true);
LabelProgressBar.Dispatcher.Invoke(() => LabelProgressBar.Content = "Finished updating Rav1e");
}
19
Source : Updater.xaml.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private async void ButtonUpdateSVTAV1_Click(object sender, RoutedEventArgs e)
{
ToggleAllButtons(false);
// Creates the svt-av1 folder if not existent
if (!Directory.Exists(Path.Combine(CurrentDir, "Apps", "svt-av1")))
{
Directory.CreateDirectory(Path.Combine(CurrentDir, "Apps", "svt-av1"));
}
// Downloads rav1e
await Task.Run(() => DownloadBin("https://jeremylee.sh/data/bin/svt-av1.7z", Path.Combine(CurrentDir, "Apps", "svt-av1.7z")));
if (File.Exists(Path.Combine(CurrentDir, "Apps", "svt-av1.7z")))
{
// Extracts rav1e
ExtractFile(Path.Combine(CurrentDir, "Apps", "svt-av1.7z"), Path.Combine(Directory.GetCurrentDirectory(), "Apps", "svt-av1"));
// Writes the version to file
if (File.Exists(Path.Combine(CurrentDir, "Apps", "svt-av1", "SvtAv1EncApp.exe")))
{
// Deletes SVT-AV1 Decoder
if (File.Exists(Path.Combine(CurrentDir, "Apps", "svt-av1", "SvtAv1EncApp.exe")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "svt-av1", "SvtAv1DecApp.exe"));
}
// Deletes txt file
if (File.Exists(Path.Combine(CurrentDir, "Apps", "svt-av1", "svt-av1.txt")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "svt-av1", "svt-av1.txt"));
}
File.WriteAllText(Path.Combine(CurrentDir, "Apps", "svt-av1", "svt-av1.txt"), SVTAV1UpdateVersion);
}
// Deletes downloaded archive
if (File.Exists(Path.Combine(CurrentDir, "Apps", "svt-av1.7z")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "svt-av1.7z"));
}
CompareLocalVersion();
}
ToggleAllButtons(true);
LabelProgressBar.Dispatcher.Invoke(() => LabelProgressBar.Content = "Finished updating SVT-AV1");
}
19
Source : CheckDependencies.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
public static void Check()
{
// Sets / Checks ffmpeg Path
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "Apps", "ffmpeg", "ffmpeg.exe")))
{
Global.FFmpeg_Path = Path.Combine(Directory.GetCurrentDirectory(), "Apps", "ffmpeg");
}
else if (ExistsOnPath("ffmpeg.exe"))
{
Global.FFmpeg_Path = GetFullPathWithOutName("ffmpeg.exe");
}
else
{
Global.FFmpeg_Path = null;
}
// Sets / Checks mkvtoolnix Path
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "Apps", "mkvtoolnix", "mkvmerge.exe")))
{
Global.MKVToolNix_Path = Path.Combine(Directory.GetCurrentDirectory(), "Apps", "mkvtoolnix");
}
else if (ExistsOnPath("mkvmerge.exe"))
{
Global.MKVToolNix_Path = GetFullPathWithOutName("mkvmerge.exe");
}
else if (File.Exists(@"C:\Program Files\MKVToolNix\mkvmerge.exe"))
{
Global.MKVToolNix_Path = @"C:\Program Files\MKVToolNix\";
}
else
{
Global.MKVToolNix_Path = null;
}
// Checks if PySceneDetect is found in the Windows PATH environment
if (ExistsOnPath("scenedetect.exe")) { MainWindow.PySceneFound = true; }
NotifyUser();
}
19
Source : OpenVideoWindow.xaml.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private void ButtonProjectFile_Click(object sender, RoutedEventArgs e)
{
// OpenFileDialog for a Project File
OpenFileDialog openVideoFileDialog = new OpenFileDialog();
openVideoFileDialog.Filter = "Project File|*.xml;";
openVideoFileDialog.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Jobs");
// Avoid NULL being returned resulting in crash
Nullable<bool> result = openVideoFileDialog.ShowDialog();
if (result == true)
{
// Sets the Video Path which the main window gets
// with the function at the beginning
VideoPath = openVideoFileDialog.FileName;
ProjectFile = true;
BatchFolder = false;
QuitCorrectly = true;
// Closes the Window
this.Close();
}
}
19
Source : Settings.xaml.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private void LoadSettingsTab()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "settings.xml")))
{
string language = "English";
try
{
XmlDoreplacedent doc = new XmlDoreplacedent();
doc.Load(Path.Combine(Directory.GetCurrentDirectory(), "settings.xml"));
XmlNodeList node = doc.GetElementsByTagName("Settings");
foreach (XmlNode n in node[0].ChildNodes)
{
switch (n.Name)
{
case "DeleteTempFiles":
ToggleSwitchDeleteTempFiles.IsOn = n.InnerText == "True";
break;
case "PlaySound":
ToggleSwitchUISounds.IsOn = n.InnerText == "True";
break;
case "Logging":
ToggleSwitchLogging.IsOn = n.InnerText == "True";
break;
case "ShowDialog":
ToggleSwitchShowWindow.IsOn = n.InnerText == "True";
break;
case "Shutdown":
ToggleSwitchShutdownAfterEncode.IsOn = n.InnerText == "True";
break;
case "TempPathActive":
ToggleSwitchTempFolder.IsOn = n.InnerText == "True";
break;
case "TempPath":
TextBoxCustomTempPath.Text = n.InnerText;
break;
case "Terminal":
ToggleSwitchHideTerminal.IsOn = n.InnerText == "True";
break;
case "ThemeAccent":
ComboBoxAccentTheme.SelectedIndex = int.Parse(n.InnerText);
break;
case "ThemeBase":
ComboBoxBaseTheme.SelectedIndex = int.Parse(n.InnerText);
break;
case "BatchContainer":
ComboBoxContainerBatchEncoding.SelectedIndex = int.Parse(n.InnerText);
break;
case "SkipSubreplacedles":
ToggleSkipSubreplacedleExtraction.IsOn = n.InnerText == "True";
break;
case "Language":
language = n.InnerText;
break;
case "OverrideWorkerCount":
ToggleOverrideWorkerCount.IsOn = n.InnerText == "True";
break;
default: break;
}
}
}
catch { }
ThemeManager.Current.ChangeTheme(this, ComboBoxBaseTheme.Text + "." + ComboBoxAccentTheme.Text);
switch (language)
{
case "Deutsch":
ComboBoxUILanguage.SelectedIndex = 1;
break;
case "Français":
ComboBoxUILanguage.SelectedIndex = 2;
break;
default:
ComboBoxUILanguage.SelectedIndex = 0;
break;
}
}
}
19
Source : Settings.xaml.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
public void SaveSettingsTab()
{
try
{
if (!MainWindow.StartUp)
{
XmlWriter writer = XmlWriter.Create(Path.Combine(Directory.GetCurrentDirectory(), "settings.xml"));
writer.WriteStartElement("Settings");
writer.WriteElementString("DeleteTempFiles", ToggleSwitchDeleteTempFiles.IsOn.ToString());
writer.WriteElementString("PlaySound", ToggleSwitchUISounds.IsOn.ToString());
writer.WriteElementString("Logging", ToggleSwitchLogging.IsOn.ToString());
writer.WriteElementString("ShowDialog", ToggleSwitchShowWindow.IsOn.ToString());
writer.WriteElementString("Shutdown", ToggleSwitchShutdownAfterEncode.IsOn.ToString());
writer.WriteElementString("TempPathActive", ToggleSwitchTempFolder.IsOn.ToString());
writer.WriteElementString("TempPath", TextBoxCustomTempPath.Text);
writer.WriteElementString("Terminal", ToggleSwitchHideTerminal.IsOn.ToString());
writer.WriteElementString("ThemeAccent", ComboBoxAccentTheme.SelectedIndex.ToString());
writer.WriteElementString("ThemeBase", ComboBoxBaseTheme.SelectedIndex.ToString());
writer.WriteElementString("BatchContainer", ComboBoxContainerBatchEncoding.SelectedIndex.ToString());
writer.WriteElementString("ReencodeMessage", MainWindow.reencodeMessage.ToString());
writer.WriteElementString("Language", ComboBoxUILanguage.Text ?? "English");
writer.WriteElementString("SkipSubreplacedles", ToggleSkipSubreplacedleExtraction.IsOn.ToString());
writer.WriteElementString("OverrideWorkerCount", ToggleOverrideWorkerCount.IsOn.ToString());
writer.WriteEndElement();
writer.Close();
}
}
catch { }
}
19
Source : Updater.xaml.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private async void ButtonUpdateFFmpeg_Click(object sender, RoutedEventArgs e)
{
ToggleAllButtons(false);
// Creates the ffmpeg folder if not existent
if (!Directory.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg")))
{
Directory.CreateDirectory(Path.Combine(CurrentDir, "Apps", "ffmpeg"));
}
// Downloads ffmpeg
await Task.Run(() => DownloadBin("https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z", Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z")));
if (File.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z")))
{
// Extracts ffmpeg
ExtractFile(Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z"), Path.Combine(Directory.GetCurrentDirectory(), "Apps", "ffmpeg"));
if (File.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg", Git_FFmpeg_Name, "bin", "ffmpeg.exe")))
{
if (File.Exists(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.exe")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.txt"));
File.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.exe"));
}
File.Move(Path.Combine(CurrentDir, "Apps", "ffmpeg", Git_FFmpeg_Name, "bin", "ffmpeg.exe"), Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.exe"));
File.WriteAllText(Path.Combine(CurrentDir, "Apps", "ffmpeg", "ffmpeg.txt"), FFmpegUpdateVersion);
File.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg-git-full.7z"));
Directory.Delete(Path.Combine(CurrentDir, "Apps", "ffmpeg", Git_FFmpeg_Name), true);
CompareLocalVersion();
}
}
ToggleAllButtons(true);
LabelProgressBar.Dispatcher.Invoke(() => LabelProgressBar.Content = "Finished updating FFmpeg");
}
19
Source : Updater.xaml.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private async void ButtonUpdateAomenc_Click(object sender, RoutedEventArgs e)
{
ToggleAllButtons(false);
// Creates the aomenc folder if not existent
if (!Directory.Exists(Path.Combine(CurrentDir, "Apps", "aomenc")))
Directory.CreateDirectory(Path.Combine(CurrentDir, "Apps", "aomenc"));
// Downloads aomenc
await Task.Run(() => DownloadBin("https://jeremylee.sh/data/bin/aom.7z", Path.Combine(CurrentDir, "Apps", "aom.7z")));
if (File.Exists(Path.Combine(CurrentDir, "Apps", "aom.7z")))
{
// Extracts aomenc
ExtractFile(Path.Combine(CurrentDir, "Apps", "aom.7z"), Path.Combine(Directory.GetCurrentDirectory(), "Apps", "aomenc"));
// Writes the version to file
if (File.Exists(Path.Combine(CurrentDir, "Apps", "aomenc", "aomenc.exe")))
{
// Deletes aomdec
if (File.Exists(Path.Combine(CurrentDir, "Apps", "aomenc", "aomdec.exe")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "aomenc", "aomdec.exe"));
}
// Deletes txt file
if (File.Exists(Path.Combine(CurrentDir, "Apps", "aomenc", "aomenc.txt")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "aomenc", "aomenc.txt"));
}
File.WriteAllText(Path.Combine(CurrentDir, "Apps", "aomenc", "aomenc.txt"), AomencUpdateVersion);
}
// Deletes downloaded archive
if (File.Exists(Path.Combine(CurrentDir, "Apps", "aom.7z")))
{
File.Delete(Path.Combine(CurrentDir, "Apps", "aom.7z"));
}
CompareLocalVersion();
}
ToggleAllButtons(true);
LabelProgressBar.Dispatcher.Invoke(() => LabelProgressBar.Content = "Finished updating Aomenc");
}
19
Source : AssemblyExtensions.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static List<replacedembly> LoadAllFrom(this replacedembly replacedembly, string includedFilePattern, params string[] excludedFileNames)
{
string[] replacedemblyFiles = null;
try
{
replacedemblyFiles = Directory.GetFiles(GetExecutingreplacedemblyDirectoryName(), "ClreplacedifyBot.*.dll").ToArray();
}
catch (Exception e)
{
L.Error(e, "Exception thrown searching directory {0} for file pattern {1}.", Directory.GetCurrentDirectory(), includedFilePattern);
return null;
}
if (replacedemblyFiles == null)
{
L.Debug("No included files preplaceded to LoadAllFrom() method");
return null;
}
else
{
return LoadAllFrom(replacedembly, replacedemblyFiles, excludedFileNames);
}
}
19
Source : PythonScript.cs
with MIT License
from allisterb
with MIT License
from allisterb
public override bool Init()
{
Operation init = Begin("Initializing embedded Python interpreter");
if (PythonEngine.IsInitialized && (HomeDir != string.Empty || ModulePath != string.Empty || Args.Count > 0))
{
Error("Python engine is already initialized and cannot be initilaized with another script or aditional arguments.");
init.Cancel();
return false;
}
string originalDirectory = Directory.GetCurrentDirectory();
try
{
SetVirtualEnvDir();
SetBinDir();
if (binDir.IsNotEmpty())
{
Directory.SetCurrentDirectory(binDir);
}
SetPythonPath();
PythonEngine.Initialize(Args);
}
catch (DllNotFoundException dnfe)
{
if (HomeDir.IsEmpty())
{
Error(dnfe, $"Could not find the system-wide python36 shared library. Add Python 3.6 to your PATH environment variable or use the -P option to set the path to a Python 3.6 interpreter directory.");
}
else
{
Error(dnfe, $"Could not find python36 shared library in {HomeDir}.");
}
}
catch (Exception e)
{
Error(e, "Exception thrown initalizing Python engine.");
}
finally
{
if (Directory.GetCurrentDirectory() != originalDirectory)
{
Directory.SetCurrentDirectory(originalDirectory);
}
}
if (!PythonEngine.IsInitialized)
{
Error("Could not initalize Python engine.");
init.Cancel();
return false;
}
Info("Python version {0} from {1}.", PythonEngine.Version.Trim(), binDir.IsEmpty() ? Runtime.PythonDLL : Path.Combine(binDir, Runtime.PythonDLL.WithDllExt()));
Modules = GetModules();
Info("{0} Python modules installed.", Modules.Count(m => !m.StartsWith("__")));
HasPipModule = Modules.Contains("pip");
if (!HasPipModule)
{
Warn("Python pip module is not installed.");
}
else
{
PipModules = GetPipModules();
Info("{0} pip modules installed.", PipModules.Count);
}
foreach (string m in RequiredModules)
{
if (!Modules.Contains(m))
{
Error("Python {0} module is not installed.", m);
init.Cancel();
return false;
}
}
init.Complete();
return true;
}
19
Source : SymbolResolver.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static IntPtr LoadImage (ref string name)
{
var pathValues = Environment.GetEnvironmentVariable("PATH");
var paths = new List<string>(pathValues == null ? new string[0] :
pathValues.Split(Path.PathSeparator));
paths.Insert(0, Directory.GetCurrentDirectory());
paths.Insert(0, Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location));
foreach (var format in formats)
{
// Search the Current or specified directory for the library
string filename = string.Format(format, name);
string attempted = null;
foreach (var path in paths)
{
var fullPath = Path.Combine(path, filename);
if (File.Exists(fullPath))
{
attempted = fullPath;
break;
}
}
if (!File.Exists(attempted))
continue;
var ptr = loadImage (attempted);
if (ptr == IntPtr.Zero)
continue;
name = attempted;
return ptr;
}
return IntPtr.Zero;
}
19
Source : SeedData.cs
with MIT License
from alonsoalon
with MIT License
from alonsoalon
private void WriteSeedData(SeedDataEnreplacedy seedDataEnreplacedy)
{
//var baseDirectory = AppContext.BaseDirectory;
//var filePath = Path.Combine(baseDirectory, "SeedData.json");
var filePath = Path.Combine(Directory.GetCurrentDirectory(), _seedDataFileName);
JObject jObject = JObject.Parse(JsonConvert.SerializeObject(seedDataEnreplacedy));
File.WriteAllText(filePath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
}
19
Source : SeedData.cs
with MIT License
from alonsoalon
with MIT License
from alonsoalon
public SeedDataEnreplacedy GetSeedData()
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"SeedData.json");
var jsonData = ReadFile(filePath);
var data = JsonConvert.DeserializeObject<SeedDataEnreplacedy>(jsonData);
return data;
}
19
Source : SeedData.cs
with MIT License
from alonsoalon
with MIT License
from alonsoalon
private void WriteSeedData(SeedDataEnreplacedy seedDataEnreplacedy)
{
//var baseDirectory = AppContext.BaseDirectory;
//var filePath = Path.Combine(baseDirectory, "SeedData.json");
var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"SeedData.json");
JObject jObject = JObject.Parse(JsonConvert.SerializeObject(seedDataEnreplacedy));
File.WriteAllText(filePath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
}
19
Source : SecretsLocalAppSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public async Task<byte[]> GetCertificateAsync(string certificateId)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), @"secrets.json");
if (File.Exists(path))
{
string jsonString = File.ReadAllText(path);
JObject keyVault = JObject.Parse(jsonString);
keyVault.TryGetValue(certificateId, out JToken token);
if (token != null)
{
byte[] localCertBytes = Convert.FromBase64String(token.ToString());
return await Task.FromResult(localCertBytes);
}
}
return null;
}
19
Source : SecretsLocalAppSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public async Task<JsonWebKey> GetKeyAsync(string keyId)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), @"secrets.json");
if (File.Exists(path))
{
JObject keyVault = JObject.Parse(File.ReadAllText(path));
keyVault.TryGetValue(keyId, out JToken token);
if (token != null)
{
JsonWebKey key = JsonSerializer.Deserialize<JsonWebKey>(token.ToString());
return await Task.FromResult(key);
}
}
return null;
}
19
Source : SecretsLocalAppSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public async Task<string> GetSecretAsync(string secretId)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), @"secrets.json");
if (File.Exists(path))
{
string jsonString = File.ReadAllText(path);
JObject keyVault = JObject.Parse(jsonString);
keyVault.TryGetValue(secretId, out JToken token);
return token != null ? token.ToString() : string.Empty;
}
return await Task.FromResult(string.Empty);
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation("Program // CreateWebHostBuilder");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
config.SetBasePath(basePath);
config.AddJsonFile(basePath + "altinn-appsettings/altinn-dbsettings-secret.json", optional: true, reloadOnChange: true);
if (basePath == "/")
{
config.AddJsonFile(basePath + "app/appsettings.json", optional: false, reloadOnChange: true);
}
else
{
config.AddJsonFile(Directory.GetCurrentDirectory() + "/appsettings.json", optional: false, reloadOnChange: true);
}
ConnectToKeyVaultAndSetApplicationInsights(config);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseStartup<Startup>();
19
Source : SigningCredentialsResolver.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public SigningCredentials GetSigningCredentials()
{
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string certPath = basePath + $"{_accessTokenSettings.AccessTokenSigningKeysFolder}{_accessTokenSettings.AccessTokenSigningCertificateFileName}";
X509Certificate2 cert = new X509Certificate2(certPath);
return new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256);
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation($"Program // ConfigureAppConfiguration");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string basePathCurrentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory is: {basePathCurrentDirectory}");
LoadConfigurationSettings(config, basePath, args);
})
.UseStartup<Startup>();
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
});
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static void LoadConfigurationSettings(IConfigurationBuilder config, string basePath, string[] args)
{
_logger.LogInformation($"Program // Loading Configuration from basePath={basePath}");
config.SetBasePath(basePath);
string configJsonFile1 = $"{basePath}/altinn-appsettings/altinn-dbsettings-secret.json";
string configJsonFile2 = $"{Directory.GetCurrentDirectory()}/appsettings.json";
if (basePath == "/")
{
configJsonFile2 = "/app/appsettings.json";
}
_logger.LogInformation($"Loading configuration file: '{configJsonFile1}'");
config.AddJsonFile(configJsonFile1, optional: true, reloadOnChange: true);
_logger.LogInformation($"Loading configuration file2: '{configJsonFile2}'");
config.AddJsonFile(configJsonFile2, optional: false, reloadOnChange: true);
config.AddEnvironmentVariables();
ConnectToKeyVaultAndSetApplicationInsights(config);
config.AddCommandLine(args);
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string basePathCurrentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory is: {basePathCurrentDirectory}");
LoadConfigurationSettings(config, basePath, args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseStartup<Startup>();
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static void LoadConfigurationSettings(IConfigurationBuilder config, string basePath, string[] args)
{
_logger.LogInformation($"Program // Loading Configuration from basePath={basePath}");
config.SetBasePath(basePath);
string configJsonFile1 = $"{basePath}/altinn-appsettings/altinn-dbsettings-secret.json";
string configJsonFile2 = Directory.GetCurrentDirectory() + "/appsettings.json";
if (basePath == "/")
{
configJsonFile2 = "/app/appsettings.json";
}
_logger.LogInformation($"Loading configuration file: '{configJsonFile1}'");
config.AddJsonFile(configJsonFile1, optional: true, reloadOnChange: true);
_logger.LogInformation($"Loading configuration file2: '{configJsonFile2}'");
config.AddJsonFile(configJsonFile2, optional: false, reloadOnChange: true);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
ConnectToKeyVaultAndSetApplicationInsights(config);
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation("Program // CreateWebHostBuilder");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
config.SetBasePath(basePath);
config.AddJsonFile(basePath + "altinn-appsettings/altinn-dbsettings-secret.json", optional: true, reloadOnChange: true);
if (basePath == "/")
{
config.AddJsonFile(basePath + "app/appsettings.json", optional: false, reloadOnChange: true);
}
else
{
config.AddJsonFile(Directory.GetCurrentDirectory() + "/appsettings.json", optional: false, reloadOnChange: true);
}
config.AddEnvironmentVariables();
ConnectToKeyVaultAndSetApplicationInsights(config);
config.AddCommandLine(args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseUrls("http://*:5020")
.UseStartup<Startup>();
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static void LoadConfigurationSettings(IConfigurationBuilder config, string basePath, string[] args)
{
_logger.LogInformation($"Program // Loading Configuration from basePath={basePath}");
config.SetBasePath(basePath);
string configJsonFile1 = $"{basePath}/altinn-appsettings/altinn-dbsettings-secret.json";
string configJsonFile2 = $"{Directory.GetCurrentDirectory()}/appsettings.json";
if (basePath == "/")
{
configJsonFile2 = "/app/appsettings.json";
}
_logger.LogInformation($"Loading configuration file: '{configJsonFile1}'");
config.AddJsonFile(configJsonFile1, optional: true, reloadOnChange: true);
_logger.LogInformation($"Loading configuration file2: '{configJsonFile2}'");
config.AddJsonFile(configJsonFile2, optional: false, reloadOnChange: true);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
ConnectToKeyVaultAndSetApplicationInsights(config);
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation("Program // (ConfigureAppConfiguration");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string basePathCurrentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory is: {basePathCurrentDirectory}");
LoadConfigurationSettings(config, basePath, args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseStartup<Startup>();
19
Source : OrganizationsControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private HttpClient GetTestClient(IOrganizations organizationsService)
{
Program.ConfigureSetupLogging();
string projectDir = Directory.GetCurrentDirectory();
string configPath = Path.Combine(projectDir, "appsettings.json");
HttpClient client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddSingleton(organizationsService);
// Set up mock authentication so that not well known endpoint is used
services.AddSingleton<IPostConfigureOptions<JwtCookieOptions>, JwtCookiePostConfigureOptionsStub>();
services.AddSingleton<ISigningKeysResolver, SigningKeyResolverMock>();
});
builder.ConfigureAppConfiguration((context, conf) => { conf.AddJsonFile(configPath); });
}).CreateClient();
return client;
}
19
Source : ReceiptControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private HttpClient GetTestClient(Mock<IRegister> registerMock, Mock<IStorage> storageMock, Mock<IProfile> profileMock)
{
string projectDir = Directory.GetCurrentDirectory();
string configPath = Path.Combine($"{projectDir}", "appsettings.json");
Program.ConfigureSetupLogging();
HttpClient client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddSingleton(registerMock.Object);
services.AddSingleton(storageMock.Object);
services.AddSingleton(profileMock.Object);
services
.AddSingleton<IPostConfigureOptions<JwtCookieOptions>, JwtCookiePostConfigureOptionsStub>();
}).ConfigureAppConfiguration((context, conf) => { conf.AddJsonFile(configPath); });
}).CreateClient();
return client;
}
19
Source : PartiesControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private HttpClient GetTestClient(IParties partiesService)
{
Program.ConfigureSetupLogging();
string projectDir = Directory.GetCurrentDirectory();
string configPath = Path.Combine(projectDir, "appsettings.json");
HttpClient client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddSingleton(partiesService);
// Set up mock authentication so that not well known endpoint is used
services.AddSingleton<IPostConfigureOptions<JwtCookieOptions>, JwtCookiePostConfigureOptionsStub>();
services.AddSingleton<ISigningKeysResolver, SigningKeyResolverMock>();
services.AddSingleton<IAuthorization, AuthorizationWrapperMock>();
});
builder.ConfigureAppConfiguration((context, conf) => { conf.AddJsonFile(configPath); });
}).CreateClient();
return client;
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static void LoadAppSettingsFiles(IConfigurationBuilder config)
{
_logger.LogInformation("Program // LoadAppSettingsFiles");
string currentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory: {currentDirectory}");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
config.SetBasePath(basePath);
config.AddJsonFile(basePath + @"altinn-appsettings/altinn-dbsettings-secret.json", true, true);
if (basePath == "/")
{
// On a pod/container where the app is located in an app folder on the root of the filesystem.
string filePath = basePath + @"app/appsettings.json";
_logger.LogInformation($"Loading configuration file: {filePath}");
config.AddJsonFile(filePath, false, true);
}
else
{
// Running on development machine.
string filePath = Directory.GetCurrentDirectory() + @"/appsettings.json";
_logger.LogInformation($"Loading configuration file: {filePath}");
config.AddJsonFile(filePath, false, true);
}
}
19
Source : LanguageController.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[HttpGet]
public IActionResult GetLanguageAsJSON(string languageCode)
{
FileIniDataParser parser = new FileIniDataParser();
Dictionary<string, Dictionary<string, string>> outerDict = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> objDict = new Dictionary<string, string>();
string currentDirectory = Directory.GetCurrentDirectory();
string filePath = string.Empty;
if (Environment.GetEnvironmentVariable("GeneralSettings__LanguageFilesLocation") != null)
{
filePath = Path.Combine(currentDirectory, $"{Environment.GetEnvironmentVariable("GeneralSettings__LanguageFilesLocation")}{languageCode}.ini");
}
else
{
filePath = Path.Combine(currentDirectory, $"{_generalSettings.LanguageFilesLocation}{languageCode}.ini");
}
var watch = System.Diagnostics.Stopwatch.StartNew();
IniData parsedData = parser.ReadFile(filePath, Encoding.UTF8);
watch.Stop();
_logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "read inifile - {0} ", watch.ElapsedMilliseconds);
watch = System.Diagnostics.Stopwatch.StartNew();
// Iterate through all the sections
foreach (SectionData section in parsedData.Sections)
{
// Iterate through all the keys in the current section
// printing the values
foreach (KeyData key in section.Keys)
{
objDict.Add(key.KeyName, key.Value);
}
outerDict.Add(section.SectionName, objDict);
objDict = new Dictionary<string, string>();
}
watch.Stop();
_logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "parse inifile - {0} ", watch.ElapsedMilliseconds);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(outerDict);
return Content(json, "application/json", Encoding.UTF8);
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("altinn-appsettings/altinn-appsettings-secret.json", optional: true, reloadOnChange: true);
IWebHostEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
string envName = hostingEnvironment.EnvironmentName;
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
IConfiguration stageOneConfig = config.Build();
string appId = stageOneConfig.GetValue<string>("KvSetting:ClientId");
string tenantId = stageOneConfig.GetValue<string>("KvSetting:TenantId");
string appKey = stageOneConfig.GetValue<string>("KvSetting:ClientSecret");
string keyVaultEndpoint = stageOneConfig.GetValue<string>("KvSetting:SecretUri");
if (!string.IsNullOrEmpty(appId) && !string.IsNullOrEmpty(tenantId)
&& !string.IsNullOrEmpty(appKey) && !string.IsNullOrEmpty(keyVaultEndpoint))
{
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider($"RunAs=App;AppId={appId};TenantId={tenantId};AppKey={appKey}");
KeyVaultClient keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
config.AddAzureKeyVault(
keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
try
{
string secretId = "ApplicationInsights--InstrumentationKey";
SecretBundle secretBundle = keyVaultClient.GetSecretAsync(
keyVaultEndpoint, secretId).Result;
Startup.ApplicationInsightsKey = secretBundle.Value;
}
catch (Exception vaultException)
{
_logger.LogError($"Could not find secretBundle for application insights {vaultException}");
}
}
if (hostingEnvironment.IsDevelopment() && !Directory.GetCurrentDirectory().Contains("app"))
{
config.AddJsonFile(Directory.GetCurrentDirectory() + $"/appsettings.{envName}.json", optional: true, reloadOnChange: true);
replacedembly replacedembly = replacedembly.Load(new replacedemblyName(hostingEnvironment.ApplicationName));
if (replacedembly != null)
{
config.AddUserSecrets(replacedembly, true);
}
}
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
}).UseStartup<Startup>()
.CaptureStartupErrors(true);
19
Source : OWMLTests.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
private string GetSolutionPath() =>
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.FullName;
19
Source : XAudio2Native.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
private static IntPtr LoadXAudioLibrary()
{
#if NETCOREAPP3_0_OR_GREATER
IntPtr libraryHandle;
if(NativeLibrary.TryLoad("xaudio2_9.dll", out libraryHandle))
{
return libraryHandle;
}
else if(NativeLibrary.TryLoad("xaudio2_9redist.dll", out libraryHandle))
{
return libraryHandle;
}
return IntPtr.Zero;
#else
string libraryPath = GetLibraryPath("xaudio2_9.dll");
IntPtr handle = Win32.LoadLibrary(libraryPath);
if (handle == IntPtr.Zero)
{
libraryPath = GetLibraryPath("xaudio2_9redist.dll");
handle = Win32.LoadLibrary(libraryPath);
if (handle == IntPtr.Zero)
{
throw new DllNotFoundException("Unable to load xaudio2_9.dll or xaudio2_9redist.dll library.");
}
}
return handle;
static string GetLibraryPath(string libraryName)
{
bool isArm = RuntimeInformation.ProcessArchitecture == Architecture.Arm || RuntimeInformation.ProcessArchitecture == Architecture.Arm64;
var arch = Environment.Is64BitProcess
? isArm ? "arm64" : "x64"
: isArm ? "arm" : "x86";
// 1. try alongside managed replacedembly
var path = typeof(XAudio2Native).replacedembly.Location;
if (!string.IsNullOrEmpty(path))
{
path = Path.GetDirectoryName(path);
// 1.1 in platform sub dir
var lib = Path.Combine(path, arch, libraryName);
if (File.Exists(lib))
return lib;
// 1.2 in root
lib = Path.Combine(path, libraryName);
if (File.Exists(lib))
return lib;
}
// 2. try current directory
path = Directory.GetCurrentDirectory();
if (!string.IsNullOrEmpty(path))
{
// 2.1 in platform sub dir
var lib = Path.Combine(path, arch, libraryName);
if (File.Exists(lib))
return lib;
// 2.2 in root
lib = Path.Combine(lib, libraryName);
if (File.Exists(lib))
return lib;
}
// 3. try app domain
try
{
if (AppDomain.CurrentDomain is AppDomain domain)
{
// 3.1 RelativeSearchPath
path = domain.RelativeSearchPath;
if (!string.IsNullOrEmpty(path))
{
// 3.1.1 in platform sub dir
var lib = Path.Combine(path, arch, libraryName);
if (File.Exists(lib))
return lib;
// 3.1.2 in root
lib = Path.Combine(lib, libraryName);
if (File.Exists(lib))
return lib;
}
// 3.2 BaseDirectory
path = domain.BaseDirectory;
if (!string.IsNullOrEmpty(path))
{
// 3.2.1 in platform sub dir
string? lib = Path.Combine(path, arch, libraryName);
if (File.Exists(lib))
return lib;
// 3.2.2 in root
lib = Path.Combine(lib, libraryName);
if (File.Exists(lib))
return lib;
}
}
}
catch
{
// no-op as there may not be any domain or path
}
// 4. use PATH or default loading mechanism
return libraryName;
}
#endif
}
19
Source : Logger.cs
with MIT License
from AmigoCap
with MIT License
from AmigoCap
void Start() {
DateTime now = DateTime.Now;
string dir = "ReViVD Output/" + now.Day.ToString("00") + '-' + now.Month.ToString("00") + '-' + now.Year.ToString().Substring(2, 2) + "_" + now.Hour.ToString("00") + 'h' + now.Minute.ToString("00");
Directory.CreateDirectory(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), dir));
dirname = new FileInfo(dir).FullName;
nfi.NumberDecimalSeparator = ".";
InvokeRepeating("LogPosition", 0, 0.5f);
}
19
Source : Program.cs
with MIT License
from amolines
with MIT License
from amolines
static void Main(string[] args)
{
var environmentName = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", true, true)
.AddJsonFile($"appsettings.{environmentName}.json", true, true)
.AddEnvironmentVariables();
var configuration = builder.Build();
var connectionStringSection = configuration.GetSection("connectionString");
var unitOfWorkConnection = connectionStringSection.Get<MySqlConnection>();
var unitOfWorkFactory = new MySqlUnitOfWorkFactory(unitOfWorkConnection);
var messageBroker = new QueryMessageBroker(unitOfWorkFactory,
(unitOfWork, contentType) =>
new VersionService(new MySqlVersionRepository(unitOfWork, contentType)));
messageBroker.Bind<ProductCreateQueryMessageFilter>();
messageBroker.Bind<ClientCreateQueryMessageFilter>();
messageBroker.Bind<AccountCreateQueryMessageFilter>();
messageBroker.Bind<AccountUpdateQueryMessageFilter>();
messageBroker.Bind<ClientUpdateQueryMessageFilter>();
messageBroker.Bind<AccountActivateQueryMessageFilter>();
var rabbitConnectionStringSection = configuration.GetSection("rabbitConnectionString");
var rabbitMqConnectionString = rabbitConnectionStringSection.Get<RabbitMqConnectionString>();
var eventBus = new RabbitMqEventBus(rabbitMqConnectionString);
eventBus.Subscribe("ProductCreated", ProductCreatedEventConsumer.ConsumerFactory(messageBroker));
eventBus.Subscribe("ClientCreated", ClientCreatedEventConsumer.ConsumerFactory(messageBroker));
eventBus.Subscribe("ClientUpdated", ClientUpdatedEventConsumer.ConsumerFactory(messageBroker));
eventBus.Subscribe("AccountCreated", AccountCreatedEventConsumer.ConsumerFactory(messageBroker));
eventBus.Subscribe("AccountBalanceChanged", AccountBalanceChangedEventConsumer.ConsumerFactory(messageBroker));
eventBus.Subscribe("AccountTransfered", AccountTransferedEventConsumer.ConsumerFactory(messageBroker));
eventBus.Subscribe("AccountActivated", AccountActivatedEventConsumer.ConsumerFactory(messageBroker));
}
19
Source : Program.cs
with MIT License
from Aminator
with MIT License
from Aminator
private async void OnMyFormLoad(object? sender, EventArgs e)
{
StorageFolder rootFolder = await StorageFolder.GetFolderFromPathAsync(Directory.GetCurrentDirectory());
MyGame game = new MyGame(new WinFormsGameContext(this) { FileProvider = new FileSystemProvider(rootFolder) });
game.Run();
}
19
Source : Program.cs
with MIT License
from amoraitis
with MIT License
from amoraitis
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args)
.ConfigureAppConfiguration((hc, config) =>
{
var env = hc.HostingEnvironment;
config.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
})
.ConfigureLogging((hc, logging) =>
{
logging.AddConfiguration(hc.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
})
.Build();
InitializeDatabase(host);
host.Run();
}
19
Source : MovieRenamerService.cs
with MIT License
from amoscardino
with MIT License
from amoscardino
public async Task RenameAsync(string inputPath, string outputPath, bool skipConfirmation, bool verbose)
{
_verbose = verbose;
inputPath = Path.GetFullPath(inputPath ?? Directory.GetCurrentDirectory());
outputPath = Path.GetFullPath(outputPath ?? inputPath);
if (!File.GetAttributes(inputPath).HasFlag(FileAttributes.Directory))
{
_console.WriteLine("Input path must be a directory, not a file.");
return;
}
if (_verbose)
{
_console.WriteLine($"* Using Input Path: {inputPath}");
_console.WriteLine($"* Using Output Path: {outputPath}");
_console.WriteLine();
}
var files = _fileService.GetFiles(inputPath);
if (!files.Any())
return;
await MatchFilesAsync(files, outputPath);
var anyToRename = files.Any(match => !match.NewPath.IsNullOrWhiteSpace());
if (anyToRename && (skipConfirmation || Prompt.GetYesNo("Look good?", true)))
_fileService.RenameFiles(files);
else
_console.WriteLine("Nothing has been changed.");
}
19
Source : ShowRenamerService.cs
with MIT License
from amoscardino
with MIT License
from amoscardino
public async Task RenameAsync(string inputPath, string outputPath, bool filesOnly, bool recurse, bool skipConfirmation, bool verbose)
{
_verbose = verbose;
inputPath = Path.GetFullPath(inputPath ?? Directory.GetCurrentDirectory());
outputPath = Path.GetFullPath(outputPath ?? inputPath);
if (!File.GetAttributes(inputPath).HasFlag(FileAttributes.Directory))
{
_console.WriteLine("Input path must be a directory, not a file.");
return;
}
if (_verbose)
{
_console.WriteLine($"* Using Input Path: {inputPath}");
_console.WriteLine($"* Using Output Path: {outputPath}");
_console.WriteLine();
}
var files = _fileService.GetFiles(inputPath, recurse);
if (!files.Any())
return;
await MatchFilesAsync(files, outputPath, filesOnly);
var anyToRename = files.Any(match => !match.NewPath.IsNullOrWhiteSpace());
if (anyToRename && (skipConfirmation || Prompt.GetYesNo("Look good?", true)))
_fileService.RenameFiles(files);
else
_console.WriteLine("Nothing has been changed.");
}
19
Source : Program.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
void run() {
Console.replacedle = "Ch_05_Clreplaced_Activation_Heatmaps";
var text = System.IO.File.ReadAllText("imagenet_clreplaced_index.json");
var imagenetInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(text);
var imagePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), imageName);
var pathToVGG16model = VGG16.download_model_if_needed();
var image = new float[224 * 224 * 3];
CPPUtil.load_image(imagePath, image);
int num_clreplacedes = 1000;
var predictions = new float[num_clreplacedes];
CPPUtil.evaluate_vgg16(pathToVGG16model, imagePath, predictions, num_clreplacedes);
var indices = Enumerable.Range(0, num_clreplacedes).ToArray<int>();
var floatComparer = Comparer<float>.Default;
Array.Sort(indices, (a, b) => floatComparer.Compare(predictions[b], predictions[a]));
Console.WriteLine("Predictions:");
for (int i=0; i<3; i++) {
var imagenetClreplaced = imagenetInfo[indices[i]];
var imagenetClreplacedName = imagenetClreplaced[1];
var predicted_score = predictions[indices[i]];
Console.WriteLine($"\t({imagenetClreplacedName} -> {predicted_score:f3})");
}
var imageWithHeatMap = new float[image.Length];
CPPUtil.visualize_heatmap(pathToVGG16model, imagePath, "conv5_3", 386, imageWithHeatMap);
var app = new System.Windows.Application();
var window = new PlotWindowBitMap("Original Image", image, 224, 224, 3);
window.Show();
var windowHeat = new PlotWindowBitMap("Clreplaced Activation Heatmap [386]", imageWithHeatMap, 224, 224, 3);
windowHeat.Show();
app.Run();
}
See More Examples