Here are the examples of the csharp api System.Guid.ToString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2074 Examples
19
Source : TempTableData.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static string GenerateName() => $"t{Guid.NewGuid().ToString("N")}";
19
Source : TableColumn.Types.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public override string Readreplacedtring(ISqDataRecordReader recordReader)
=> this.ReadNullable(recordReader)?.ToString("D")
?? throw new SqExpressException($"Null value is not expected in non nullable column '{this.ColumnName.Name}'");
19
Source : TableColumn.Types.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public override string? Readreplacedtring(ISqDataRecordReader recordReader) => this.Read(recordReader)?.ToString("D");
19
Source : ExprPlainWriter.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public void VisitPlainProperty(string name, Guid? value, int ctx)
{
this._buffer.Add(this._factory(ctx, ctx, null, false, name, value?.ToString("D")));
}
19
Source : ExprXmlWriter.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public void VisitPlainProperty(string name, Guid? value, XmlWriter writer)
{
if (value == null)
{
return;
}
writer.WriteStartElement(name);
writer.WriteValue(value.Value.ToString("D"));
writer.WriteEndElement();
}
19
Source : TableColumnsTest.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
[Test]
public void TestGuid()
{
replacedert.AreEqual(SqQueryBuilder.SqlType.Guid, this.Table.ColGuid.SqlType);
replacedert.AreEqual("[AT].[ColGuid]", this.Table.ColGuid.ToSql());
replacedert.IsFalse(this.Table.ColGuid.IsNullable);
DerivedTable dt = new DerivedTable();
var customColumn = this.Table.ColGuid.AddToDerivedTable(dt);
replacedert.AreEqual(this.Table.ColGuid.ColumnName, customColumn.ColumnName);
replacedert.IsTrue(dt.Columns.Contains(customColumn));
var customColumn2 = this.Table.ColGuid.ToCustomColumn(this.NewSource);
replacedert.AreEqual(this.Table.ColGuid.ColumnName, customColumn2.ColumnName);
var reader = new Mock<ISqDataRecordReader>();
this.Table.ColGuid.Read(reader.Object);
customColumn.Read(reader.Object);
reader.Verify(r => r.GetGuid(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));
var guid = new Guid("3E0F7FA1-E7CA-4F6E-BF19-69C398565EA2");
var guidString = guid.ToString("D");
replacedert.Throws<SqExpressException>(() => this.Table.ColGuid.Readreplacedtring(reader.Object));
reader.Setup(r => r.GetNullableGuid(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(guid);
replacedert.AreEqual(guidString, this.Table.ColGuid.Readreplacedtring(reader.Object));
replacedert.AreEqual($"'{guidString}'", this.Table.ColGuid.FromString(guidString).ToSql());
replacedert.Throws<SqExpressException>(() => this.Table.ColGuid.FromString(null));
}
19
Source : TableColumnsTest.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
[Test]
public void TestNullableGuid()
{
replacedert.AreEqual(SqQueryBuilder.SqlType.Guid, this.Table.ColNullableGuid.SqlType);
replacedert.AreEqual("[AT].[ColNullableGuid]", this.Table.ColNullableGuid.ToSql());
replacedert.IsTrue(this.Table.ColNullableGuid.IsNullable);
DerivedTable dt = new DerivedTable();
var customColumn = this.Table.ColNullableGuid.AddToDerivedTable(dt);
replacedert.AreEqual(this.Table.ColNullableGuid.ColumnName, customColumn.ColumnName);
replacedert.IsTrue(dt.Columns.Contains(customColumn));
var customColumn2 = this.Table.ColNullableGuid.ToCustomColumn(this.NewSource);
replacedert.AreEqual(this.Table.ColNullableGuid.ColumnName, customColumn2.ColumnName);
var reader = new Mock<ISqDataRecordReader>();
this.Table.ColNullableGuid.Read(reader.Object);
customColumn.Read(reader.Object);
reader.Verify(r => r.GetNullableGuid(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));
var guid = new Guid("3E0F7FA1-E7CA-4F6E-BF19-69C398565EA2");
var guidString = guid.ToString("D");
replacedert.IsNull(this.Table.ColNullableGuid.Readreplacedtring(reader.Object));
reader.Setup(r => r.GetNullableGuid(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(guid);
replacedert.AreEqual(guidString, this.Table.ColNullableGuid.Readreplacedtring(reader.Object));
replacedert.AreEqual($"'{guidString}'", this.Table.ColNullableGuid.FromString(guidString).ToSql());
replacedert.AreEqual("NULL", this.Table.ColNullableGuid.FromString(null).ToSql());
}
19
Source : IClient.Default.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task<IServiceResult> SendAsync(IInvokeMessage message)
{
var transportMessage = new TransportMessage<IInvokeMessage>
{
Id = Guid.NewGuid().ToString("N"),
Body = message
};
if (Logger.IsEnabled(LogLevel.Trace))
Logger.LogTrace($"Sending message to node {Node}:\nMessage id:{transportMessage.Id}\nArgs:{Codec.ToJson(message.Args)}\n\n");
var tcs = new TaskCompletionSource<IServiceResult>(TaskCreationOptions.RunContinuationsAsynchronously);
using (var ct = new CancellationTokenSource(UraganoOptions.Remoting_Invoke_CancellationTokenSource_Timeout.Value))
{
ct.Token.Register(() =>
{
tcs.TrySetResult(new ServiceResult("Remoting invoke timeout!", RemotingStatus.Timeout));
Logger.LogWarning("Remoting invoke timeout,You can set the wait time with the Remoting_Invoke_CancellationTokenSource_Timeout option.\nSend to node:{1}\nMessage id:{0}\n\n", transportMessage.Id, Node);
}, false);
if (!_resultCallbackTask.TryAdd(transportMessage.Id, tcs)) throw new Exception("Failed to send.");
try
{
await Channel.WriteAndFlushAsync(transportMessage);
if (Logger.IsEnabled(LogLevel.Trace))
Logger.LogTrace($"Send completed, waiting for node {Node} to return results:\nMessage id:{transportMessage.Id}\n\n");
var result = await tcs.Task;
if (Logger.IsEnabled(LogLevel.Trace))
Logger.LogTrace($"The client received the return result of node {Node}:\nMessage id:{transportMessage.Id}\nBody:{Codec.ToJson(result)}\n\n");
return result;
}
finally
{
_resultCallbackTask.TryRemove(transportMessage.Id, out var t);
t?.TrySetCanceled();
}
}
}
19
Source : DbQuery.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private string ResolveUpdate()
{
var table = GetTableMetaInfo().TableName;
var builder = new StringBuilder();
if (_setExpressions.Count > 0)
{
var where = ResolveWhere();
foreach (var item in _setExpressions)
{
var column = new BooleanExpressionResovle(item.Column).Resovle();
var expression = new BooleanExpressionResovle(item.Expression, _parameters).Resovle();
builder.Append($"{column} = {expression},");
}
var sql = $"UPDATE {table} SET {builder.ToString().Trim(',')}{where}";
return sql;
}
else
{
var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
var where = ResolveWhere();
var columns = GetColumnMetaInfos();
var updcolumns = columns
.Where(a => !filters.Contains(a.ColumnName))
.Where(a => !a.IsComplexType)
.Where(a => !a.IsIdenreplacedy && !a.IsPrimaryKey && !a.IsNotMapped)
.Where(a => !a.IsConcurrencyCheck)
.Select(s => $"{s.ColumnName} = @{s.CsharpName}");
if (string.IsNullOrEmpty(where))
{
var primaryKey = columns.Where(a => a.IsPrimaryKey).FirstOrDefault()
?? columns.First();
where = $" WHERE {primaryKey.ColumnName} = @{primaryKey.CsharpName}";
if (columns.Exists(a => a.IsConcurrencyCheck))
{
var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
where += $" AND {checkColumn.ColumnName} = @{checkColumn.CsharpName}";
}
}
var sql = $"UPDATE {table} SET {string.Join(",", updcolumns)}";
if (columns.Exists(a => a.IsConcurrencyCheck))
{
var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
sql += $",{checkColumn.ColumnName} = @New{checkColumn.CsharpName}";
if (checkColumn.CsharpType.IsValueType)
{
var version = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
_parameters.Add($"New{checkColumn.CsharpName}", version);
}
else
{
var version = Guid.NewGuid().ToString("N");
_parameters.Add($"New{checkColumn.CsharpName}", version);
}
}
sql += where;
return sql;
}
}
19
Source : DotNetToJScript.cs
with MIT License
from 1y0n
with MIT License
from 1y0n
static string CreateScriptlet(string script, string script_name, bool register_script, Guid clsid)
{
XmlDoreplacedent doc = new XmlDoreplacedent();
doc.LoadXml(Global_Var.scriptlet_template);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;
settings.Encoding = new UTF8Encoding(false);
XmlElement reg_node = (XmlElement)doc.SelectSingleNode("/package/component/registration");
XmlNode root_node = register_script ? reg_node : doc.SelectSingleNode("/package/component");
XmlNode script_node = root_node.AppendChild(doc.CreateElement("script"));
script_node.Attributes.Append(doc.CreateAttribute("language")).Value = script_name;
script_node.AppendChild(doc.CreateCDataSection(script));
if (clsid != Guid.Empty)
{
reg_node.SetAttribute("clreplacedid", clsid.ToString("B"));
}
using (MemoryStream stm = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(stm, settings))
{
doc.Save(writer);
}
return Encoding.UTF8.GetString(stm.ToArray());
}
}
19
Source : ConditionTaskForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void button2_Click(object sender, EventArgs e)
{
string name = task_name.Text;
int count = customShellListView.Items.Count;
Object item1 = scb_condition1.SelectedItem;
Object item2 = scb_condition2.SelectedItem;
Object item3 = scb_condition3.SelectedItem;
if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show(this, "请输入任务名称");
task_name.Focus();
}
else if (item1 == null)
{
MessageBox.Show(this, "请至少选择一个条件");
}
else if (count == 0)
{
MessageBox.Show(this, "请添加任务指令脚本(Shell)");
shell_name.Focus();
}
else
{
string condition = "";
ConditionItem ci1 = (ConditionItem)item1;
condition += gereplacedemUuid(ci1) + "," + (scb_status1.SelectedIndex == 1 ? "Y" : "N");
if(item2 != null){
ConditionItem ci2 = (ConditionItem)item2;
condition += gereplacedemCondi(1) + gereplacedemUuid(ci2) + "," + (scb_status2.SelectedIndex == 1 ? "Y" : "N");
if (item3 != null)
{
ConditionItem ci3 = (ConditionItem)item2;
condition += gereplacedemCondi(2) + gereplacedemUuid(ci3) + "," + (scb_status3.SelectedIndex == 1 ? "Y" : "N");
}
}
ListView.ListViewItemCollection coll = customShellListView.Items;
if (null == cmdShell)
{
cmdShell = new CmdShell();
cmdShell.Uuid = Guid.NewGuid().ToString("N");
}
JObject obj = null;
JArray list = new JArray();
List<TaskShell> shellList = new List<TaskShell>();
TaskShell task = null;
cmdShell.Name = name;
cmdShell.TaskType = TaskType.Condition;
cmdShell.Condition = condition;
cmdShell.Type = "条件任务";
foreach(ListViewItem item in coll){
obj = (JObject)item.Tag;
task = new TaskShell();
task.Uuid = Guid.NewGuid().ToString("N");
task.Shell = obj["code"].ToString();
task.Name = obj["name"].ToString();
shellList.Add(task);
}
cmdShell.ShellList = shellList;
if (null != this.callback)
{
this.callback(cmdShell);
}
this.Close();
}
}
19
Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void button1_Click(object sender, EventArgs e)
{
int index = tabControl1.SelectedIndex;
bool isnew = false;
if (monitorConfig == null)
{
isnew = true;
}
else
{
index = tabIndex;
}
if (index == 0)
{ // springboot
SpringBootMonitorItem item = new SpringBootMonitorItem();
item.AppName = stb_app_name.Text;
item.BuildFileName = stb_build_file.Text;
item.CrlFileName = stb_ctl_file.Text;
item.ShFileDir = stb_sh_dir.Text;
if (item.ShFileDir.EndsWith("/"))
{
item.ShFileDir = item.ShFileDir.Substring(0, item.ShFileDir.Length);
}
item.ProjectSourceDir = stb_project_source_dir.Text;
if (item.ProjectSourceDir.EndsWith("/"))
{
item.ProjectSourceDir = item.ProjectSourceDir.Substring(0, item.ProjectSourceDir.Length);
}
item.HomeUrl = stb_home_url.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.HomeUrl))
{
item.HomeUrl = "http://" + config.Host + ":8080/";
}
if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
{
MessageBox.Show(this, "请填写应用名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.ShFileDir))
{
MessageBox.Show(this, "请填写应用脚本目录");
return;
}
else if (string.IsNullOrWhiteSpace(item.BuildFileName))
{
MessageBox.Show(this, "请填写应用编译脚本文件名称");
return;
}
else if (string.IsNullOrWhiteSpace(item.CrlFileName))
{
MessageBox.Show(this, "请填写应用控制脚本文件名称");
return;
}
else if (string.IsNullOrWhiteSpace(item.ProjectSourceDir))
{
MessageBox.Show(this, "请填写应用代码存放目录");
return;
}
item.NeedAdd = cb_need_add.Checked;
if (item.NeedAdd)
{
item.ProjectSvnUrl = stb_project_svn.Text;
if (string.IsNullOrWhiteSpace(item.ProjectSvnUrl))
{
MessageBox.Show(this, "请填写应用SVN地址");
return;
}
}
if (isnew)
{
item.Uuid = Guid.NewGuid().ToString("N");
monitorConfig = new MonitorItemConfig();
}
else
{
item.Uuid = monitorConfig.spring.Uuid;
}
monitorConfig.spring = item;
}
else if (index == 1)
{ // tomcat
TomcatMonitorItem item = new TomcatMonitorItem();
item.TomcatName = stb_tomcat_name.Text;
item.TomcatDir = stb_tomcat_path.Text;
item.TomcatPort = stb_tomcat_port.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.TomcatName) || hasNonChar(item.TomcatName))
{
MessageBox.Show(this, "请填写Tomcat名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.TomcatDir))
{
MessageBox.Show(this, "请填写Tomcat根目录");
return;
}
else if (string.IsNullOrWhiteSpace(item.TomcatPort))
{
item.TomcatPort = "8080";
}
if (isnew)
{
item.Uuid = Guid.NewGuid().ToString("N");
monitorConfig = new MonitorItemConfig();
}
else
{
item.Uuid = monitorConfig.tomcat.Uuid;
}
monitorConfig.tomcat = item;
}
else if (index == 2)
{ // nginx
NginxMonitorItem item = new NginxMonitorItem();
item.NginxName = stb_nginx_name.Text;
item.NginxPath = stb_nginx_path.Text;
item.NginxConfig = stb_nginx_conf.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.NginxName) || hasNonChar(item.NginxName))
{
MessageBox.Show(this, "请填写Nginx名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.NginxPath))
{
MessageBox.Show(this, "请填写Nginx执行文件完整路径");
return;
}
else if (string.IsNullOrWhiteSpace(item.NginxConfig))
{
MessageBox.Show(this, "请填写Nginx配置文件完整路径");
return;
}
if (isnew)
{
monitorConfig = new MonitorItemConfig();
item.Uuid = Guid.NewGuid().ToString("N");
}
else
{
item.Uuid = monitorConfig.nginx.Uuid;
}
monitorConfig.nginx = item;
}
else if (index == 3)
{ // ice
IceMonitorItem item = new IceMonitorItem();
item.AppName = stb_ice_appname.Text;
item.IceSrvDir = stb_ice_srvpath.Text;
item.NodePorts = stb_ice_ports.Text;
item.ServerName = stb_ice_servername.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
{
MessageBox.Show(this, "请填写项目名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.IceSrvDir))
{
MessageBox.Show(this, "请填写项目Ice目录完整路径");
return;
}
else if (string.IsNullOrWhiteSpace(item.ServerName))
{
MessageBox.Show(this, "请填写Ice服务名称");
return;
}
else if (string.IsNullOrWhiteSpace(item.NodePorts))
{
MessageBox.Show(this, "请填写项目使用的端口号,多个以逗号(,)分隔");
return;
}
if (isnew)
{
monitorConfig = new MonitorItemConfig();
item.Uuid = Guid.NewGuid().ToString("N");
}
else
{
item.Uuid = monitorConfig.ice.Uuid;
}
monitorConfig.ice = item;
}
if (isnew)
{
config.MonitorConfigList.Add(monitorConfig);
}
AppConfig.Instance.SaveConfig(2);
if (null != parentForm && monitorConfig.spring != null)
{
// TODO 执行checkout
if (monitorConfig.spring.NeedAdd)
{
string home = parentForm.getSftp().getHome();
string buildStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__build.sh");
string ctlStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__ctl.sh");
if (monitorConfig.spring.ProjectSourceDir.StartsWith(home))
{
string path = monitorConfig.spring.ProjectSourceDir.Substring(home.Length);
if (path.StartsWith("/"))
{
path = path.Substring(1);
}
buildStr = buildStr.Replace("_sourcePath_", "~/" + path);
ctlStr = ctlStr.Replace("_sourcePath_", "~/" + path);
}
else
{
buildStr = buildStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
ctlStr = ctlStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
}
buildStr = buildStr.Replace("_projectName_", monitorConfig.spring.AppName);
ctlStr = ctlStr.Replace("_projectName_", monitorConfig.spring.AppName);
ctlStr = ctlStr.Replace("_disconfigUrl_", stb_disconfig_url.Text);
string localBuild = MainForm.CONF_DIR + monitorConfig.spring.BuildFileName;
string localCtl = MainForm.CONF_DIR + monitorConfig.spring.CrlFileName;
string remoteBuild = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.BuildFileName;
string remoteCtl = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.CrlFileName;
YSTools.YSFile.writeFileByString(localBuild, buildStr);
YSTools.YSFile.writeFileByString(localCtl, ctlStr);
ThreadPool.QueueUserWorkItem((a) =>
{
Thread.Sleep(500);
parentForm.BeginInvoke((MethodInvoker)delegate()
{
parentForm.getSftp().put(localBuild, remoteBuild, ChannelSftp.OVERWRITE);
parentForm.getSftp().put(localCtl, remoteCtl, ChannelSftp.OVERWRITE);
parentForm.RunShell("cd " + monitorConfig.spring.ProjectSourceDir, true);
parentForm.RunShell("svn checkout " + monitorConfig.spring.ProjectSvnUrl, true);
File.Delete(localBuild);
File.Delete(localCtl);
});
});
}
}
this.Close();
}
19
Source : TimedTaskForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void button2_Click(object sender, EventArgs e)
{
string name = task_name.Text;
int count = customShellListView.Items.Count;
if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show(this, "请输入任务名称");
task_name.Focus();
}
else if (count == 0)
{
MessageBox.Show(this, "请添加任务指令脚本(Shell)");
shell_name.Focus();
}
else
{
ListView.ListViewItemCollection coll = customShellListView.Items;
if (null == cmdShell)
{
cmdShell = new CmdShell();
cmdShell.Type = "定时任务";
cmdShell.TaskType = TaskType.Timed;
}
cmdShell.Name = name;
JObject obj = null;
JArray list = new JArray();
List<TaskShell> shellList = new List<TaskShell>();
TaskShell task = null;
foreach(ListViewItem item in coll){
obj = (JObject)item.Tag;
task = new TaskShell();
task.Uuid = Guid.NewGuid().ToString("N");
task.DateTime = obj["time"].ToString();
task.Shell = obj["code"].ToString();
task.Name = obj["name"].ToString();
shellList.Add(task);
}
cmdShell.ShellList = shellList;
if (null != this.callback)
{
this.callback(cmdShell);
}
this.Close();
}
}
19
Source : CentralServerConfigForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void 添加子节点ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_treeView.SelectedItems.Count > 0)
{
TreeListViewItem parentNode = _treeView.SelectedItems[0];
YmlItem parentObj = (YmlItem) parentNode.Tag;
TreeListViewItem viewItem = new TreeListViewItem();
YmlItem obj = new YmlItem()
{
Key = "",
Value = "",
Level = parentObj.Level + 1,
Common = "",
Uuid = Guid.NewGuid().ToString("N"),
ImageIndex = 1,
Parent = parentObj,
SpcCount = (parentObj.Level + 1) * 4
};
viewItem.Tag = obj;
viewItem.Text = obj.Key;
viewItem.ImageIndex = obj.ImageIndex;
viewItem.SubItems.Add(obj.Value);
viewItem.SubItems.Add("" + obj.Level);
viewItem.SubItems.Add(obj.Common);
parentNode.Items.Add(viewItem);
string parentId = parentObj.Uuid;
YmlNodeForm form = new YmlNodeForm(viewItem, null, null, 1);
form.ShowDialog(this);
string value = viewItem.SubItems[1].Text;
if (string.IsNullOrWhiteSpace(value))
{
string key = viewItem.SubItems[0].Text;
if (key.Trim().StartsWith("#"))
{
obj.ImageIndex = 2;
} else {
obj.ImageIndex = 3;
}
viewItem.ImageIndex = obj.ImageIndex;
}
btn_save.Enabled = true;
}
}
19
Source : CentralServerConfigForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void 添加顶级节点ToolStripMenuItem1_Click(object sender, EventArgs e)
{
TreeListViewItem viewItem = new TreeListViewItem();
YmlItem obj = new YmlItem()
{
Key = "",
Value = "",
Level = 0,
Common = "",
Uuid = Guid.NewGuid().ToString("N"),
ImageIndex = 3,
Parent = null,
SpcCount = 0
};
viewItem.Tag = obj;
viewItem.Text = obj.Key;
viewItem.ImageIndex = obj.ImageIndex;
viewItem.SubItems.Add(obj.Value);
viewItem.SubItems.Add("" + obj.Level);
viewItem.SubItems.Add(obj.Common);
_treeView.Items.Add(viewItem);
YmlNodeForm form = new YmlNodeForm(viewItem, null, null, 2);
form.ShowDialog(this);
btn_save.Enabled = true;
}
19
Source : CentralServerConfigForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void 添加同级节点ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_treeView.SelectedItems.Count > 0)
{
TreeListViewItem parentNode = _treeView.SelectedItems[0];
YmlItem parentObj = (YmlItem)parentNode.Tag;
TreeListViewItem viewItem = new TreeListViewItem();
YmlItem obj = new YmlItem()
{
Key = "",
Value = "",
Level = parentObj.Level,
Common = "",
Uuid = Guid.NewGuid().ToString("N"),
ImageIndex = parentObj.ImageIndex == 2 ? 1 : parentObj.ImageIndex,
Parent = parentObj.Parent,
SpcCount = parentObj.SpcCount
};
viewItem.Tag = obj;
viewItem.Text = obj.Key;
viewItem.ImageIndex = obj.ImageIndex;
viewItem.SubItems.Add(obj.Value);
viewItem.SubItems.Add("" + obj.Level);
viewItem.SubItems.Add(obj.Common);
if (parentNode.Parent != null)
{
parentNode.Parent.Items.Add(viewItem);
}
else
{
_treeView.Items.Add(viewItem);
}
YmlNodeForm form = new YmlNodeForm(viewItem, null, null, 1);
form.ShowDialog(this);
string value = viewItem.SubItems[1].Text;
if (string.IsNullOrWhiteSpace(value))
{
string key = viewItem.SubItems[0].Text;
if (key.Trim().StartsWith("#"))
{
obj.ImageIndex = 2;
}
else
{
obj.ImageIndex = 3;
}
viewItem.ImageIndex = obj.ImageIndex;
}
btn_save.Enabled = true;
}
}
19
Source : CustomShellForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void button1_Click(object sender, EventArgs e)
{
string name = stb_name.Text;
string cmdstr = cmd.Text;
if(string.IsNullOrWhiteSpace(name)){
MessageBox.Show(this, "请定义一个名称");
return;
}
if (string.IsNullOrWhiteSpace(cmdstr))
{
MessageBox.Show(this, "请输入要执行的命令");
return;
}
List<TaskShell> cmdList = new List<TaskShell>();
string[] cmds = cmdstr.Split('\n');
TaskShell task = null;
foreach(string c in cmds){
if (!string.IsNullOrWhiteSpace(c.Trim()))
{
task = new TaskShell();
task.Uuid = Guid.NewGuid().ToString("N");
task.Name = "";
task.Shell = c.Trim();
cmdList.Add(task);
}
}
bool isnew = false;
if(shell == null){
shell = new CmdShell();
shell.Uuid = Guid.NewGuid().ToString("N");
shell.Target = uuid;
isnew = true;
}
shell.Name = name;
shell.Type = "自定义脚本";
shell.TaskType = TaskType.Default;
shell.ShellList = cmdList;
if (isnew)
{
config.CustomShellList.Add(shell);
}
AppConfig.Instance.SaveConfig(2);
this.Close();
}
19
Source : RedisSentinelManager.cs
with MIT License
from 2881099
with MIT License
from 2881099
string SetMaster(string name, int timeout)
{
for (int i = 0; i < _sentinels.Count; i++)
{
if (i > 0)
Next();
using (var sentinel = Current())
{
try
{
if (!sentinel.Connect(timeout))
continue;
}
catch (Exception)
{
continue;
}
var master = sentinel.GetMasterAddrByName(name);
if (master == null)
continue;
if (_redisClient != null)
_redisClient.Dispose();
if (SentinelMasterConverter != null)
master = SentinelMasterConverter(master);
_redisClient = new RedisClient(master.Item1, master.Item2);
_redisClient.Connected += OnConnectionConnected;
try
{
if (!_redisClient.Connect(timeout))
continue;
var role = _redisClient.Role();
if (role.RoleName != "master")
continue;
//测试 write
var testid = Guid.NewGuid().ToString("N");
_redisClient.StartPipe();
_redisClient.Set(testid, 1);
_redisClient.Del(testid);
_redisClient.EndPipe();
foreach (var remoteSentinel in sentinel.Sentinels(name))
Add(remoteSentinel.Ip, remoteSentinel.Port);
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
Console.WriteLine(ex.Message);
continue;
}
return master.Item1 + ':' + master.Item2;
}
}
return null;
}
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static object FromObject(this Type targetType, object value, Encoding encoding = null)
{
if (targetType == typeof(object)) return value;
if (encoding == null) encoding = Encoding.UTF8;
var valueIsNull = value == null;
var valueType = valueIsNull ? typeof(string) : value.GetType();
if (valueType == targetType) return value;
if (valueType == typeof(byte[])) //byte[] -> guid
{
if (targetType == typeof(Guid))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
if (targetType == typeof(Guid?))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
}
}
if (targetType == typeof(byte[])) //guid -> byte[]
{
if (valueIsNull) return null;
if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
var bytes = new byte[16];
var guidN = ((Guid)value).ToString("N");
for (var a = 0; a < guidN.Length; a += 2)
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
return bytes;
}
return encoding.GetBytes(value.ToInvariantCultureToString());
}
else if (targetType.IsArray)
{
if (value is Array valueArr)
{
var targetElementType = targetType.GetElementType();
var sourceArrLen = valueArr.Length;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
return target;
}
//if (value is IList valueList)
//{
// var targetElementType = targetType.GetElementType();
// var sourceArrLen = valueList.Count;
// var target = Array.CreateInstance(targetElementType, sourceArrLen);
// for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
// return target;
//}
}
var func = _dicFromObject.GetOrAdd(targetType, tt =>
{
if (tt == typeof(object)) return vs => vs;
if (tt == typeof(string)) return vs => vs;
if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
if (tt == typeof(bool)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
}
return false;
};
if (tt == typeof(bool?)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
case "false":
case "0":
return false;
}
return null;
};
if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
if (tt.NullableTypeOrThis().IsEnum)
{
var tttype = tt.NullableTypeOrThis();
var ttdefval = tt.CreateInstanceGetDefaultValue();
return vs =>
{
if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
return Enum.Parse(tttype, vs, true);
};
}
var localTargetType = targetType;
var localValueType = valueType;
return vs =>
{
if (vs == null) return null;
throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
};
});
var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
return func(valueStr);
}
19
Source : DynamicProxy.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append($@"{(proxyMethodName == "Before" ? $@"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
$@"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append($@"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return $@"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? $@"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append($@"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append($@"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append($@"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append($@"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append($@"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append($@"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append($@"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append($@"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => $@"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append($@"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
19
Source : CodeGenerate.cs
with MIT License
from 2881099
with MIT License
from 2881099
public async Task<string> Setup(Models.TaskBuild task)
{
try
{
var paths = await Task.Run(() =>
{
var config = new TemplateServiceConfiguration();
config.EncodedStringFactory = new RawStringFactory();
var service = RazorEngineService.Create(config);
Engine.Razor = service;
///本次要操作的数据库
var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();
string path = string.Empty;
foreach (var db in dataBases)
{
//创建数据库连接
using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
.Build())
{
//取指定数据库信息
var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
var outputTables = tables;
//是否有指定表
var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
if (uTables.Length > 0)
//过滤不要的表
outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();
//根据用户设置组装生成路径并验证目录是否存在
path = $"{task.GeneratePath}\\{db.Name}";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var razorId = Guid.NewGuid().ToString("N");
Engine.Razor.Compile(task.Templates.Code, razorId);
//开始生成操作
foreach (var table in outputTables)
{
var sw = new StringWriter();
var model = new RazorModel(fsql, task, tables, table);
Engine.Razor.Run(razorId, sw, null, model);
StringBuilder plus = new StringBuilder();
plus.AppendLine("//------------------------------------------------------------------------------");
plus.AppendLine("// <auto-generated>");
plus.AppendLine("// 此代码由工具生成。");
plus.AppendLine("// 运行时版本:" + Environment.Version.ToString());
plus.AppendLine("// Website: http://www.freesql.net");
plus.AppendLine("// 对此文件的更改可能会导致不正确的行为,并且如果");
plus.AppendLine("// 重新生成代码,这些更改将会丢失。");
plus.AppendLine("// </auto-generated>");
plus.AppendLine("//------------------------------------------------------------------------------");
plus.Append(sw.ToString());
plus.AppendLine();
File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
}
}
}
return path;
});
Process.Start(paths);
return "生成成功";
}
catch (Exception ex)
{
return "生成时发生异常,请检查模版代码.";
}
}
19
Source : CodeGenerate.cs
with MIT License
from 2881099
with MIT License
from 2881099
public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
{
try
{
var paths = await Task.Run(() =>
{
var config = new TemplateServiceConfiguration();
config.EncodedStringFactory = new RawStringFactory();
Engine.Razor = RazorEngineService.Create(config);
string path = string.Empty;
foreach (var templatesPath in taskBuild.Templates)
{
path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var razorId = Guid.NewGuid().ToString("N");
var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
Engine.Razor.Compile(html, razorId);
//开始生成操作
foreach (var table in outputTables)
{
var sw = new StringWriter();
var model = new RazorModel(taskBuild, outputTables, table);
Engine.Razor.Run(razorId, sw, null, model);
StringBuilder plus = new StringBuilder();
plus.AppendLine("//------------------------------------------------------------------------------");
plus.AppendLine("// <auto-generated>");
plus.AppendLine("// 此代码由工具生成。");
plus.AppendLine("// 运行时版本:" + Environment.Version.ToString());
plus.AppendLine("// Website: http://www.freesql.net");
plus.AppendLine("// 对此文件的更改可能会导致不正确的行为,并且如果");
plus.AppendLine("// 重新生成代码,这些更改将会丢失。");
plus.AppendLine("// </auto-generated>");
plus.AppendLine("//------------------------------------------------------------------------------");
plus.Append(sw.ToString());
plus.AppendLine();
var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
File.WriteAllText(outPath, plus.ToString());
}
}
return path;
});
Process.Start(paths);
return "生成成功";
}
catch (Exception ex)
{
MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
return $"生成时发生异常,请检查模版代码: {ex.Message}.";
}
}
19
Source : ImClient.cs
with MIT License
from 2881099
with MIT License
from 2881099
protected string SelectServer(Guid clientId)
{
var servers_idx = int.Parse(clientId.ToString("N").Substring(28), NumberStyles.HexNumber) % _servers.Length;
if (servers_idx >= _servers.Length) servers_idx = 0;
return _servers[servers_idx];
}
19
Source : CodeGenerate.cs
with MIT License
from 2881099
with MIT License
from 2881099
public async Task<string> Setup(TaskBuild taskBuild, string code, List<DbTableInfo> dbTables, DbTableInfo dbTableInfo)
{
StringBuilder plus = new StringBuilder();
try
{
var config = new TemplateServiceConfiguration();
config.EncodedStringFactory = new RawStringFactory();
Engine.Razor = RazorEngineService.Create(config);
var razorId = Guid.NewGuid().ToString("N");
Engine.Razor.Compile(code, razorId);
var sw = new StringWriter();
var model = new RazorModel(taskBuild, dbTables, dbTableInfo);
Engine.Razor.Run(razorId, sw, null, model);
plus.AppendLine("//------------------------------------------------------------------------------");
plus.AppendLine("// <auto-generated>");
plus.AppendLine("// 此代码由工具生成。");
plus.AppendLine("// 运行时版本:" + Environment.Version.ToString());
plus.AppendLine("// Website: http://www.freesql.net");
plus.AppendLine("// 对此文件的更改可能会导致不正确的行为,并且如果");
plus.AppendLine("// 重新生成代码,这些更改将会丢失。");
plus.AppendLine("// </auto-generated>");
plus.AppendLine("//------------------------------------------------------------------------------");
plus.Append(sw.ToString());
plus.AppendLine();
return await Task.FromResult(plus.ToString());
}
catch
{
return await Task.FromResult(plus.ToString());
}
}
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static string GetGUID()
{
try
{
return Guid.NewGuid().ToString("D");
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
}
return string.Empty;
}
19
Source : StringExtension.cs
with MIT License
from 3F
with MIT License
from 3F
public static string SlnFormat(this Guid guid)
{
return guid.ToString("B").ToUpper();
}
19
Source : User.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public static string CreateRandomPreplacedword()
{
return Guid.NewGuid().ToString("N").Truncate(16);
}
19
Source : AllocationTests.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
[SetUp]
public void Setup()
{
_tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_tempDirectory);
_waitableAppender = new WaitableAppender(Path.Combine(_tempDirectory, "allocation-test"));
BasicConfigurator.Configure(new ZeroLogBasicConfiguration
{
Appenders = { _waitableAppender },
LogEventQueueSize = 2048 * 10,
LogEventBufferSize = 512
});
LogManager.RegisterEnum<DayOfWeek>();
LogManager.RegisterUnmanaged<UnmanagedStruct>();
}
19
Source : Uuid128.cs
with MIT License
from abdullin
with MIT License
from abdullin
public string ToString(string format)
{
return m_packed.ToString(format);
}
19
Source : GuidGenerator.cs
with MIT License
from abock
with MIT License
from abock
static string FormatGuid(GuidFormat format, Guid guid)
{
switch (format)
{
case GuidFormat.N:
return guid.ToString("N");
case GuidFormat.B:
return guid.ToString("B");
case GuidFormat.P:
return guid.ToString("P");
case GuidFormat.X:
return guid.ToString("X");
case GuidFormat.Base64:
return Convert.ToBase64String(guid.ToByteArray());
case GuidFormat.Short:
return Convert.ToBase64String(guid.ToByteArray())
.Replace("/", "_")
.Replace("+", "-")
.Substring(0, 22);
case GuidFormat.D:
default:
return guid.ToString("D");
}
}
19
Source : OrderingMongoDbTestModule.cs
with MIT License
from AbpApp
with MIT License
from AbpApp
public override void ConfigureServices(ServiceConfigurationContext context)
{
var connectionString = MongoDbRunner.ConnectionString.EnsureEndsWith('/') +
"Db_" +
Guid.NewGuid().ToString("N");
Configure<AbpDbConnectionOptions>(options =>
{
options.ConnectionStrings.Default = connectionString;
});
}
19
Source : ContainerActionHandler.cs
with MIT License
from actions
with MIT License
from actions
public async Task RunAsync(ActionRunStage stage)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(Data, nameof(Data));
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
#if OS_WINDOWS || OS_OSX
throw new NotSupportedException($"Container action is only supported on Linux");
#else
// Update the env dictionary.
AddInputsToEnvironment();
var dockerManager = HostContext.GetService<IDockerCommandManager>();
// container image haven't built/pull
if (Data.Image.StartsWith("docker://", StringComparison.OrdinalIgnoreCase))
{
Data.Image = Data.Image.Substring("docker://".Length);
}
else if (Data.Image.EndsWith("Dockerfile") || Data.Image.EndsWith("dockerfile"))
{
// ensure docker file exist
var dockerFile = Path.Combine(ActionDirectory, Data.Image);
ArgUtil.File(dockerFile, nameof(Data.Image));
ExecutionContext.Output($"##[group]Building docker image");
ExecutionContext.Output($"Dockerfile for action: '{dockerFile}'.");
var imageName = $"{dockerManager.DockerInstanceLabel}:{ExecutionContext.Id.ToString("N")}";
var buildExitCode = await dockerManager.DockerBuild(
ExecutionContext,
ExecutionContext.GetGitHubContext("workspace"),
dockerFile,
Directory.GetParent(dockerFile).FullName,
imageName);
ExecutionContext.Output("##[endgroup]");
if (buildExitCode != 0)
{
throw new InvalidOperationException($"Docker build failed with exit code {buildExitCode}");
}
Data.Image = imageName;
}
string type = Action.Type == Pipelines.ActionSourceType.Repository ? "Dockerfile" : "DockerHub";
// Add Telemetry to JobContext to send with JobCompleteMessage
if (stage == ActionRunStage.Main)
{
var telemetry = new ActionsStepTelemetry {
Ref = GetActionRef(),
HasPreStep = Data.HasPre,
HasPostStep = Data.HasPost,
IsEmbedded = ExecutionContext.IsEmbedded,
Type = type
};
ExecutionContext.Root.ActionsStepsTelemetry.Add(telemetry);
}
// run container
var container = new ContainerInfo(HostContext)
{
ContainerImage = Data.Image,
ContainerName = ExecutionContext.Id.ToString("N"),
ContainerDisplayName = $"{Pipelines.Validation.NameValidation.Sanitize(Data.Image)}_{Guid.NewGuid().ToString("N").Substring(0, 6)}",
};
if (stage == ActionRunStage.Main)
{
if (!string.IsNullOrEmpty(Data.EntryPoint))
{
// use entrypoint from action.yml
container.ContainerEntryPoint = Data.EntryPoint;
}
else
{
// use entrypoint input, this is for action v1 which doesn't have action.yml
container.ContainerEntryPoint = Inputs.GetValueOrDefault("entryPoint");
}
}
else if (stage == ActionRunStage.Pre)
{
container.ContainerEntryPoint = Data.Pre;
}
else if (stage == ActionRunStage.Post)
{
container.ContainerEntryPoint = Data.Post;
}
// create inputs context for template evaluation
var inputsContext = new DictionaryContextData();
if (this.Inputs != null)
{
foreach (var input in Inputs)
{
inputsContext.Add(input.Key, new StringContextData(input.Value));
}
}
var extraExpressionValues = new Dictionary<string, PipelineContextData>(StringComparer.OrdinalIgnoreCase);
extraExpressionValues["inputs"] = inputsContext;
var manifestManager = HostContext.GetService<IActionManifestManager>();
if (Data.Arguments != null)
{
container.ContainerEntryPointArgs = "";
var evaluatedArgs = manifestManager.EvaluateContainerArguments(ExecutionContext, Data.Arguments, extraExpressionValues);
foreach (var arg in evaluatedArgs)
{
if (!string.IsNullOrEmpty(arg))
{
container.ContainerEntryPointArgs = container.ContainerEntryPointArgs + $" \"{arg.Replace("\"", "\\\"")}\"";
}
else
{
container.ContainerEntryPointArgs = container.ContainerEntryPointArgs + " \"\"";
}
}
}
else
{
container.ContainerEntryPointArgs = Inputs.GetValueOrDefault("args");
}
if (Data.Environment != null)
{
var evaluatedEnv = manifestManager.EvaluateContainerEnvironment(ExecutionContext, Data.Environment, extraExpressionValues);
foreach (var env in evaluatedEnv)
{
if (!this.Environment.ContainsKey(env.Key))
{
this.Environment[env.Key] = env.Value;
}
}
}
if (ExecutionContext.JobContext.Container.TryGetValue("network", out var networkContextData) && networkContextData is StringContextData networkStringData)
{
container.ContainerNetwork = networkStringData.ToString();
}
var defaultWorkingDirectory = ExecutionContext.GetGitHubContext("workspace");
var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
ArgUtil.NotNullOrEmpty(defaultWorkingDirectory, nameof(defaultWorkingDirectory));
ArgUtil.NotNullOrEmpty(tempDirectory, nameof(tempDirectory));
var tempHomeDirectory = Path.Combine(tempDirectory, "_github_home");
Directory.CreateDirectory(tempHomeDirectory);
this.Environment["HOME"] = tempHomeDirectory;
var tempFileCommandDirectory = Path.Combine(tempDirectory, "_runner_file_commands");
ArgUtil.Directory(tempFileCommandDirectory, nameof(tempFileCommandDirectory));
var tempWorkflowDirectory = Path.Combine(tempDirectory, "_github_workflow");
ArgUtil.Directory(tempWorkflowDirectory, nameof(tempWorkflowDirectory));
container.MountVolumes.Add(new MountVolume("/var/run/docker.sock", "/var/run/docker.sock"));
container.MountVolumes.Add(new MountVolume(tempHomeDirectory, "/github/home"));
container.MountVolumes.Add(new MountVolume(tempWorkflowDirectory, "/github/workflow"));
container.MountVolumes.Add(new MountVolume(tempFileCommandDirectory, "/github/file_commands"));
container.MountVolumes.Add(new MountVolume(defaultWorkingDirectory, "/github/workspace"));
container.AddPathTranslateMapping(tempHomeDirectory, "/github/home");
container.AddPathTranslateMapping(tempWorkflowDirectory, "/github/workflow");
container.AddPathTranslateMapping(tempFileCommandDirectory, "/github/file_commands");
container.AddPathTranslateMapping(defaultWorkingDirectory, "/github/workspace");
container.ContainerWorkDirectory = "/github/workspace";
// expose context to environment
foreach (var context in ExecutionContext.ExpressionValues)
{
if (context.Value is IEnvironmentContextData runtimeContext && runtimeContext != null)
{
foreach (var env in runtimeContext.GetRuntimeEnvironmentVariables())
{
Environment[env.Key] = env.Value;
}
}
}
// Add Actions Runtime server info
var systemConnection = ExecutionContext.Global.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
Environment["ACTIONS_RUNTIME_URL"] = systemConnection.Url.AbsoluteUri;
Environment["ACTIONS_RUNTIME_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
if (systemConnection.Data.TryGetValue("CacheServerUrl", out var cacheUrl) && !string.IsNullOrEmpty(cacheUrl))
{
Environment["ACTIONS_CACHE_URL"] = cacheUrl;
}
if (systemConnection.Data.TryGetValue("GenerateIdTokenUrl", out var generateIdTokenUrl) && !string.IsNullOrEmpty(generateIdTokenUrl))
{
Environment["ACTIONS_ID_TOKEN_REQUEST_URL"] = generateIdTokenUrl;
Environment["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
}
foreach (var variable in this.Environment)
{
container.ContainerEnvironmentVariables[variable.Key] = container.TranslateToContainerPath(variable.Value);
}
using (var stdoutManager = new OutputManager(ExecutionContext, ActionCommandManager, container))
using (var stderrManager = new OutputManager(ExecutionContext, ActionCommandManager, container))
{
var runExitCode = await dockerManager.DockerRun(ExecutionContext, container, stdoutManager.OnDataReceived, stderrManager.OnDataReceived);
ExecutionContext.Debug($"Docker Action run completed with exit code {runExitCode}");
if (runExitCode != 0)
{
ExecutionContext.Result = TaskResult.Failed;
}
}
#endif
}
19
Source : JobExtension.cs
with MIT License
from actions
with MIT License
from actions
public async Task<List<IStep>> InitializeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message)
{
Trace.Entering();
ArgUtil.NotNull(jobContext, nameof(jobContext));
ArgUtil.NotNull(message, nameof(message));
// Create a new timeline record for 'Set up job'
IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Set up job", $"{nameof(JobExtension)}_Init", null, null, ActionRunStage.Pre);
List<IStep> preJobSteps = new List<IStep>();
List<IStep> jobSteps = new List<IStep>();
using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
{
try
{
context.Start();
context.Debug($"Starting: Set up job");
context.Output($"Current runner version: '{BuildConstants.RunnerPackage.Version}'");
var setting = HostContext.GetService<IConfigurationStore>().GetSettings();
var credFile = HostContext.GetConfigFile(WellKnownConfigFile.Credentials);
if (File.Exists(credFile))
{
var credData = IOUtil.LoadObject<CredentialData>(credFile);
if (credData != null &&
credData.Data.TryGetValue("clientId", out var clientId))
{
// print out HostName for self-hosted runner
context.Output($"Runner name: '{setting.AgentName}'");
if (message.Variables.TryGetValue("system.runnerGroupName", out VariableValue runnerGroupName))
{
context.Output($"Runner group name: '{runnerGroupName.Value}'");
}
context.Output($"Machine name: '{Environment.MachineName}'");
}
}
var setupInfoFile = HostContext.GetConfigFile(WellKnownConfigFile.SetupInfo);
if (File.Exists(setupInfoFile))
{
Trace.Info($"Load machine setup info from {setupInfoFile}");
try
{
var setupInfo = IOUtil.LoadObject<List<SetupInfo>>(setupInfoFile);
if (setupInfo?.Count > 0)
{
foreach (var info in setupInfo)
{
if (!string.IsNullOrEmpty(info?.Detail))
{
var groupName = info.Group;
if (string.IsNullOrEmpty(groupName))
{
groupName = "Machine Setup Info";
}
context.Output($"##[group]{groupName}");
var multiLines = info.Detail.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
foreach (var line in multiLines)
{
context.Output(line);
}
context.Output("##[endgroup]");
}
}
}
}
catch (Exception ex)
{
context.Output($"Fail to load and print machine setup info: {ex.Message}");
Trace.Error(ex);
}
}
try
{
var tokenPermissions = jobContext.Global.Variables.Get("system.github.token.permissions") ?? "";
if (!string.IsNullOrEmpty(tokenPermissions))
{
context.Output($"##[group]GITHUB_TOKEN Permissions");
var permissions = StringUtil.ConvertFromJson<Dictionary<string, string>>(tokenPermissions);
foreach(KeyValuePair<string, string> entry in permissions)
{
context.Output($"{entry.Key}: {entry.Value}");
}
context.Output("##[endgroup]");
}
}
catch (Exception ex)
{
context.Output($"Fail to parse and display GITHUB_TOKEN permissions list: {ex.Message}");
Trace.Error(ex);
}
var repoFullName = context.GetGitHubContext("repository");
ArgUtil.NotNull(repoFullName, nameof(repoFullName));
context.Debug($"Primary repository: {repoFullName}");
// Print proxy setting information for better diagnostic experience
if (!string.IsNullOrEmpty(HostContext.WebProxy.HttpProxyAddress))
{
context.Output($"Runner is running behind proxy server '{HostContext.WebProxy.HttpProxyAddress}' for all HTTP requests.");
}
if (!string.IsNullOrEmpty(HostContext.WebProxy.HttpsProxyAddress))
{
context.Output($"Runner is running behind proxy server '{HostContext.WebProxy.HttpsProxyAddress}' for all HTTPS requests.");
}
// Prepare the workflow directory
context.Output("Prepare workflow directory");
var directoryManager = HostContext.GetService<IPipelineDirectoryManager>();
TrackingConfig trackingConfig = directoryManager.PrepareDirectory(
context,
message.Workspace);
// Set the directory variables
context.Debug("Update context data");
string _workDirectory = HostContext.GetDirectory(WellKnownDirectory.Work);
context.SetRunnerContext("workspace", Path.Combine(_workDirectory, trackingConfig.PipelineDirectory));
context.SetGitHubContext("workspace", Path.Combine(_workDirectory, trackingConfig.WorkspaceDirectory));
// Temporary hack for GHES alpha
var configurationStore = HostContext.GetService<IConfigurationStore>();
var runnerSettings = configurationStore.GetSettings();
if (string.IsNullOrEmpty(context.GetGitHubContext("server_url")) && !runnerSettings.IsHostedServer && !string.IsNullOrEmpty(runnerSettings.GitHubUrl))
{
var url = new Uri(runnerSettings.GitHubUrl);
var portInfo = url.IsDefaultPort ? string.Empty : $":{url.Port.ToString(CultureInfo.InvariantCulture)}";
context.SetGitHubContext("server_url", $"{url.Scheme}://{url.Host}{portInfo}");
context.SetGitHubContext("api_url", $"{url.Scheme}://{url.Host}{portInfo}/api/v3");
context.SetGitHubContext("graphql_url", $"{url.Scheme}://{url.Host}{portInfo}/api/graphql");
}
// Evaluate the job-level environment variables
context.Debug("Evaluating job-level environment variables");
var templateEvaluator = context.ToPipelineTemplateEvaluator();
foreach (var token in message.EnvironmentVariables)
{
var environmentVariables = templateEvaluator.EvaluateStepEnvironment(token, jobContext.ExpressionValues, jobContext.ExpressionFunctions, VarUtil.EnvironmentVariableKeyComparer);
foreach (var pair in environmentVariables)
{
context.Global.EnvironmentVariables[pair.Key] = pair.Value ?? string.Empty;
context.SetEnvContext(pair.Key, pair.Value ?? string.Empty);
}
}
// Evaluate the job container
context.Debug("Evaluating job container");
var container = templateEvaluator.EvaluateJobContainer(message.JobContainer, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
if (container != null)
{
jobContext.Global.Container = new Container.ContainerInfo(HostContext, container);
}
// Evaluate the job service containers
context.Debug("Evaluating job service containers");
var serviceContainers = templateEvaluator.EvaluateJobServiceContainers(message.JobServiceContainers, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
if (serviceContainers?.Count > 0)
{
foreach (var pair in serviceContainers)
{
var networkAlias = pair.Key;
var serviceContainer = pair.Value;
jobContext.Global.ServiceContainers.Add(new Container.ContainerInfo(HostContext, serviceContainer, false, networkAlias));
}
}
// Evaluate the job defaults
context.Debug("Evaluating job defaults");
foreach (var token in message.Defaults)
{
var defaults = token.replacedertMapping("defaults");
if (defaults.Any(x => string.Equals(x.Key.replacedertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase)))
{
context.Global.JobDefaults["run"] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var defaultsRun = defaults.First(x => string.Equals(x.Key.replacedertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase));
var jobDefaults = templateEvaluator.EvaluateJobDefaultsRun(defaultsRun.Value, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
foreach (var pair in jobDefaults)
{
if (!string.IsNullOrEmpty(pair.Value))
{
context.Global.JobDefaults["run"][pair.Key] = pair.Value;
}
}
}
}
// Build up 2 lists of steps, pre-job, job
// Download actions not already in the cache
Trace.Info("Downloading actions");
var actionManager = HostContext.GetService<IActionManager>();
var prepareResult = await actionManager.PrepareActionsAsync(context, message.Steps);
preJobSteps.AddRange(prepareResult.ContainerSetupSteps);
// Add start-container steps, record and stop-container steps
if (jobContext.Global.Container != null || jobContext.Global.ServiceContainers.Count > 0)
{
var containerProvider = HostContext.GetService<IContainerOperationProvider>();
var containers = new List<Container.ContainerInfo>();
if (jobContext.Global.Container != null)
{
containers.Add(jobContext.Global.Container);
}
containers.AddRange(jobContext.Global.ServiceContainers);
preJobSteps.Add(new JobExtensionRunner(runAsync: containerProvider.StartContainersAsync,
condition: $"{PipelineTemplateConstants.Success}()",
displayName: "Initialize containers",
data: (object)containers));
}
// Add action steps
foreach (var step in message.Steps)
{
if (step.Type == Pipelines.StepType.Action)
{
var action = step as Pipelines.ActionStep;
Trace.Info($"Adding {action.DisplayName}.");
var actionRunner = HostContext.CreateService<IActionRunner>();
actionRunner.Action = action;
actionRunner.Stage = ActionRunStage.Main;
actionRunner.Condition = step.Condition;
var contextData = new Pipelines.ContextData.DictionaryContextData();
if (message.ContextData?.Count > 0)
{
foreach (var pair in message.ContextData)
{
contextData[pair.Key] = pair.Value;
}
}
actionRunner.TryEvaluateDisplayName(contextData, context);
jobSteps.Add(actionRunner);
if (prepareResult.PreStepTracker.TryGetValue(step.Id, out var preStep))
{
Trace.Info($"Adding pre-{action.DisplayName}.");
preStep.TryEvaluateDisplayName(contextData, context);
preStep.DisplayName = $"Pre {preStep.DisplayName}";
preJobSteps.Add(preStep);
}
}
}
var intraActionStates = new Dictionary<Guid, Dictionary<string, string>>();
foreach (var preStep in prepareResult.PreStepTracker)
{
intraActionStates[preStep.Key] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
// Create execution context for pre-job steps
foreach (var step in preJobSteps)
{
if (step is JobExtensionRunner)
{
JobExtensionRunner extensionStep = step as JobExtensionRunner;
ArgUtil.NotNull(extensionStep, extensionStep.DisplayName);
Guid stepId = Guid.NewGuid();
extensionStep.ExecutionContext = jobContext.CreateChild(stepId, extensionStep.DisplayName, null, null, stepId.ToString("N"), ActionRunStage.Pre);
}
else if (step is IActionRunner actionStep)
{
ArgUtil.NotNull(actionStep, step.DisplayName);
Guid stepId = Guid.NewGuid();
actionStep.ExecutionContext = jobContext.CreateChild(stepId, actionStep.DisplayName, stepId.ToString("N"), null, null, ActionRunStage.Pre, intraActionStates[actionStep.Action.Id]);
}
}
// Create execution context for job steps
foreach (var step in jobSteps)
{
if (step is IActionRunner actionStep)
{
ArgUtil.NotNull(actionStep, step.DisplayName);
intraActionStates.TryGetValue(actionStep.Action.Id, out var intraActionState);
actionStep.ExecutionContext = jobContext.CreateChild(actionStep.Action.Id, actionStep.DisplayName, actionStep.Action.Name, null, actionStep.Action.ContextName, ActionRunStage.Main, intraActionState);
}
}
List<IStep> steps = new List<IStep>();
steps.AddRange(preJobSteps);
steps.AddRange(jobSteps);
// Prepare for orphan process cleanup
_processCleanup = jobContext.Global.Variables.GetBoolean("process.clean") ?? true;
if (_processCleanup)
{
// Set the RUNNER_TRACKING_ID env variable.
Environment.SetEnvironmentVariable(Constants.ProcessTrackingId, _processLookupId);
context.Debug("Collect running processes for tracking orphan processes.");
// Take a snapshot of current running processes
Dictionary<int, Process> processes = SnapshotProcesses();
foreach (var proc in processes)
{
// Pid_ProcessName
_existingProcesses.Add($"{proc.Key}_{proc.Value.ProcessName}");
}
}
jobContext.Global.EnvironmentVariables.TryGetValue(Constants.Runner.Features.DiskSpaceWarning, out var enableWarning);
if (StringUtil.ConvertToBoolean(enableWarning, defaultValue: true))
{
_diskSpaceCheckTask = CheckDiskSpaceAsync(context, _diskSpaceCheckToken.Token);
}
return steps;
}
catch (OperationCanceledException ex) when (jobContext.CancellationToken.IsCancellationRequested)
{
// Log the exception and cancel the JobExtension Initialization.
Trace.Error($"Caught cancellation exception from JobExtension Initialization: {ex}");
context.Error(ex);
context.Result = TaskResult.Canceled;
throw;
}
catch (FailedToResolveActionDownloadInfoException ex)
{
// Log the error and fail the JobExtension Initialization.
Trace.Error($"Caught exception from JobExtenion Initialization: {ex}");
context.InfrastructureError(ex.Message);
context.Result = TaskResult.Failed;
throw;
}
catch (Exception ex)
{
// Log the error and fail the JobExtension Initialization.
Trace.Error($"Caught exception from JobExtension Initialization: {ex}");
context.Error(ex);
context.Result = TaskResult.Failed;
throw;
}
finally
{
context.Debug("Finishing: Set up job");
context.Complete();
}
}
}
19
Source : PropertyValidation.cs
with MIT License
from actions
with MIT License
from actions
public static void ValidatePropertyValue(String propertyName, Object value)
{
// Keep this consistent with XmlPropertyWriter.Write.
if (null != value)
{
Type type = value.GetType();
TypeCode typeCode = Type.GetTypeCode(type);
if (type.IsEnum)
{
ValidateStringValue(propertyName, ((Enum)value).ToString("D"));
}
else if (typeCode == TypeCode.Object && value is byte[])
{
ValidateByteArray(propertyName, (byte[])value);
}
else if (typeCode == TypeCode.Object && value is Guid)
{
//treat Guid like the other valid primitive types that
//don't have explicit columns, e.g. it gets stored as a string
ValidateStringValue(propertyName, ((Guid)value).ToString("N"));
}
else if (typeCode == TypeCode.Object)
{
throw new PropertyTypeNotSupportedException(propertyName, type);
}
else if (typeCode == TypeCode.DBNull)
{
throw new PropertyTypeNotSupportedException(propertyName, type);
}
else if (typeCode == TypeCode.Empty)
{
// should be impossible with null check above, but just in case.
throw new PropertyTypeNotSupportedException(propertyName, type);
}
else if (typeCode == TypeCode.Int32)
{
ValidateInt32(propertyName, (int)value);
}
else if (typeCode == TypeCode.Double)
{
ValidateDouble(propertyName, (double)value);
}
else if (typeCode == TypeCode.DateTime)
{
ValidateDateTime(propertyName, (DateTime)value);
}
else if (typeCode == TypeCode.String)
{
ValidateStringValue(propertyName, (String)value);
}
else
{
// Here are the remaining types. All are supported over in DbArtifactPropertyValueColumns.
// With a property definition they'll be strongly-typed when they're read back.
// Otherwise they read back as strings.
// Boolean
// Char
// SByte
// Byte
// Int16
// UInt16
// UInt32
// Int64
// UInt64
// Single
// Decimal
ValidateStringValue(propertyName, value.ToString());
}
}
}
19
Source : VssHttpRequestSettings.cs
with MIT License
from actions
with MIT License
from actions
protected internal virtual Boolean ApplyTo(HttpRequestMessage request)
{
// Make sure we only apply the settings to the request once
if (request.Properties.ContainsKey(PropertyName))
{
return false;
}
request.Properties.Add(PropertyName, this);
if (this.AcceptLanguages != null && this.AcceptLanguages.Count > 0)
{
// An empty or null CultureInfo name will cause an ArgumentNullException in the
// StringWithQualityHeaderValue constructor. CultureInfo.InvariantCulture is an example of
// a CultureInfo that has an empty name.
foreach (CultureInfo culture in this.AcceptLanguages.Where(a => !String.IsNullOrEmpty(a.Name)))
{
request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(culture.Name));
}
}
if (this.UserAgent != null)
{
foreach (var headerVal in this.UserAgent)
{
if (!request.Headers.UserAgent.Contains(headerVal))
{
request.Headers.UserAgent.Add(headerVal);
}
}
}
if (this.SuppressFedAuthRedirects)
{
request.Headers.Add(Internal.HttpHeaders.TfsFedAuthRedirect, "Suppress");
}
// Record the command, if we have it. Otherwise, just record the session ID.
if (!request.Headers.Contains(Internal.HttpHeaders.TfsSessionHeader))
{
if (!String.IsNullOrEmpty(this.OperationName))
{
request.Headers.Add(Internal.HttpHeaders.TfsSessionHeader, String.Concat(this.SessionId.ToString("D"), ", ", this.OperationName));
}
else
{
request.Headers.Add(Internal.HttpHeaders.TfsSessionHeader, this.SessionId.ToString("D"));
}
}
if (!String.IsNullOrEmpty(this.AgentId))
{
request.Headers.Add(Internal.HttpHeaders.VssAgentHeader, this.AgentId);
}
// Content is being sent as chunked by default in dotnet5.4, which differs than the .net 4.5 behaviour.
if (request.Content != null && !request.Content.Headers.ContentLength.HasValue && !request.Headers.TransferEncodingChunked.HasValue)
{
request.Content.Headers.ContentLength = request.Content.ReadAsByteArrayAsync().Result.Length;
}
return true;
}
19
Source : ServiceEndpointReference.cs
with MIT License
from actions
with MIT License
from actions
public override String ToString()
{
return base.ToString() ?? this.Id.ToString("D");
}
19
Source : ContainerOperationProvider.cs
with MIT License
from actions
with MIT License
from actions
public async Task StartContainersAsync(IExecutionContext executionContext, object data)
{
Trace.Entering();
if (!Constants.Runner.Platform.Equals(Constants.OSPlatform.Linux))
{
throw new NotSupportedException("Container operations are only supported on Linux runners");
}
ArgUtil.NotNull(executionContext, nameof(executionContext));
List<ContainerInfo> containers = data as List<ContainerInfo>;
ArgUtil.NotNull(containers, nameof(containers));
var postJobStep = new JobExtensionRunner(runAsync: this.StopContainersAsync,
condition: $"{PipelineTemplateConstants.Always}()",
displayName: "Stop containers",
data: data);
executionContext.Debug($"Register post job cleanup for stopping/deleting containers.");
executionContext.RegisterPostJobStep(postJobStep);
// Check whether we are inside a container.
// Our container feature requires to map working directory from host to the container.
// If we are already inside a container, we will not able to find out the real working direcotry path on the host.
#if OS_WINDOWS
// service CExecSvc is Container Execution Agent.
ServiceController[] scServices = ServiceController.GetServices();
if (scServices.Any(x => String.Equals(x.ServiceName, "cexecsvc", StringComparison.OrdinalIgnoreCase) && x.Status == ServiceControllerStatus.Running))
{
throw new NotSupportedException("Container feature is not supported when runner is already running inside container.");
}
#else
var initProcessCgroup = File.ReadLines("/proc/1/cgroup");
if (initProcessCgroup.Any(x => x.IndexOf(":/docker/", StringComparison.OrdinalIgnoreCase) >= 0))
{
throw new NotSupportedException("Container feature is not supported when runner is already running inside container.");
}
#endif
#if OS_WINDOWS
// Check OS version (Windows server 1803 is required)
object windowsInstallationType = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "InstallationType", defaultValue: null);
ArgUtil.NotNull(windowsInstallationType, nameof(windowsInstallationType));
object windowsReleaseId = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", defaultValue: null);
ArgUtil.NotNull(windowsReleaseId, nameof(windowsReleaseId));
executionContext.Debug($"Current Windows version: '{windowsReleaseId} ({windowsInstallationType})'");
if (int.TryParse(windowsReleaseId.ToString(), out int releaseId))
{
if (!windowsInstallationType.ToString().StartsWith("Server", StringComparison.OrdinalIgnoreCase) || releaseId < 1803)
{
throw new NotSupportedException("Container feature requires Windows Server 1803 or higher.");
}
}
else
{
throw new ArgumentOutOfRangeException(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ReleaseId");
}
#endif
// Check docker client/server version
executionContext.Output("##[group]Checking docker version");
DockerVersion dockerVersion = await _dockerManager.DockerVersion(executionContext);
executionContext.Output("##[endgroup]");
ArgUtil.NotNull(dockerVersion.ServerVersion, nameof(dockerVersion.ServerVersion));
ArgUtil.NotNull(dockerVersion.ClientVersion, nameof(dockerVersion.ClientVersion));
#if OS_WINDOWS
Version requiredDockerEngineAPIVersion = new Version(1, 30); // Docker-EE version 17.6
#else
Version requiredDockerEngineAPIVersion = new Version(1, 35); // Docker-CE version 17.12
#endif
if (dockerVersion.ServerVersion < requiredDockerEngineAPIVersion)
{
throw new NotSupportedException($"Min required docker engine API server version is '{requiredDockerEngineAPIVersion}', your docker ('{_dockerManager.DockerPath}') server version is '{dockerVersion.ServerVersion}'");
}
if (dockerVersion.ClientVersion < requiredDockerEngineAPIVersion)
{
throw new NotSupportedException($"Min required docker engine API client version is '{requiredDockerEngineAPIVersion}', your docker ('{_dockerManager.DockerPath}') client version is '{dockerVersion.ClientVersion}'");
}
// Clean up containers left by previous runs
executionContext.Output("##[group]Clean up resources from previous jobs");
var staleContainers = await _dockerManager.DockerPS(executionContext, $"--all --quiet --no-trunc --filter \"label={_dockerManager.DockerInstanceLabel}\"");
foreach (var staleContainer in staleContainers)
{
int containerRemoveExitCode = await _dockerManager.DockerRemove(executionContext, staleContainer);
if (containerRemoveExitCode != 0)
{
executionContext.Warning($"Delete stale containers failed, docker rm fail with exit code {containerRemoveExitCode} for container {staleContainer}");
}
}
int networkPruneExitCode = await _dockerManager.DockerNetworkPrune(executionContext);
if (networkPruneExitCode != 0)
{
executionContext.Warning($"Delete stale container networks failed, docker network prune fail with exit code {networkPruneExitCode}");
}
executionContext.Output("##[endgroup]");
// Create local docker network for this job to avoid port conflict when multiple runners run on same machine.
// All containers within a job join the same network
executionContext.Output("##[group]Create local container network");
var containerNetwork = $"github_network_{Guid.NewGuid().ToString("N")}";
await CreateContainerNetworkAsync(executionContext, containerNetwork);
executionContext.JobContext.Container["network"] = new StringContextData(containerNetwork);
executionContext.Output("##[endgroup]");
foreach (var container in containers)
{
container.ContainerNetwork = containerNetwork;
await StartContainerAsync(executionContext, container);
}
executionContext.Output("##[group]Waiting for all services to be ready");
foreach (var container in containers.Where(c => !c.IsJobContainer))
{
await ContainerHealthcheck(executionContext, container);
}
executionContext.Output("##[endgroup]");
}
19
Source : ExecutionContext.cs
with MIT License
from actions
with MIT License
from actions
private IExecutionContext CreatePostChild(string displayName, Dictionary<string, string> intraActionState, string siblingScopeName = null)
{
if (!_expandedForPostJob)
{
Trace.Info($"Reserve record order {_childTimelineRecordOrder + 1} to {_childTimelineRecordOrder * 2} for post job actions.");
_expandedForPostJob = true;
_childTimelineRecordOrder = _childTimelineRecordOrder * 2;
}
var newGuid = Guid.NewGuid();
return CreateChild(newGuid, displayName, newGuid.ToString("N"), null, null, ActionRunStage.Post, intraActionState, _childTimelineRecordOrder - Root.PostJobSteps.Count, siblingScopeName: siblingScopeName);
}
19
Source : TestService.cs
with MIT License
from ad313
with MIT License
from ad313
public string Get()
{
return Guid.NewGuid().ToString("N");
}
19
Source : TestService.cs
with MIT License
from ad313
with MIT License
from ad313
public string GetByKey()
{
return Guid.NewGuid().ToString("N");
}
19
Source : TestService.cs
with MIT License
from ad313
with MIT License
from ad313
public string GetByKeyAndParamter(int userId)
{
return Guid.NewGuid().ToString("N") + "---" + userId;
}
19
Source : TestService.cs
with MIT License
from ad313
with MIT License
from ad313
public async Task<UserInfo> GetUserInfo(int type, Req req)
{
return new UserInfo()
{
Id = new Random().Next(1, 100),
Name = Guid.NewGuid().ToString("N"),
UserInfo2 = new UserInfo2()
{
Id = new Random().Next(1, 100),
Name = Guid.NewGuid().ToString("N")
}
};
}
19
Source : TestService.cs
with MIT License
from ad313
with MIT License
from ad313
public async Task<UserInfo> SetUserInfo(int type, Req req)
{
return new UserInfo()
{
Id = new Random().Next(1, 100),
Name = Guid.NewGuid().ToString("N"),
UserInfo2 = new UserInfo2()
{
Id = new Random().Next(1, 100),
Name = Guid.NewGuid().ToString("N")
}
};
}
19
Source : TestService.cs
with MIT License
from ad313
with MIT License
from ad313
[AopCache(Key = "TestSingleClreplacedKey")]
[AopSubscriber(Channel = "aaa2")]
public virtual string Get()
{
return Guid.NewGuid().ToString("N");
}
19
Source : TestService.cs
with MIT License
from ad313
with MIT License
from ad313
[AopPublisher(Channel = "aaa2")]
public virtual string ClearTestSingleClreplacedCache()
{
return Guid.NewGuid().ToString("N");
}
19
Source : EdgeCasesTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public async Task FailingEntryDontGetStuck()
{
var logsDirName = Guid.NewGuid().ToString("D");
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
var fileProvider = new PhysicalFileProvider(tempPath);
var options = new FileLoggerOptions
{
FileAppender = new PhysicalFileAppender(fileProvider),
BasePath = logsDirName,
Files = new[]
{
new LogFileOptions
{
Path = "default.log",
},
},
};
var optionsMonitor = new DelegatedOptionsMonitor<FileLoggerOptions>(_ => options);
var completeCts = new CancellationTokenSource();
var completionTimeoutMs = 2000;
var context = new TestFileLoggerContext(completeCts.Token, TimeSpan.FromMilliseconds(completionTimeoutMs), writeRetryDelay: TimeSpan.FromMilliseconds(250));
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context));
services.AddSingleton<IOptionsMonitor<FileLoggerOptions>>(optionsMonitor);
string filePath = Path.Combine(logPath, "default.log");
try
{
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
var resetTasks = new List<Task>();
foreach (FileLoggerProvider provider in providers)
provider.Reset += (s, e) => resetTasks.Add(e);
ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
ILogger logger = loggerFactory.CreateLogger("X");
logger.LogInformation("This should get through.");
optionsMonitor.Reload();
// ensuring that reset has been finished and the new settings are effective
await Task.WhenAll(resetTasks);
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
logger.LogInformation("This shouldn't get through.");
Task completion = context.GetCompletion(sp);
replacedert.False(completion.IsCompleted);
completeCts.Cancel();
replacedert.Equal(completion, await Task.WhenAny(completion, Task.Delay(TimeSpan.FromMilliseconds(completionTimeoutMs * 2))));
replacedert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
}
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/default.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.UTF8, encoding);
replacedert.Equal(new[]
{
$"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This should get through.",
""
}, lines);
}
finally
{
Directory.Delete(logPath, recursive: true);
}
}
19
Source : LoggingTest.cs
with MIT License
from adams85
with MIT License
from adams85
private async Task LoggingToPhysicalUsingDICore(LogFileAccessMode accessMode)
{
var logsDirName = Guid.NewGuid().ToString("D");
var configData = new Dictionary<string, string>
{
[$"{nameof(FileLoggerOptions.BasePath)}"] = logsDirName,
[$"{nameof(FileLoggerOptions.FileEncodingName)}"] = "UTF-16",
[$"{nameof(FileLoggerOptions.DateFormat)}"] = "yyMMdd",
[$"{nameof(FileLoggerOptions.FileAccessMode)}"] = accessMode.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.Path)}"] = "logger-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File"] = LogLevel.None.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.Path)}"] = "test-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File.Test"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.None.ToString(),
};
var cb = new ConfigurationBuilder();
cb.AddInMemoryCollection(configData);
IConfigurationRoot config = cb.Build();
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
var fileProvider = new PhysicalFileProvider(tempPath);
var cts = new CancellationTokenSource();
var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEventReceived = false;
context.DiagnosticEvent += _ => diagnosticEventReceived = true;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o => o.FileAppender = new PhysicalFileAppender(fileProvider)));
services.Configure<FileLoggerOptions>(config);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
var ex = new Exception();
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();
logger1.LogInformation("This is a nice logger.");
using (logger1.BeginScope("SCOPE"))
{
logger1.LogWarning(1, "This is a smart logger.");
logger1.LogTrace("This won't make it.");
using (logger1.BeginScope("NESTED SCOPE"))
{
ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
ILogger logger2 = loggerFactory.CreateLogger("X");
logger2.LogError(0, ex, "Some failure!");
}
}
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.False(diagnosticEventReceived);
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"info: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a nice logger.",
$"warn: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a smart logger.",
""
}, lines);
logFile = fileProvider.GetFileInfo(
$"{logsDirName}/logger-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"fail: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" Some failure!",
}
.Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
.Append(""), lines);
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
19
Source : LoggingTest.cs
with MIT License
from adams85
with MIT License
from adams85
[Fact]
public async Task LoggingToPhysicalUsingDIAndExpectingDiagnosticEvents()
{
var logsDirName = Guid.NewGuid().ToString("D");
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
var fileProvider = new PhysicalFileProvider(tempPath);
var cts = new CancellationTokenSource();
var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEvents = new List<IFileLoggerDiagnosticEvent>();
context.DiagnosticEvent += diagnosticEvents.Add;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o =>
{
o.FileAppender = new PhysicalFileAppender(fileProvider);
o.BasePath = logsDirName;
o.FileAccessMode = LogFileAccessMode.KeepOpen;
o.Files = new[]
{
new LogFileOptions
{
Path = "<invalid_filename>.log"
}
};
}));
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();
logger1.LogInformation("This is a nice logger.");
logger1.LogWarning(1, "This is a smart logger.");
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.NotEmpty(diagnosticEvents);
replacedert.All(diagnosticEvents, e =>
{
replacedert.IsType<FileLoggerDiagnosticEvent.LogEntryWriteFailed>(e);
replacedert.IsType<FileLoggerProcessor>(e.Source);
replacedert.NotNull(e.FormattableMessage);
replacedert.NotNull(e.Exception);
});
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
19
Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string GetStorageContainerName(OrganizationServiceContext context)
{
var containerName = context.GetSettingValueByName(StorageContainerSetting);
return (string.IsNullOrEmpty(containerName)
? ((WhoAmIResponse)context.Execute(new WhoAmIRequest())).OrganizationId.ToString("N")
: containerName).ToLowerInvariant();
}
19
Source : AnnotationDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private void CopyBlob(IAnnotation note, IEnumerable<Tuple<Guid, Guid>> newNoteInfos)
{
var azureBlob = note.FileAttachment as AzureAnnotationFile;
if (azureBlob == null)
{
return;
}
var fileName = azureBlob.FileName;
var fromBlob = azureBlob.BlockBlob;
if (fromBlob.Exists())
{
var context = _dependencies.GetServiceContextForWrite();
foreach (var newNoteInfo in newNoteInfos)
{
var newNoteId = newNoteInfo.Item2;
var storageAccount = GetStorageAccount(context);
var container = GetBlobContainer(storageAccount, _containerName);
var toBlob = container.GetBlockBlobReference("{0:N}/{1}".FormatWith(newNoteId.ToString("N"), fileName));
toBlob.DeleteIfExists();
toBlob.StartCopy(fromBlob);
var azureFile = note.FileAttachment as AzureAnnotationFile;
var enreplacedy = new Enreplacedy("annotation")
{
Id = newNoteId
};
var fileMetadata = new
{
Name = azureFile.FileName,
Type = azureFile.MimeType,
Size = (ulong)azureFile.FileSize,
Url = toBlob.Uri.AbsoluteUri
};
enreplacedy.SetAttributeValue("doreplacedentbody",
Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
context.Attach(enreplacedy);
context.SaveChanges();
}
}
}
See More Examples