Here are the examples of the csharp api System.DateTime.ToString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
5505 Examples
19
Source : Log.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static string GetLogFileName(string type)
{
return string.Format("{0}-{1}.log", type, DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss"));
}
19
Source : TableColumn.Types.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public override string Readreplacedtring(ISqDataRecordReader recordReader)
{
var value = this.ReadNullable(recordReader);
if (value == null)
{
throw new SqExpressException($"Null value is not expected in non nullable column '{this.ColumnName.Name}'");
}
return this.IsDate ? value.Value.ToString("yyyy-MM-dd") : value.Value.ToString("yyyy-MM-ddTHH:mm:ss.fff");
}
19
Source : TableColumn.Types.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public override string? Readreplacedtring(ISqDataRecordReader recordReader)
{
var value = this.Read(recordReader);
return value == null ? null : this.IsDate ? value.Value.ToString("yyyy-MM-dd") : value.Value.ToString("yyyy-MM-ddTHH:mm:ss.fff");
}
19
Source : ExprPlainWriter.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public void VisitPlainProperty(string name, DateTime? value, int ctx)
{
if (value != null)
{
string ts = value.Value.ToString("yyyy-MM-ddTHH:mm:ss.fff");
this._buffer.Add(this._factory(ctx, ctx, null, false, name, ts));
}
}
19
Source : TableColumnsTest.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
[Test]
public void TestDateTime()
{
replacedert.AreEqual(SqQueryBuilder.SqlType.DateTime().GetType(), this.Table.ColDateTime.SqlType.GetType());
replacedert.AreEqual("[AT].[ColDateTime]", this.Table.ColDateTime.ToSql());
replacedert.IsFalse(this.Table.ColDateTime.IsNullable);
DerivedTable dt = new DerivedTable();
var customColumn = this.Table.ColDateTime.AddToDerivedTable(dt);
replacedert.AreEqual(this.Table.ColDateTime.ColumnName, customColumn.ColumnName);
replacedert.IsTrue(dt.Columns.Contains(customColumn));
var customColumn2 = this.Table.ColDateTime.ToCustomColumn(this.NewSource);
replacedert.AreEqual(this.Table.ColDateTime.ColumnName, customColumn2.ColumnName);
var reader = new Mock<ISqDataRecordReader>();
this.Table.ColDateTime.Read(reader.Object);
customColumn.Read(reader.Object);
reader.Verify(r => r.GetDateTime(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));
var date1 = new DateTime(2021, 10, 21, 9, 25, 37);
var dateString1 = date1.ToString("yyyy-MM-ddTHH:mm:ss.fff");
replacedert.Throws<SqExpressException>(() => this.Table.ColDateTime.Readreplacedtring(reader.Object));
reader.Setup(r => r.GetNullableDateTime(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(date1);
replacedert.AreEqual(dateString1, this.Table.ColDateTime.Readreplacedtring(reader.Object));
replacedert.AreEqual($"'{dateString1}'", this.Table.ColDateTime.FromString(dateString1).ToSql());
replacedert.Throws<SqExpressException>(() => this.Table.ColDateTime.FromString(null));
var date2 = new DateTime(2021, 10, 21);
var dateString2 = date2.ToString("yyyy-MM-dd");
var dateString2Full = date2.ToString("yyyy-MM-ddTHH:mm:ss.fff");
reader.Setup(r => r.GetNullableDateTime(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(date2);
replacedert.AreEqual(dateString2Full, this.Table.ColDateTime.Readreplacedtring(reader.Object));
replacedert.AreEqual($"'{dateString2}'", this.Table.ColDateTime.FromString(dateString2).ToSql());
replacedert.Throws<SqExpressException>(() => this.Table.ColDateTime.FromString(null));
}
19
Source : TableColumnsTest.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
[Test]
public void TestNullableDateTime()
{
replacedert.AreEqual(SqQueryBuilder.SqlType.DateTime().GetType(), this.Table.ColNullableDateTime.SqlType.GetType());
replacedert.AreEqual("[AT].[ColNullableDateTime]", this.Table.ColNullableDateTime.ToSql());
replacedert.IsTrue(this.Table.ColNullableDateTime.IsNullable);
DerivedTable dt = new DerivedTable();
var customColumn = this.Table.ColNullableDateTime.AddToDerivedTable(dt);
replacedert.AreEqual(this.Table.ColNullableDateTime.ColumnName, customColumn.ColumnName);
replacedert.IsTrue(dt.Columns.Contains(customColumn));
var customColumn2 = this.Table.ColNullableDateTime.ToCustomColumn(this.NewSource);
replacedert.AreEqual(this.Table.ColNullableDateTime.ColumnName, customColumn2.ColumnName);
var reader = new Mock<ISqDataRecordReader>();
this.Table.ColNullableDateTime.Read(reader.Object);
customColumn.Read(reader.Object);
reader.Verify(r => r.GetNullableDateTime(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));
var date = new DateTime(2021, 10, 21, 9, 25, 37);
var dateString = date.ToString("yyyy-MM-ddTHH:mm:ss.fff");
replacedert.IsNull(this.Table.ColNullableDateTime.Readreplacedtring(reader.Object));
reader.Setup(r => r.GetNullableDateTime(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(date);
replacedert.AreEqual(dateString, this.Table.ColNullableDateTime.Readreplacedtring(reader.Object));
replacedert.AreEqual($"'{dateString}'", this.Table.ColNullableDateTime.FromString(dateString).ToSql());
replacedert.AreEqual("NULL", this.Table.ColNullableDateTime.FromString(null).ToSql());
}
19
Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054
with GNU General Public License v3.0
from 0xC0000054
private DialogResult ProcessOutputImages()
{
DialogResult result = DialogResult.Cancel;
OutputImageState state = server.OutputImageState;
if (state.Error != null)
{
ShowErrorMessage(state.Error);
}
else
{
IReadOnlyList<Surface> outputImages = state.OutputImages;
if (outputImages.Count > 1)
{
if (!string.IsNullOrWhiteSpace(outputFolder))
{
folderBrowserDialog.SelectedPath = outputFolder;
}
if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
{
outputFolder = folderBrowserDialog.SelectedPath;
try
{
OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
surface?.Dispose();
surface = null;
result = DialogResult.OK;
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (SecurityException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
}
else
{
Surface output = outputImages[0];
if (output.Size == EnvironmentParameters.SourceSurface.Size)
{
if (surface == null)
{
surface = new Surface(EnvironmentParameters.SourceSurface.Width, EnvironmentParameters.SourceSurface.Height);
}
surface.CopySurface(output);
result = DialogResult.OK;
}
else
{
if (surface != null)
{
surface.Dispose();
surface = null;
}
// Place the full image on the clipboard when the size does not match the Paint.NET layer
// and prompt the user to save it.
// The resized image will not be copied to the Paint.NET canvas.
Services.GetService<IClipboardService>().SetImage(output);
resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
if (resizedImageSaveDialog.ShowDialog(this) == DialogResult.OK)
{
string resizedImagePath = resizedImageSaveDialog.FileName;
try
{
using (Bitmap bitmap = output.CreateAliasedBitmap())
{
bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
}
result = DialogResult.OK;
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (SecurityException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
}
}
FinishTokenUpdate();
}
return result;
}
19
Source : GmicEffect.cs
with GNU General Public License v3.0
from 0xC0000054
with GNU General Public License v3.0
from 0xC0000054
protected override void OnSetRenderInfo(EffectConfigToken parameters, RenderArgs dstArgs, RenderArgs srcArgs)
{
if (repeatEffect)
{
GmicConfigToken token = (GmicConfigToken)parameters;
if (token.Surface != null)
{
token.Surface.Dispose();
token.Surface = null;
}
if (File.Exists(GmicConfigDialog.GmicPath))
{
try
{
using (GmicPipeServer server = new GmicPipeServer())
{
List<GmicLayer> layers = new List<GmicLayer>();
Surface clipboardSurface = null;
try
{
// Some G'MIC filters require the image to have more than one layer.
// Because use Paint.NET does not currently support Effect plug-ins accessing
// other layers in the doreplacedent, allowing the user to place the second layer on
// the clipboard is supported as a workaround.
clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();
if (clipboardSurface != null)
{
layers.Add(new GmicLayer(clipboardSurface, true));
clipboardSurface = null;
}
}
finally
{
if (clipboardSurface != null)
{
clipboardSurface.Dispose();
}
}
layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));
server.AddLayers(layers);
server.Start();
string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0} reapply", server.FullPipeName);
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo(GmicConfigDialog.GmicPath, arguments);
process.Start();
process.WaitForExit();
if (process.ExitCode == GmicExitCode.Ok)
{
OutputImageState state = server.OutputImageState;
if (state.Error != null)
{
ShowErrorMessage(state.Error);
}
else
{
IReadOnlyList<Surface> outputImages = state.OutputImages;
if (outputImages.Count > 1)
{
using (PlatformFolderBrowserDialog folderBrowserDialog = new PlatformFolderBrowserDialog())
{
folderBrowserDialog.ClreplacedicFolderBrowserDescription = Resources.ClreplacedicFolderBrowserDescription;
folderBrowserDialog.VistaFolderBrowserreplacedle = Resources.VistaFolderBrowserreplacedle;
if (!string.IsNullOrWhiteSpace(token.OutputFolder))
{
folderBrowserDialog.SelectedPath = token.OutputFolder;
}
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
string outputFolder = folderBrowserDialog.SelectedPath;
try
{
OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (SecurityException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
}
}
else
{
Surface output = outputImages[0];
if (output.Width == srcArgs.Surface.Width && output.Height == srcArgs.Surface.Height)
{
token.Surface = output.Clone();
}
else
{
// Place the full image on the clipboard when the size does not match the Paint.NET layer
// and prompt the user to save it.
// The resized image will not be copied to the Paint.NET canvas.
Services.GetService<IClipboardService>().SetImage(output);
using (PlatformFileSaveDialog resizedImageSaveDialog = new PlatformFileSaveDialog())
{
resizedImageSaveDialog.Filter = Resources.ResizedImageSaveDialogFilter;
resizedImageSaveDialog.replacedle = Resources.ResizedImageSaveDialogreplacedle;
resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
if (resizedImageSaveDialog.ShowDialog() == DialogResult.OK)
{
string resizedImagePath = resizedImageSaveDialog.FileName;
try
{
using (Bitmap bitmap = output.CreateAliasedBitmap())
{
bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
}
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (SecurityException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
}
}
}
}
}
else
{
switch (process.ExitCode)
{
case GmicExitCode.ImageTooLargeForX86:
ShowErrorMessage(Resources.ImageTooLargeForX86);
break;
}
}
}
}
}
catch (ArgumentException ex)
{
ShowErrorMessage(ex);
}
catch (ExternalException ex)
{
ShowErrorMessage(ex);
}
catch (IOException ex)
{
ShowErrorMessage(ex);
}
catch (UnauthorizedAccessException ex)
{
ShowErrorMessage(ex);
}
}
else
{
ShowErrorMessage(Resources.GmicNotFound);
}
}
base.OnSetRenderInfo(parameters, dstArgs, srcArgs);
}
19
Source : OutputImageUtil.cs
with GNU General Public License v3.0
from 0xC0000054
with GNU General Public License v3.0
from 0xC0000054
public static void SaveAllToFolder(IReadOnlyList<Surface> outputImages, string outputFolder)
{
if (outputImages is null)
{
ExceptionUtil.ThrowArgumentNullException(nameof(outputImages));
}
if (outputFolder is null)
{
ExceptionUtil.ThrowArgumentNullException(nameof(outputFolder));
}
DirectoryInfo directoryInfo = new DirectoryInfo(outputFolder);
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
string currentTime = DateTime.Now.ToString("yyyyMMdd-THHmmss");
for (int i = 0; i < outputImages.Count; i++)
{
string imageName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}.png", currentTime, i);
string path = Path.Combine(outputFolder, imageName);
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
using (System.Drawing.Bitmap image = outputImages[i].CreateAliasedBitmap())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
}
}
}
}
19
Source : Log.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
private static void LogInternal(Exception e, string message, LogLevel level, ConsoleColor foregroundColor, ConsoleColor? backgroundColor = null)
{
try
{
#if DEBUG
const LogLevel minLevel = LogLevel.TRACE;
#else
const LogLevel minLevel = LogLevel.DEBUG;
#endif
if (level >= minLevel && message != null)
{
Console.ForegroundColor = foregroundColor;
if (backgroundColor is ConsoleColor bg)
Console.BackgroundColor = bg;
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss ") + message);
Console.ResetColor();
}
if (FileLog != null)
{
if (message != null)
FileLog.WriteLine($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}\t{(long)Timer.Elapsed.TotalMilliseconds}\t{level}\t{message}");
if (e != null)
FileLog.WriteLine(e.ToString());
FileLog.Flush();
}
}
catch { }
}
19
Source : ExpressionResolver.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private static void ResolveInForGeneric(StringBuilder sqlBuilder, string columnName, Expression exp, Type valueType, bool notContainer = false)
{
var value = ResolveDynamicInvoke(exp);
var isValueType = false;
var list = new List<string>();
if (valueType.IsEnum)
{
isValueType = true;
var valueList = (IEnumerable)value;
if (valueList != null)
{
foreach (var c in valueList)
{
list.Add(Enum.Parse(valueType, c.ToString()!).ToInt().ToString());
}
}
}
else
{
var typeName = valueType.Name;
switch (typeName)
{
case "Guid":
if (value is IEnumerable<Guid> guidValues)
{
foreach (var c in guidValues)
{
list.Add(c.ToString());
}
}
break;
case "DateTime":
if (value is IEnumerable<DateTime> dateTimeValues)
{
foreach (var c in dateTimeValues)
{
list.Add(c.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
break;
case "Byte":
isValueType = true;
if (value is IEnumerable<byte> byteValues)
{
foreach (var c in byteValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Char":
if (value is IEnumerable<char> charValues)
{
foreach (var c in charValues)
{
list.Add(c.ToString());
}
}
break;
case "Int16":
isValueType = true;
if (value is IEnumerable<short> shortValues)
{
foreach (var c in shortValues)
{
list.Add(c.ToString());
}
}
break;
case "Int32":
isValueType = true;
if (value is IEnumerable<int> intValues)
{
foreach (var c in intValues)
{
list.Add(c.ToString());
}
}
break;
case "Int64":
isValueType = true;
if (value is IEnumerable<long> longValues)
{
foreach (var c in longValues)
{
list.Add(c.ToString());
}
}
break;
case "Double":
isValueType = true;
if (value is IEnumerable<double> doubleValues)
{
foreach (var c in doubleValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Single":
isValueType = true;
if (value is IEnumerable<float> floatValues)
{
foreach (var c in floatValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Decimal":
isValueType = true;
if (value is IEnumerable<decimal> decimalValues)
{
foreach (var c in decimalValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
}
}
if (list!.Count < 1)
return;
sqlBuilder.Append(columnName);
sqlBuilder.Append(notContainer ? " NOT IN (" : " IN (");
//值类型不带引号
if (isValueType)
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("{0}", list[i]);
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
else
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("'{0}'", list[i].Replace("'", "''"));
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
sqlBuilder.Append(")");
}
19
Source : DateTimeExtensions.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public static string Format(this DateTime dateTime, string format = null)
{
if (format.IsNull())
format = "yyyy-MM-dd HH:mm:ss";
return dateTime.ToString(format);
}
19
Source : FileUploadProvider.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public async Task<IResultModel<FileDescriptor>> Upload(FileUploadModel model, CancellationToken cancellationToken = default)
{
Check.NotNull(model, nameof(model), "file upload model is null");
Check.NotNull(model.StorageRootDirectory, nameof(model.StorageRootDirectory), "the file storage root directory is null");
var result = new ResultModel<FileDescriptor>();
if (model.FormFile == null)
return result.Failed("请选择文件!");
var size = model.FormFile.Length;
//验证文件大小
if (model.MaxSize > 0 && model.MaxSize < size)
return result.Failed($"文件大小不能超过{new FileSize(model.MaxSize).ToString()}");
var name = model.FileName.IsNull() ? model.FormFile.FileName : model.FileName;
var descriptor = new FileDescriptor(name, size);
//验证扩展名
if (model.LimitExtensions != null && !model.LimitExtensions.Any(m => m.EqualsIgnoreCase(descriptor.Extension)))
return result.Failed($"文件格式无效,请上传{model.LimitExtensions.Aggregate((x, y) => x + "," + y)}格式的文件");
//按照日期来保存文件
var date = DateTime.Now;
descriptor.DirectoryName = Path.Combine(model.StorageRootDirectory, date.ToString("yyyy"), date.ToString("MM"), date.ToString("dd"));
//创建目录
if (!Directory.Exists(descriptor.DirectoryName))
{
Directory.CreateDirectory(descriptor.DirectoryName);
}
//生成文件存储名称
descriptor.StorageName = $"{Guid.NewGuid().ToString().Replace("-", "")}.{descriptor.Extension}";
//写入
await using var stream = new FileStream(descriptor.FullName, FileMode.Create);
//计算MD5
if (model.CalculateMd5)
{
descriptor.Md5 = _md5Encrypt.Encrypt(stream);
}
await model.FormFile.CopyToAsync(stream, cancellationToken);
return result.Success(descriptor);
}
19
Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void stb_home_url_Enter(object sender, EventArgs e)
{
string sdir = stb_project_source_dir.Text;
string appname = stb_app_name.Text;
string url = stb_home_url.Text;
if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
try
{
if (get_spboot_port_run)
{
return;
}
get_spboot_port_run = true;
if (!sdir.EndsWith("/"))
{
sdir += "/";
}
string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
ThreadPool.QueueUserWorkItem((a) =>
{
Thread.Sleep(500);
string port = "", ctx = "";
string yml = YSTools.YSFile.readFileToString(targetxml);
if(!string.IsNullOrWhiteSpace(yml)){
string[] lines = yml.Split('\n');
bool find = false;
int index = 0, start = 0;
foreach(string line in lines){
if (line.Trim().StartsWith("server:"))
{
find = true;
start = index;
}
else if(find && line.Trim().StartsWith("port:")){
port = line.Substring(line.IndexOf(":") + 1).Trim();
}
else if (find && line.Trim().StartsWith("context-path:"))
{
ctx = line.Substring(line.IndexOf(":") + 1).Trim();
}
if (index - start > 4 && start > 0)
{
break;
}
index++;
}
}
if (port != "")
{
stb_home_url.BeginInvoke((MethodInvoker)delegate()
{
stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
});
}
get_spboot_port_run = false;
File.Delete(targetxml);
});
}
catch(Exception ex) {
logger.Error("Error", ex);
}
}
}
19
Source : NginxMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void checkTimedTask()
{
var now = DateTime.Now;
String[] dts = null;
string week = "";
foreach (CmdShell cmds in seConfig.CustomShellList)
{
if (cmds.Target == itemConfig.tomcat.Uuid)
{
if (cmds.TaskType == TaskType.Timed)
{
if (null != cmds.ShellList)
{
dts = null;
foreach (TaskShell task in cmds.ShellList)
{
dts = task.DateTime.Split('|');
if (dts[0] == "0")
{// 一次
if (now.ToString("yyyy-MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "1")
{// 每天
if (now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "2")
{// 每周
week = DateTime.Now.DayOfWeek.ToString("d");
if (dts[1].Contains(week) && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "3")
{// 每月
if (now.ToString("dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "4")
{// 每年
if (now.ToString("MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
}
}
}
}
}
}
19
Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void checkTimedTask()
{
var now = DateTime.Now;
String[] dts = null;
string week = "";
foreach (CmdShell cmds in seConfig.CustomShellList)
{
if (cmds.Target == itemConfig.ice.Uuid)
{
if (cmds.TaskType == TaskType.Timed)
{
if (null != cmds.ShellList)
{
dts = null;
foreach (TaskShell task in cmds.ShellList)
{
dts = task.DateTime.Split('|');
if (dts[0] == "0")
{// 一次
if (now.ToString("yyyy-MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "1")
{// 每天
if (now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "2")
{// 每周
week = DateTime.Now.DayOfWeek.ToString("d");
if (dts[1].Contains(week) && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "3")
{// 每月
if (now.ToString("dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "4")
{// 每年
if (now.ToString("MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
}
}
}
}
}
}
19
Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (get_srvxml_run)
{
return;
}
get_srvxml_run = true;
linkLabel1.Enabled = false;
string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
string serverxml = string.Format("{0}config/{1}.xml", l_pro_path.Text, l_appname.Text);
TextEditorForm editor = new TextEditorForm();
editor.Show(this);
editor.LoadRemoteFile(new ShellForm(monitorForm), serverxml, targetxml);
}
catch { }
get_srvxml_run = false;
linkLabel1.Enabled = true;
}
19
Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
void Tomcat_TextChanged(object sender, EventArgs e)
{
string path = stb_tomcat_path.Text;
if (!string.IsNullOrWhiteSpace(path))
{
if (string.IsNullOrWhiteSpace(tomcat_name))
{
try
{
stb_tomcat_name.Text = path.Substring(path.LastIndexOf("/") + 1);
}
catch { }
}
if (string.IsNullOrWhiteSpace(stb_tomcat_port.Text))
{
try
{
if (get_tomcat_port_run)
{
return;
}
get_tomcat_port_run = true;
if (!path.EndsWith("/"))
{
path += "/";
}
string serverxml = path + "conf/server.xml";
string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
ThreadPool.QueueUserWorkItem((a) => {
Thread.Sleep(500);
List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
if(list != null && list.Count > 0){
List<Hashtable> serviceList = null;
string port = null;
foreach(Hashtable one in list){
if (one["NodeName"].ToString() == "Service")
{
serviceList = (List<Hashtable>) one["ChildList"];
foreach (Hashtable two in serviceList)
{
if (two["NodeName"].ToString() == "Connector")
{
port = two["port"].ToString();
break;
}
}
if(port != null){
break;
}
}
}
stb_tomcat_port.BeginInvoke((MethodInvoker)delegate()
{
stb_tomcat_port.Text = port == null ? "8080" : port;
});
}
get_tomcat_port_run = false;
File.Delete(targetxml);
});
}
catch { }
}
}
}
19
Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
void SrvPath_TextChanged(object sender, EventArgs e)
{
string path = stb_ice_srvpath.Text;
if (!string.IsNullOrWhiteSpace(path))
{
string appname = stb_ice_appname.Text;
if (!string.IsNullOrWhiteSpace(appname) && string.IsNullOrWhiteSpace(stb_ice_ports.Text))
{
try
{
if (get_ice_port_run)
{
return;
}
get_ice_port_run = true;
if (!path.EndsWith("/"))
{
path += "/";
}
string serverxml = string.Format("{0}config/{1}.xml", path, appname);
string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
ThreadPool.QueueUserWorkItem((a) =>
{
Thread.Sleep(500);
List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "icegrid");
if (list != null && list.Count > 0)
{
List<Hashtable> appList = null, nodeList = null;
List<Hashtable> serverList = null;
string ports = "", nodeName = "", serverName = "";
foreach (Hashtable one in list)
{
if (one["NodeName"].ToString() == "application")
{
appList = (List<Hashtable>)one["ChildList"];
foreach (Hashtable two in appList)
{
if (two["NodeName"].ToString() == "node")
{
nodeName = two["name"].ToString();
nodeList = (List<Hashtable>)two["ChildList"];
foreach (Hashtable four in nodeList)
{
if (four["NodeName"].ToString() == "server-instance")
{
ports += "," + four["serverport"].ToString();
}
}
}
if (two["NodeName"].ToString() == "server-template")
{
serverList = (List<Hashtable>)two["ChildList"];
foreach (Hashtable four in serverList)
{
if (four["NodeName"].ToString() == "icebox")
{
serverName = four["id"].ToString();
serverName = serverName.Substring(0, serverName.IndexOf("$")) + "1";
break;
}
}
}
if (ports != "")
{
break;
}
}
}
}
stb_ice_ports.BeginInvoke((MethodInvoker)delegate()
{
stb_ice_servername.Text = serverName;
stb_ice_ports.Text = ports == "" ? "8082" : ports.Substring(1);
});
}
get_ice_port_run = false;
File.Delete(targetxml);
});
}
catch { }
}
}
}
19
Source : NginxMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (get_nginx_conf_run)
{
return;
}
get_nginx_conf_run = true;
linkLabel2.Enabled = false;
string targetxml = MainForm.TEMP_DIR + string.Format("nginx-{0}.conf", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
string serverxml = l_nginx_conf.Text;
TextEditorForm editor = new TextEditorForm();
editor.Show(this);
editor.LoadRemoteFile(new ShellForm(monitorForm), serverxml, targetxml);
}
catch { }
get_nginx_conf_run = false;
linkLabel2.Enabled = true;
}
19
Source : SpringBootMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void checkTimedTask()
{
var now = DateTime.Now;
String[] dts = null;
string week = "";
foreach (CmdShell cmds in seConfig.CustomShellList)
{
if (cmds.Target == itemConfig.spring.Uuid)
{
if (cmds.TaskType == TaskType.Timed)
{
if (null != cmds.ShellList)
{
dts = null;
foreach (TaskShell task in cmds.ShellList)
{
dts = task.DateTime.Split('|');
if (dts[0] == "0")
{// 一次
if (now.ToString("yyyy-MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "1")
{// 每天
if (now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "2")
{// 每周
week = DateTime.Now.DayOfWeek.ToString("d");
if (dts[1].Contains(week) && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "3")
{// 每月
if (now.ToString("dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
else if (dts[0] == "4")
{// 每年
if (now.ToString("MM-dd") == dts[1] && now.ToString("HH:mm:ss") == dts[2])
{
// 执行
runTaskShell(cmds, task);
}
}
}
}
}
}
}
}
19
Source : Program.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
static async Task SendResponseAsync(IHttpRequestResponse request, HttpSender httpSender)
{
if (request.RequestType == RequestType.TCP)
{
var response = new HttpResponse
{
StatusCode = (int)HttpStatusCode.OK,
ResponseReason = HttpStatusCode.OK.ToString(),
Headers = new Dictionary<string, string>
{
{"Date", DateTime.UtcNow.ToString("r")},
{"Content-Type", "text/html; charset=UTF-8" },
},
Body = new MemoryStream(Encoding.UTF8.GetBytes($"<html>\r\n<body>\r\n<h1>Hello, World! {DateTime.Now}</h1>\r\n</body>\r\n</html>"))
};
await httpSender.SendTcpResponseAsync(request, response).ConfigureAwait(false);
}
}
19
Source : HttpUtil.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void HandException(Exception ex, StateObject state)
{
string message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " : " + state.ResponseInfo.RequestInfo.Url + " : " + ex.Message;
if (state.Action != null)
{
state.Action(state.ResponseInfo);
}
logger.Error(message);
}
19
Source : SftpForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void TransfersFileProgress(string id, long precent, long c, long max, int elapsed)
{
try
{
int start = 0, end = Convert.ToInt32(DateTime.Now.ToString("ffff"));
if(TIMEDIC.ContainsKey(id)){
start = TIMEDIC[id];
TIMEDIC[id] = end;
} else {
TIMEDIC.Add(id, end);
}
long startByte = 0, endByte = c;
if (BYTEDIC.ContainsKey(id))
{
startByte = BYTEDIC[id];
BYTEDIC[id] = endByte;
} else {
BYTEDIC.Add(id, endByte);
}
this.BeginInvoke((MethodInvoker)delegate()
{
TransferItem obj = null;
foreach (ListViewItem item in listView3.Items)
{
if (item.Name == id)
{
obj = (TransferItem)item.Tag;
obj.Progress = precent;
item.SubItems[1].Text = TransferStatus.Transfers.ToString();
item.SubItems[2].Text = precent + "%";
item.SubItems[6].Text = Utils.CalculaSpeed(startByte, endByte, max, start, end);
item.SubItems[7].Text = Utils.CalculaTimeLeft(startByte, endByte, max, start, end);
break;
}
}
});
}
catch(Exception ex) {
logger.Error("传输文件的到服务器时异常:" + ex.Message, ex);
ChangeTransferItemStatus("R2L", id, TransferStatus.Failed);
}
}
19
Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public List<JObject> loadTomcatServerProject()
{
List<JObject> itemList = new List<JObject>();
try
{
string serverxml = l_tomcat_path.Text + "conf/server.xml";
string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
List<System.Collections.Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
if (list != null && list.Count > 0)
{
List<System.Collections.Hashtable> serviceList = null;
List<System.Collections.Hashtable> engineList = null;
List<System.Collections.Hashtable> hostList = null;
string port = null, docBase = "", path = "";
JObject json = null;
foreach (System.Collections.Hashtable one in list)
{
if (one["NodeName"].ToString() == "Service")
{
serviceList = (List<System.Collections.Hashtable>)one["ChildList"];
foreach (System.Collections.Hashtable two in serviceList)
{
if (two["NodeName"].ToString() == "Engine")
{
engineList = (List<System.Collections.Hashtable>)two["ChildList"];
foreach (System.Collections.Hashtable three in engineList)
{
if (three["NodeName"].ToString() == "Host")
{
hostList = (List<System.Collections.Hashtable>)three["ChildList"];
foreach (System.Collections.Hashtable four in hostList)
{
if (four["NodeName"].ToString() == "Context")
{
json = new JObject();
docBase = four["docBase"].ToString();
path = four["path"].ToString();
if (!docBase.EndsWith(path))
{
if (docBase.StartsWith("/"))
{
json.Add("path", docBase);
}
else
{
json.Add("path", l_tomcat_path.Text + "webapps/" + docBase);
}
json.Add("name", docBase);
json.Add("url", l_visit_url.Text + "/" + path);
itemList.Add(json);
}
}
}
}
}
break;
}
}
if (port != null)
{
break;
}
}
}
}
File.Delete(targetxml);
}
catch { }
return itemList;
}
19
Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (get_tomcat_xml_run)
{
return;
}
get_tomcat_xml_run = true;
linkLabel2.Enabled = false;
string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
string serverxml = l_xml_path.Text;
TextEditorForm editor = new TextEditorForm();
editor.Show(this);
editor.LoadRemoteFile(new ShellForm(monitorForm), serverxml, targetxml);
}
catch { }
get_tomcat_xml_run = false;
linkLabel2.Enabled = true;
}
19
Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "修改")
{
tb_port.BorderStyle = BorderStyle.FixedSingle;
tb_port.ReadOnly = false;
tb_port.Location = new Point(tb_port.Location.X, tb_port.Location.Y - 2);
button1.Text = "保存";
}
else if (button1.Text == "保存")
{
string port = tb_port.Text;
if (port == itemConfig.tomcat.TomcatPort)
{
label_msg.Text = "端口无变化";
}
else
{
DialogResult dr = MessageBox.Show("修改端口后需要重启Tomcat才能生效,您确定要修改吗?", "操作提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (dr == System.Windows.Forms.DialogResult.OK)
{
button1.Enabled = false;
label_msg.Text = "修改中...";
try
{
string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
string serverxml = l_xml_path.Text;
monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
string content = YSFile.readFileToString(targetxml);
if (null != content)
{
content = content.Replace(itemConfig.tomcat.TomcatPort, port);
YSFile.writeFileByString(targetxml, content);
monitorForm.RunSftpShell(string.Format("put {0} {1}", targetxml, serverxml), false, false);
itemConfig.tomcat.TomcatPort = port;
AppConfig.Instance.SaveConfig(2);
label_msg.Text = "修改成功";
}
}
catch (Exception ex)
{
logger.Error("修改Tomcat端口异常:" + ex.Message, ex);
label_msg.Text = "修改失败";
}
}
else
{
tb_port.Text = itemConfig.tomcat.TomcatPort;
}
}
button1.Enabled = true;
button1.Text = "修改";
tb_port.BorderStyle = BorderStyle.None;
tb_port.ReadOnly = true;
tb_port.Location = new Point(tb_port.Location.X, tb_port.Location.Y + 2);
ControlUtil.delayClearText(new DelayDelegate(labelMsg), 2000);
}
}
19
Source : SftpForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void WriteLog(string flag, string id, string local, string remote)
{
try
{
string log = "";
if (flag == "L2R")
{
log = string.Format("【{0}】 - [{1}] Transfers File To {2},{3} -> {4} ", user.Host, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Remote", local, remote);
}
else
{
log = string.Format("[{0} {1}] Transfers File To {2},{3} -> {4} ", user.Host, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "Local", remote, local);
}
WriteLog2(log);
}
catch(Exception e) {
logger.Error("格式化日志报错", e);
}
}
19
Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listView2.SelectedItems.Count > 0)
{
ListViewItem row = listView2.SelectedItems[0];
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry)row.Tag;
if (!entry.getAttrs().isDir())
{
try
{
string resfile = getCurrDir() + entry.getFilename();
string targetfile = MainForm.TEMP_DIR + string.Format("{0}.file", DateTime.Now.ToString("MMddHHmmss"));
targetfile = targetfile.Replace("\\", "/");
TextEditorForm editor = new TextEditorForm();
editor.Show(this);
editor.LoadRemoteFile(new ShellForm(this), resfile, targetfile);
}
catch { }
}
}
}
19
Source : SftpWinForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void LoadDirFilesToListView(string path, LoadFilesResult result = null)
{
this.BeginInvoke((MethodInvoker)delegate()
{
try
{
DirectoryInfo dire = new DirectoryInfo(path);
if(dire.Exists){
listView1.Items.Clear();
LargeImages.Images.Clear();
SmallImages.Images.Clear();
FileInfo[] files = dire.GetFiles();
DirectoryInfo[] dires = dire.GetDirectories();
Icon icon = null;
ListViewItem item = null;
ListViewItem.ListViewSubItem subItem = null;
LargeImages.Images.Add(Properties.Resources.filen_64px);
LargeImages.Images.Add(Properties.Resources.folder_64px);
SmallImages.Images.Add(Properties.Resources.filen_16px);
SmallImages.Images.Add(Properties.Resources.folder_16px);
int index = 2;
item = new ListViewItem();
item.Text = "..";
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "文件夹";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "";
item.SubItems.Add(subItem);
item.ImageIndex = 1;
listView1.Items.Add(item);
foreach (DirectoryInfo file in dires)
{
item = new ListViewItem();
item.Text = file.Name;
item.Tag = file;
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = "文件夹";
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = file.LastWriteTime.ToString("yyyy-MM-dd, HH:mm:ss");
item.SubItems.Add(subItem);
item.ImageIndex = 1;
listView1.Items.Add(item);
//Console.WriteLine(file.Name + " - " + file.ToString());
}
foreach(FileInfo file in files){
if(file.Extension == ".lnk"){
continue;
}
icon = Icon.ExtractreplacedociatedIcon(file.FullName);
LargeImages.Images.Add(icon.ToBitmap());
SmallImages.Images.Add(icon.ToBitmap());
item = new ListViewItem();
item.Text = file.Name;
item.Tag = file;
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = Utils.getFileSize(file.Length);
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = file.Extension;
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = file.LastWriteTime.ToString("yyyy-MM-dd, HH:mm:ss");
item.SubItems.Add(subItem);
item.ImageIndex = index++;
listView1.Items.Add(item);
//Console.WriteLine(file.Name + " - " + file.ToString());
}
if (null != result)
{
result();
}
}
else
{
MessageBox.Show(this, "目录不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception e)
{
logger.Error("加载数据失败:" + e.Message, e);
}
});
}
19
Source : Object.cs
with MIT License
from 2881099
with MIT License
from 2881099
public override string ToString()
{
return $"{this.Value}, Times: {this.GetTimes}, ThreadId(R/G): {this.LastReturnThreadId}/{this.LastGetThreadId}, Time(R/G): {this.LastReturnTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}/{this.LastGetTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}";
}
19
Source : CentralServerConfigForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private void btn_new_Click(object sender, EventArgs e)
{
string oldName = "";
string msg = "请输入文件名称(不包含.yml后缀)";
InputForm form = new InputForm(msg, oldName, new InputForm.FormResult((newName) =>
{
if (oldName != newName)
{
oldName = newName + ".yml";
string path = cfgDir + "/" + oldName;
YSTools.YSFile.writeFileByString(path, "#.yml File Create By AMShell - " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
listView1.Items.Add(new ListViewItem()
{
Text = oldName,
ImageIndex = 0,
Tag = new YmlFile()
{
remotePath = remoteCfgPath + "/",
remoteName = oldName,
localName = oldName,
localPath = cfgDir + "/",
status = YmlFileState.NoAsync,
correct = true
}
});
}
else
{
MessageBox.Show(this, "文件名称不能为空");
}
}));
form.ShowDialog(this);
}
19
Source : GlobalExtensions.cs
with Apache License 2.0
from 2881099
with Apache License 2.0
from 2881099
public static string ToGmtISO8601(this DateTime time) {
return time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
}
19
Source : IdleBus`1.Test.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static void Test()
{
//超过1分钟没有使用,连续检测2次都这样,就销毁【实例】
var ib = new IdleBus<string, IDisposable>(TimeSpan.FromMinutes(1));
ib.Notice += (_, e) =>
{
var log = $"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e.Log}";
//Trace.WriteLine(log);
Console.WriteLine(log);
};
ib.Register("key1", () => new ManualResetEvent(false));
ib.Register("key2", () => new AutoResetEvent(false));
var item = ib.Get("key2") as AutoResetEvent;
//获得 key2 对象,创建
item = ib.Get("key2") as AutoResetEvent;
//获得 key2 对象,已创建
int num1 = ib.UsageQuanreplacedy;
//【实例】有效数量(即已经创建了的),后台定时清理不活跃的【实例】,此值就会减少
ib.Dispose();
}
19
Source : FreeSqlCloud.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal void _distributedTraceCall(string log)
{
DistributeTrace?.Invoke($"{DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")} 【{DistributeKey}】{log}");
}
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 GetVersion()
{
try
{
string location = GetExePath();
return string.Format("v2rayN - V{0} - {1}",
FileVersionInfo.GetVersionInfo(location).FileVersion.ToString(),
File.GetLastWriteTime(location).ToString("yyyy/MM/dd"));
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
return string.Empty;
}
}
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static void SaveLog(string strreplacedle, Exception ex)
{
try
{
string path = Path.Combine(StartupPath(), "guiLogs");
string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!File.Exists(FilePath))
{
FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
FsCreate.Close();
FsCreate.Dispose();
}
FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
StreamWriter SwWrite = new StreamWriter(FsWrite);
string strContent = ex.ToString();
SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
SwWrite.Write(strContent);
SwWrite.WriteLine(Environment.NewLine);
SwWrite.WriteLine(" ");
SwWrite.Flush();
SwWrite.Close();
}
catch { }
}
19
Source : MainFormHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public void BackupGuiNConfig(Config config, bool auto = false)
{
string fileName = string.Empty;
if (auto)
{
fileName = Utils.GetTempPath($"guiNConfig{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.json");
}
else
{
SaveFileDialog fileDialog = new SaveFileDialog
{
Filter = "guiNConfig|*.json",
FilterIndex = 2,
RestoreDirectory = true
};
if (fileDialog.ShowDialog() != DialogResult.OK)
{
return;
}
fileName = fileDialog.FileName;
}
if (Utils.IsNullOrEmpty(fileName))
{
return;
}
var ret = Utils.ToJsonFile(config, fileName);
if (!auto)
{
if (ret == 0)
{
UI.Show(UIRes.I18N("OperationSuccess"));
}
else
{
UI.ShowWarning(UIRes.I18N("OperationFailed"));
}
}
}
19
Source : ProfileClientTests.cs
with MIT License
from 4egod
with MIT License
from 4egod
[TestMethod]
public void SetStartButtonPostbackTest()
{
bool result = client.SetStartButtonPostback("#start_postback#"+DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss")).Result;
Trace.WriteLine(("Success: {0}".Format(result)));
}
19
Source : Fixtures.cs
with MIT License
from 8T4
with MIT License
from 8T4
public static arrange The_time_is_before_close_of_trading(this arrange fixtures)
{
var date = DateTime.Today.ToString("yyyy-MM-dd");
return fixtures.Setup((f) => f.Stocks.SetTimeToCloseTrading($"{date} 23:59:59"));
}
19
Source : ZUART.cs
with MIT License
from a2633063
with MIT License
from a2633063
private void AddContent(string content)
{
this.BeginInvoke(new MethodInvoker(delegate
{
if (chkAutoLine.Checked && txtShowData.Text.Length > 0)
{
txtShowData.AppendText("\r\n");
if (chkShowTime.Checked)
{
txtShowData.AppendText("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "】" + "\r\n");
}
}
txtShowData.AppendText(content);
}));
}
19
Source : CamerasManager.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
void Start() {
if(enableVideoSave) {
Time.captureFramerate = frameRate;
if(cameras.Count > 0) {
// crea la cartella principale nella quale verranno create una sottocartella per ogni telecamera
folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
if(System.IO.Directory.Exists(folder)) {
System.IO.Directory.Delete(folder, true);
}
System.IO.Directory.CreateDirectory(folder);
// crea una sottocartella per ogni telecamera
for(int i = 0; i < cameras.Count; ++i) {
if(cameras[i].Camera) {
cameras[i].Folder = string.Format("{0}/{1}_{2}x{3}_{4}fps",
folder,
cameras[i].Name,
cameras[i].Camera.rect.width,
cameras[i].Camera.rect.height,
frameRate);
System.IO.Directory.CreateDirectory(cameras[i].Folder);
}
}
}
}
}
19
Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static byte[] FromAudioClip(AudioClip audioClip, out string filepath, bool saveAsFile = true, string dirname = "recordings")
{
MemoryStream stream = new MemoryStream();
const int headerSize = 44;
// get bit depth
UInt16 bitDepth = 16; //BitDepth (audioClip);
// NB: Only supports 16 bit
//Debug.replacedertFormat (bitDepth == 16, "Only converting 16 bit is currently supported. The audio clip data is {0} bit.", bitDepth);
// total file size = 44 bytes for header format and audioClip.samples * factor due to float to Int16 / sbyte conversion
int fileSize = audioClip.samples * BlockSize_16Bit + headerSize; // BlockSize (bitDepth)
// chunk descriptor (riff)
WriteFileHeader(ref stream, fileSize);
// file header (fmt)
WriteFileFormat(ref stream, audioClip.channels, audioClip.frequency, bitDepth);
// data chunks (data)
WriteFileData(ref stream, audioClip, bitDepth);
byte[] bytes = stream.ToArray();
// Validate total bytes
Debug.replacedertFormat(bytes.Length == fileSize, "Unexpected AudioClip to wav format byte count: {0} == {1}", bytes.Length, fileSize);
// Save file to persistant storage location
if (saveAsFile)
{
filepath = string.Format("{0}/{1}/{2}.{3}", Application.persistentDataPath, dirname, DateTime.UtcNow.ToString("yyMMdd-HHmmss-fff"), "wav");
Directory.CreateDirectory(Path.GetDirectoryName(filepath));
File.WriteAllBytes(filepath, bytes);
//Debug.Log ("Auto-saved .wav file: " + filepath);
}
else
{
filepath = null;
}
stream.Dispose();
return bytes;
}
19
Source : Tracking.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
void Start()
{
ss = 0;
if (SaveVideoElaborated)
{
folder = folder + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss");
if (System.IO.Directory.Exists(folder))
{
System.IO.Directory.Delete(folder, true);
}
System.IO.Directory.CreateDirectory(folder);
}
x_coordinate = 0;
y_coordinate = 0;
skipFrame = 0;
roiRect = null;
termination = new TermCriteria(TermCriteria.EPS | TermCriteria.COUNT, 10, 1);
#if UNITY_WEBGL && !UNITY_EDITOR
StartCoroutine(Utils.getFilePathAsync("blobparams.yml", (result) => {
blobparams_yml_filepath = result;
}));
#else
blobparams_yml_filepath = Utils.getFilePath("blobparams.yml");
//Debug.Log(blobparams_yml_filepath);
#endif
}
19
Source : Helper.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public static string ToSQLDateTime(this DateTime pDate)
{
return pDate.ToString("yyyy-MM-dd HH:mm:ss");
}
19
Source : Helper.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public static string ToSQLDate(this DateTime pDate)
{
return pDate.ToString("yyyy-MM-dd");
}
19
Source : InsertTests.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
[Fact]
public void InsertWithDefaultCreatedUpdatedOn()
{
Country country = new Country
{
Name = "India",
ShortCode = "IN",
Independence = new DateTime(1947, 8, 15),//15th August, 1947
CreatedBy = Fixture.CurrentUserId,
};
Repository<Country> countryRepo = new Repository<Country>(Fixture.Connection);
var id = countryRepo.Add(country);
replacedert.Equal(DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), countryRepo.ReadOne<DateTime>("CreatedOn", id).ToString("dd-MM-yyyy hh:mm:ss"));
replacedert.Equal(DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), countryRepo.ReadOne<DateTime>("UpdatedOn", id).ToString("dd-MM-yyyy hh:mm:ss"));
}
19
Source : UpdateTests.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
[Fact]
public void UpdateDefaultUpdatedOn()
{
Country country = new Country
{
Name = "India",
ShortCode = "IN",
Independence = new DateTime(1947, 8, 15),
CreatedBy = Fixture.CurrentUserId
};
Repository<Country> countryRepo = new Repository<Country>(Fixture.Connection);
var id = countryRepo.Add(country);
country = countryRepo.ReadOne(id);
country.Independence = null;
countryRepo.Update(country, "independence");
replacedert.Equal(DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), countryRepo.ReadOne<DateTime>("UpdatedOn", id).ToString("dd-MM-yyyy hh:mm:ss"));
}
19
Source : Program.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
var date = DateTime.Now.ToString("yyyy-MM-dd-hh-mm");
var fileName = Path.Combine(path, "!UnhandledException" + date + ".log");
File.WriteAllText(fileName, e.ExceptionObject.ToString(), Encoding.UTF8);
}
19
Source : Program.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var date = DateTime.Now.ToString("yyyy-MM-dd-hh-mm");
var fileName = Path.Combine(Directory.GetCurrentDirectory(), "!UnhandledException" + date + ".log");
File.WriteAllText(fileName, e.ExceptionObject.ToString(), Encoding.UTF8);
}
See More Examples