Here are the examples of the csharp api System.DateTime.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1439 Examples
19
Source : PropVariantFacade.cs
with MIT License
from Bassman2
with MIT License
from Bassman2
public override string ToString()
{
switch (this.Value.vt)
{
case PropVariantType.VT_LPSTR:
return Marshal.PtrToStringAnsi(this.Value.ptrVal);
case PropVariantType.VT_LPWSTR:
return Marshal.PtrToStringUni(this.Value.ptrVal);
case PropVariantType.VT_BSTR:
return Marshal.PtrToStringBSTR(this.Value.ptrVal);
case PropVariantType.VT_CLSID:
return ToGuid().ToString();
case PropVariantType.VT_DATE:
return ToDate().ToString();
case PropVariantType.VT_BOOL:
return ToBool().ToString();
case PropVariantType.VT_INT:
case PropVariantType.VT_I1:
case PropVariantType.VT_I2:
case PropVariantType.VT_I4:
return ToInt().ToString();
case PropVariantType.VT_UINT:
case PropVariantType.VT_UI1:
case PropVariantType.VT_UI2:
case PropVariantType.VT_UI4:
return ToUInt().ToString();
case PropVariantType.VT_I8:
return ToLong().ToString();
case PropVariantType.VT_UI8:
return ToUlong().ToString();
case PropVariantType.VT_ERROR:
Debug.WriteLine($"VT_ERROR: 0x{this.Value.errorCode:X}");
return "";
default:
return "";
}
}
19
Source : MDC.cs
with MIT License
from Battlerax
with MIT License
from Battlerax
public void SendBoloToClient(Player player, Bolo bolo)
{
//boloId, officer, time, priority, info
NAPI.ClientEvent.TriggerClientEvent(player, "addBolo", bolo.Id, bolo.ReportingOfficer, bolo.Time.ToString(),
bolo.Priority, bolo.Info);
}
19
Source : MDC.cs
with MIT License
from Battlerax
with MIT License
from Battlerax
public void Send911ToClient(Player player, EmergencyCall call)
{
NAPI.ClientEvent.TriggerClientEvent(player, "add911", call.PhoneNumber, call.Time.ToString(), call.Info, call.Location);
}
19
Source : ExampleSavePosition.cs
with MIT License
from BayatGames
with MIT License
from BayatGames
void Start()
{
_encodePreplacedword = "12345678910abcdef12345678910abcdef";
SaveGame.EncodePreplacedword = _encodePreplacedword;
SaveGame.Encode = true;
SaveGame.Serializer = new SaveGameFree.Serializers.SaveGameBinarySerializer();
StorageSG ssg = new StorageSG();
SaveGame.Save<StorageSG>("pizza2", ssg);
StorageSG ssgLoaded = SaveGame.Load<StorageSG>("pizza2");
Debug.Log(ssgLoaded.myDateTime.ToLocalTime().ToString());
if (loadOnStart)
{
Load();
}
}
19
Source : Form1.cs
with GNU General Public License v3.0
from BeanBagKing
with GNU General Public License v3.0
from BeanBagKing
private void FindEventsButton_Click(object sender, EventArgs e)
{
FindEventsButton.Enabled = false;
if (StartInput.Text == "" || EndInput.Text == "") // Check to make sure times are populated
{
StatusOutput.Text = "Missing Start or End Time!";
StatusOutput.ForeColor = System.Drawing.Color.Red;
}
else if (!DateTime.TryParse(StartInput.Text, out DateTime temp)) // And that the start time is valid
{
StatusOutput.Text = "Invalid Start Time";
StatusOutput.ForeColor = System.Drawing.Color.Red;
}
else if (!DateTime.TryParse(EndInput.Text, out DateTime temp2)) // And that the end time is valid
{
StatusOutput.Text = "Invalid End Time";
StatusOutput.ForeColor = System.Drawing.Color.Red;
}
else // If everything is valid, run!
{
// Variables we will need
DateTime StartTime = DateTime.ParseExact(StartInput.Text, "MM/dd/yyyy HH:mm:ss", null); // Needed for filter query
DateTime EndTime = DateTime.ParseExact(EndInput.Text, "MM/dd/yyyy HH:mm:ss", null); // Needed for filter query
string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Needed for file name
string RunTime = DateTime.Now.ToString("yyyyMMdd_HHmmss"); // Needed for file name
EventLogSession Session = new EventLogSession();
var Logs = Session.GetLogNames().ToList();
var pathType = PathType.LogName;
if (currentSystem.Checked == true)
{
Logs = Session.GetLogNames().ToList();
pathType = PathType.LogName;
} else if (System.IO.Directory.Exists(currentPath.Text))
{
Logs = System.IO.Directory.GetFiles(currentPath.Text, "*.evtx").ToList();
pathType = PathType.FilePath;
} else
{
MessageBox.Show("Something Wrong:\nYou likely selected an invalid path");
FindEventsButton.Enabled = true;
return;
}
var query = string.Format(@"*[System[TimeCreated[@SystemTime >= '{0}']]] and *[System[TimeCreated[@SystemTime <= '{1}']]]", StartTime.ToUniversalTime().ToString("o"), EndTime.ToUniversalTime().ToString("o"));
List<Record> records = new List<Record> { }; // Start a list for all those sweet sweet logs we're going to get
foreach (var Log in Logs)
{
try
{
EventLogQuery eventlogQuery = new EventLogQuery(Log, pathType, query);
EventLogReader eventlogReader = new EventLogReader(eventlogQuery);
for (EventRecord eventRecord = eventlogReader.ReadEvent(); null != eventRecord; eventRecord = eventlogReader.ReadEvent())
{
// Get the SystemTime from the event record XML
var xml = XDoreplacedent.Parse(eventRecord.ToXml());
XNamespace ns = xml.Root.GetDefaultNamespace();
string Message = "";
string SystemTime = "";
string Id = "";
string Version = "";
string Qualifiers = "";
string Level = "";
string Task = "";
string Opcode = "";
string Keywords = "";
string RecordId = "";
string ProviderName = "";
string ProviderID = "";
string LogName = "";
string ProcessId = "";
string ThreadId = "";
string MachineName = "";
string UserID = "";
string TimeCreated = "";
string ActivityId = "";
string RelatedActivityId = "";
string Hashcode = "";
string LevelDisplayName = "";
string OpcodeDisplayName = "";
string TaskDisplayName = "";
// Debugging Stuff
//Console.WriteLine("-- STARTING --");
// Try to collect all the things. Catch them if we can't.
// Sometimes fields are null or cannot be converted to string (why?).
// If they are, catch and do nothing, so they will stay empty ("").
// This has primarily been LevelDisplayName, OpcodeDisplayName, and TaskDisplayName
// but we'll catch it all anyway
// https://github.com/BeanBagKing/EventFinder2/issues/1
try
{
Message = eventRecord.FormatDescription();
if (Message == null)
{
Message += "EventRecord.FormatDescription() returned a null value. This is usually because:\n";
Message += " \"Either the component that raises this event is not installed on your local computer\n" +
" or the installation is corrupted. You can install or repair the component on the local computer.\"\n";
Message += "The event likely originated on another system, below is the XML data replacedociated with this event\n";
Message += "\n";
Message += XDoreplacedent.Parse(eventRecord.ToXml()).ToString();
// If the message body is null, it's because the DLL that created it is on another system and it can't be parsed in real time
// The below works, but we can do better!
// foreach (var node in xml.Descendants(ns + "Event"))
// {
// Message += node.Value;
// Message += "\n";
// }
}
}
catch
{
//Console.WriteLine("Error on FormatDescription");
}
try
{
SystemTime = xml.Root.Element(ns + "System").Element(ns + "TimeCreated").Attribute("SystemTime").Value;
}
catch
{
//Console.WriteLine("Error on SystemTime");
}
try
{
Id = eventRecord.Id.ToString();
}
catch
{
//Console.WriteLine("Error on Id");
}
try
{
Version = eventRecord.Version.ToString();
}
catch
{
//Console.WriteLine("Error on Version");
}
try
{
Qualifiers = eventRecord.Qualifiers.ToString();
}
catch
{
//Console.WriteLine("Error on Qualifiers");
}
try
{
Level = eventRecord.Level.ToString();
}
catch
{
//Console.WriteLine("Error on Level");
}
try
{
Task = eventRecord.Task.ToString();
}
catch
{
//Console.WriteLine("Error on Task");
}
try
{
Opcode = eventRecord.Opcode.ToString();
}
catch
{
//Console.WriteLine("Error on Opcode");
}
try
{
Keywords = eventRecord.Keywords.ToString();
}
catch
{
//Console.WriteLine("Error on Keywords");
}
try
{
RecordId = eventRecord.RecordId.ToString();
}
catch
{
//Console.WriteLine("Error on RecordId");
}
try
{
ProviderName = eventRecord.ProviderName;
}
catch
{
//Console.WriteLine("Error on ProviderName");
}
try
{
ProviderID = eventRecord.ProviderId.ToString();
}
catch
{
//Console.WriteLine("Error on ProviderId");
}
try
{
LogName = eventRecord.LogName;
}
catch
{
//Console.WriteLine("Error on LogName");
}
try
{
ProcessId = eventRecord.ProcessId.ToString();
}
catch
{
//Console.WriteLine("Error on ProcessId");
}
try
{
ThreadId = eventRecord.ThreadId.ToString();
}
catch
{
//Console.WriteLine("Error on ThreadId");
}
try
{
MachineName = eventRecord.MachineName;
}
catch
{
//Console.WriteLine("Error on eventRecord");
}
try
{
UserID = eventRecord.UserId?.ToString();
}
catch
{
//Console.WriteLine("Error on UserId");
}
try
{
TimeCreated = eventRecord.TimeCreated.ToString();
}
catch
{
//Console.WriteLine("Error on TimeCreated");
}
try
{
ActivityId = eventRecord.ActivityId.ToString();
}
catch
{
//Console.WriteLine("Error on ActivityId");
}
try
{
RelatedActivityId = eventRecord.RelatedActivityId.ToString();
}
catch
{
//Console.WriteLine("Error on RelatedActivityId");
}
try
{
Hashcode = eventRecord.GetHashCode().ToString();
}
catch
{
//Console.WriteLine("Error on GetHashCode");
}
try
{
LevelDisplayName = eventRecord.LevelDisplayName;
}
catch
{
//Console.WriteLine("Error on LevelDisplayName");
}
try
{
OpcodeDisplayName = eventRecord.OpcodeDisplayName;
}
catch
{
//Console.WriteLine("Error on OpcodeDisplayName");
}
try
{
TaskDisplayName = eventRecord.TaskDisplayName;
}
catch
{
//Console.WriteLine("Error on TaskDisplayName");
}
//Console.WriteLine("-- ENDING --");
// Add them to the record. The things equal the things.
records.Add(new Record() { Message = Message, SystemTime = SystemTime, Id = Id, Version = Version, Qualifiers = Qualifiers, Level = Level, Task = Task, Opcode = Opcode, Keywords = Keywords, RecordId = RecordId, ProviderName = ProviderName, ProviderID = ProviderID, LogName = LogName, ProcessId = ProcessId, ThreadId = ThreadId, MachineName = MachineName, UserID = UserID, TimeCreated = TimeCreated, ActivityId = ActivityId, RelatedActivityId = RelatedActivityId, Hashcode = Hashcode, LevelDisplayName = LevelDisplayName, OpcodeDisplayName = OpcodeDisplayName, TaskDisplayName = TaskDisplayName });
}
}
catch (UnauthorizedAccessException)
{
// If you are running as admin, you will get unauthorized for some logs. Hey, I warned you! Nothing to do here.
// Catching this seperately since we know what happened.
}
catch (Exception ex)
{
if (Log.ToString().Equals("Microsoft-RMS-MSIPC/Debug"))
{
// Known issue, do nothing
// https://github.com/BeanBagKing/EventFinder2/issues/3
}
else if (Log.ToString().Equals("Microsoft-Windows-USBVideo/replacedytic"))
{
// Known issue, do nothing
// https://github.com/BeanBagKing/EventFinder2/issues/2
}
else
{
// Unknown issue! Write us a bug report
bool isElevated;
using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
using (StreamWriter writer = new StreamWriter(DesktopPath + "\\ERROR_EventFinder_" + RunTime + ".txt", append: true))
{
writer.WriteLine("-----------------------------------------------------------------------------");
writer.WriteLine("Issue Submission: https://github.com/BeanBagKing/EventFinder2/issues");
writer.WriteLine("Date : " + DateTime.Now.ToString());
writer.WriteLine("Log : " + Log);
writer.WriteLine("Admin Status: " + isElevated);
writer.WriteLine();
while (ex != null)
{
writer.WriteLine(ex.GetType().FullName);
writer.WriteLine("Message : " + ex.Message);
writer.WriteLine("StackTrace : " + ex.StackTrace);
writer.WriteLine("Data : " + ex.Data);
writer.WriteLine("HelpLink : " + ex.HelpLink);
writer.WriteLine("HResult : " + ex.HResult);
writer.WriteLine("InnerException : " + ex.InnerException);
writer.WriteLine("Source : " + ex.Source);
writer.WriteLine("TargetSite : " + ex.TargetSite);
ex = ex.InnerException;
}
}
}
}
}
records = records.OrderBy(x => x.SystemTime).ToList(); // Sort our records in chronological order
// and write them to a CSV
using (var writer = new StreamWriter(DesktopPath + "\\Logs_Runtime_" + RunTime + ".csv", append: true))
using (var csv = new CsvWriter(writer))
{
csv.Configuration.ShouldQuote = (field, context) => true;
csv.WriteRecords(records);
}
StatusOutput.Text = "Run Complete";
StatusOutput.ForeColor = System.Drawing.Color.Blue;
records.Clear();
}
FindEventsButton.Enabled = true;
}
19
Source : MainWindow.xaml.cs
with Apache License 2.0
from beetlex-io
with Apache License 2.0
from beetlex-io
private void SetTime(DateTime time)
{
this.Dispatcher.BeginInvoke(new Action<DateTime>(t =>
{
this.txtTime.Content = t.ToString();
}), time);
}
19
Source : Folder.cs
with Apache License 2.0
from beetlex-io
with Apache License 2.0
from beetlex-io
public List<Network.FileInfo> GetFiles()
{
List<Network.FileInfo> result = new List<Network.FileInfo>();
foreach (string item in System.IO.Directory.GetFiles(Path))
{
Network.FileInfo info = new Network.FileInfo();
info.Name = System.IO.Path.GetFileName(item);
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(item);
if (myFileVersionInfo != null)
info.Version = myFileVersionInfo.FileVersion;
info.UpdateTime = System.IO.File.GetLastWriteTime(item).ToString();
result.Add(info);
}
return result;
}
19
Source : CodeGeneration.cs
with Apache License 2.0
from BeiYinZhiNian
with Apache License 2.0
from BeiYinZhiNian
protected virtual string CreateFile(CodeGenerateData generate, string fileName, string extend,string producer)
{
string txt = File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}/Template/File/{fileName}{extend}.temp");
txt = txt.Replace("{Producer}", producer);
txt = txt.Replace("{GenerationTime}", DateTime.Now.ToString());
txt = txt.Replace("{EnreplacedyNamespace}", generate.EnreplacedyNamespace);
txt = txt.Replace("{WebUINamespace}", CaviarConfig.WebUI.Namespace);
txt = txt.Replace("{ModelsNamespace}", CaviarConfig.Models.Namespace);
txt = txt.Replace("{WebApiNamespace}", CaviarConfig.WebAPI.Namespace);
txt = txt.Replace("{BaseController}", CaviarConfig.WebAPI.Base);
txt = txt.Replace("{page}", "/" + generate.OutName + "/" + fileName);
txt = txt.Replace("{DataSourceWebApi}", $"{generate.OutName}/GetPages");
txt = txt.Replace("{EnreplacedyDisplayName}", generate.ModelName);
txt = txt.Replace("{FormItem}", CreateFormItem(generate));
//以下为最小单元,必须为最后替换
txt = txt.Replace("{ViewOutName}", $"View{generate.OutName}");
txt = txt.Replace("{OutName}", $"{generate.OutName}");
txt = txt.Replace("{EnreplacedyName}", generate.EnreplacedyName);
return txt;
}
19
Source : UserList.cs
with GNU General Public License v3.0
from belowaverage-org
with GNU General Public License v3.0
from belowaverage-org
public static string ConvertColumnValue(KeyValuePair<ULColumnType, string> ColumnItem)
{
if (ColumnItem.Key == ULColumnType.Size)
{
if (double.TryParse(ColumnItem.Value, out double dblValue))
{
return dblValue.ByteHumanize();
}
}
if (
ColumnItem.Key == ULColumnType.ExportedOn ||
ColumnItem.Key == ULColumnType.FirstCreated ||
ColumnItem.Key == ULColumnType.ImportedOn ||
ColumnItem.Key == ULColumnType.LastModified
) {
if (long.TryParse(ColumnItem.Value, out long longValue))
{
return DateTime.FromFileTime(longValue).ToString();
}
}
return ColumnItem.Value;
}
19
Source : Form1.cs
with GNU General Public License v3.0
from Benjerman
with GNU General Public License v3.0
from Benjerman
private void btnExecute_Click(object sender, EventArgs e)
{
try
{
if (this.minecraftProcess.HasExited)
{
txtOutput.AppendText("\r\n\r\nThe server has been shutdown.\r\n");
File.AppendAllText(@"ServerLog.csv", "\r\n" + DateTime.Now.ToString() + " " + "The server has been shutdown.\r\n");
return;
}
mcInputStream.WriteLine(txtInputCommand.Text);
}
catch
{
}
}
19
Source : Form1.cs
with GNU General Public License v3.0
from Benjerman
with GNU General Public License v3.0
from Benjerman
public void ProcessExited(object sender, EventArgs e)
{
txtOutput.AppendText("\r\n\r\nThe server has been shutdown.\r\n");
File.AppendAllText(@"ServerLog.csv", "\r\n" + DateTime.Now.ToString() + " " + "The server has been shutdown.\r\n");
}
19
Source : Form1.cs
with GNU General Public License v3.0
from Benjerman
with GNU General Public License v3.0
from Benjerman
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
mcInputStream.WriteLine("say THE SERVER IS GOING DOWN FOR A BACKUP IN 10 SECONDS");
txtOutput.AppendText("\r\n\r\nTelling players the server is going down in 10 seconds\r\n");
File.AppendAllText(@"ServerLog.csv", "\r\n" + DateTime.Now.ToString() + " " + "Telling players the server is going down in 10 seconds\r\n");
Thread.Sleep(10000);
txtOutput.AppendText("\r\nStopping Server\r\n");
File.AppendAllText(@"ServerLog.csv", DateTime.Now.ToString() + " " + "Stopping Server\r\n");
mcInputStream.WriteLine("stop");
Thread.Sleep(5000);
string source_dir = "";
string destination_dir = "";
source_dir = @"worlds";
destination_dir = @"backups\worlds" + DateTime.Now.ToString("hhmmttMMddyyyy");
txtOutput.AppendText("\r\nStarting Backup\r\n\r\n");
File.AppendAllText(@"ServerLog.csv", DateTime.Now.ToString() + " " + "Starting Backup\r\n");
foreach (string dir in System.IO.Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
{
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(destination_dir, dir.Substring(source_dir.Length + 1)));
}
foreach (string file_name in System.IO.Directory.GetFiles(source_dir, "*", System.IO.SearchOption.AllDirectories))
{
System.IO.File.Copy(file_name, System.IO.Path.Combine(destination_dir, file_name.Substring(source_dir.Length + 1)));
txtOutput.AppendText("Backing up: " + file_name + " TO: " + destination_dir + file_name + "\r\n\r\n");
File.AppendAllText(@"ServerLog.csv", DateTime.Now.ToString() + " " + "Backing up: " + file_name + " TO: " + destination_dir + file_name + "\r\n");
txtOutput.ScrollToCaret();
}
Thread.Sleep(5000);
txtOutput.AppendText("\r\nBackup Complete. Starting server\r\n\r\n");
File.AppendAllText(@"ServerLog.csv", DateTime.Now.ToString() + " " + "Backup Complete. Starting server\r\n");
startServerButton_Click(sender, e);
}
19
Source : CustomDateFormatConverter.cs
with MIT License
from berdon
with MIT License
from berdon
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
string ticks = "0";
switch (value)
{
case DateTime t1:
{
ticks = t1.Ticks.ToString();
break;
}
case DateTimeOffset t:
{
ticks = t.UtcDateTime.ToString();
break;
}
default:
{
throw new Exception("Expected date object value.");
}
}
writer.WriteValue(ticks);
}
19
Source : Invoice Details.cs
with MIT License
from bilalmehrban
with MIT License
from bilalmehrban
private void btntoday_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
DateTime thedate = System.DateTime.Today;
thedate -= new TimeSpan(1, 0, 0, 0);
DataTable dat = dal1.MonthlyAndDailyData(date.ToString(), thedate.ToString());
dgvinvoicedetails.DataSource = dat;
double[] columnData = (from DataGridViewRow row in dgvinvoicedetails.Rows
where row.Cells[3].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[3].FormattedValue)).ToArray();
txttotalamount.Text = columnData.Sum().ToString();
double[] columnData1 = (from DataGridViewRow row in dgvinvoicedetails.Rows
where row.Cells[6].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[6].FormattedValue)).ToArray();
txtdueamount.Text = columnData1.Sum().ToString();
double[] columnData2 = (from DataGridViewRow row in dgvinvoicedetails.Rows
where row.Cells[7].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[7].FormattedValue)).ToArray();
txtreturnamount.Text = columnData2.Sum().ToString();
}
19
Source : Invoice Details.cs
with MIT License
from bilalmehrban
with MIT License
from bilalmehrban
private void btnmonth_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
DateTime thedate = System.DateTime.Today;
thedate -= new TimeSpan(30, 0, 0, 0);
DataTable dat = dal1.MonthlyAndDailyData(date.ToString(), thedate.ToString());
dgvinvoicedetails.DataSource = dat;
double[] columnData = (from DataGridViewRow row in dgvinvoicedetails.Rows
where row.Cells[3].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[3].FormattedValue)).ToArray();
txttotalamount.Text = columnData.Sum().ToString();
double[] columnData1 = (from DataGridViewRow row in dgvinvoicedetails.Rows
where row.Cells[6].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[6].FormattedValue)).ToArray();
txtdueamount.Text = columnData1.Sum().ToString();
double[] columnData2 = (from DataGridViewRow row in dgvinvoicedetails.Rows
where row.Cells[7].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[7].FormattedValue)).ToArray();
txtreturnamount.Text = columnData2.Sum().ToString();
}
19
Source : Sales Analytics.cs
with MIT License
from bilalmehrban
with MIT License
from bilalmehrban
private void btnmonth_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
DateTime thedate = System.DateTime.Today;
thedate -= new TimeSpan(30, 0, 0,0);
DataTable dat = d.MonthlyAndDailyData(date.ToString(),thedate.ToString()) ;
dgvsalesreplacedytics.DataSource = dat;
//To calculate total quanreplacedy from table
double[] columnData = (from DataGridViewRow row in dgvsalesreplacedytics.Rows
where row.Cells[7].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[7].FormattedValue)).ToArray();
txtquanreplacedy.Text = columnData.Sum().ToString();
//To calculate total amount from table
double[] columnData1 = (from DataGridViewRow row in dgvsalesreplacedytics.Rows
where row.Cells[9].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[9].FormattedValue)).ToArray();
totalamount = columnData1.Sum();
txtamount.Text = totalamount.ToString();
//To calculate purchase price from table
double[] columnData2 = (from DataGridViewRow row in dgvsalesreplacedytics.Rows
where row.Cells[10].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[10].FormattedValue)).ToArray();
purchaseprice = columnData2.Sum();
//to calculate total revenue
totalrevenue = totalamount - purchaseprice;
txtrevenue.Text = (totalrevenue).ToString();
}
19
Source : Sales Analytics.cs
with MIT License
from bilalmehrban
with MIT License
from bilalmehrban
private void btntoday_Click(object sender, EventArgs e)
{
//To Create Variables for sale history
DateTime date = DateTime.Now;
DateTime thedate = System.DateTime.Today;
thedate -= new TimeSpan(1, 0, 0, 0);
DataTable dat = d.MonthlyAndDailyData(date.ToString(), thedate.ToString());
dgvsalesreplacedytics.DataSource = dat;
//To calculate total quanreplacedy from table
double[] columnData = (from DataGridViewRow row in dgvsalesreplacedytics.Rows
where row.Cells[7].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[7].FormattedValue)).ToArray();
txtquanreplacedy.Text = columnData.Sum().ToString();
//To calculate total amount from table
double[] columnData1 = (from DataGridViewRow row in dgvsalesreplacedytics.Rows
where row.Cells[9].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[9].FormattedValue)).ToArray();
totalamount = columnData1.Sum();
txtamount.Text = totalamount.ToString();
//To calculate purchase price from table
double[] columnData2 = (from DataGridViewRow row in dgvsalesreplacedytics.Rows
where row.Cells[10].FormattedValue.ToString() != string.Empty
select Convert.ToDouble(row.Cells[10].FormattedValue)).ToArray();
purchaseprice = columnData2.Sum();
//to calculate total revenue
totalrevenue = totalamount - purchaseprice;
txtrevenue.Text = (totalrevenue).ToString();
}
19
Source : SearchModule.cs
with GNU General Public License v3.0
from Bililive
with GNU General Public License v3.0
from Bililive
private void WriteError(Exception exception, string description)
{
try
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
using (StreamWriter outfile = new StreamWriter(path + @"\B站彈幕姬点歌姬歌曲搜索引擎" + ModuleName + "错误报告.txt"))
{
outfile.WriteLine("请将错误报告发给 " + ModuleAuthor + " 谢谢,联系方式:" + ModuleContact);
outfile.WriteLine(description);
outfile.WriteLine(ModuleName + " 本地时间:" + DateTime.Now.ToString());
outfile.Write(exception.ToString());
new Thread(() =>
{
System.Windows.MessageBox.Show("点歌姬歌曲搜索引擎“" + ModuleName + @"”遇到了未处理的错误
日志已经保存在桌面,请发给引擎作者 " + ModuleAuthor + ", 联系方式:" + ModuleContact);
}).Start();
}
}
catch (Exception)
{ }
}
19
Source : GetChildItemCommand.cs
with BSD 3-Clause "New" or "Revised" License
from bitsadmin
with BSD 3-Clause "New" or "Revised" License
from bitsadmin
public static CommandResult BrowseFilesystem(string path, bool recurse, int depth, bool includeHidden, string searchPattern)
{
CommandResult results = new CommandResult();
DirectoryInfo gciDir = new DirectoryInfo(path);
if (!gciDir.Exists)
throw new ItemNotFoundException(path);
// TODO: Follow symlinks. Skipping them for now
if ((gciDir.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
return results;
DirectoryInfo[] directories;
try
{
directories = gciDir.GetDirectories(recurse ? "*" : searchPattern);
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Unauthorized to access \"{0}\"", path);
return results;
}
FileInfo[] files = gciDir.GetFiles(searchPattern);
// Enumerate directories
foreach (DirectoryInfo dir in directories)
{
if (!includeHidden && ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden))
continue;
// Don't show directories if -Recurse and an -Include filter is set
if (recurse && !string.IsNullOrEmpty(searchPattern))
continue;
ResultRecord currentDir = new ResultRecord()
{
{ "Mode", GetModeFlags(dir) },
{ "LastWriteTime", dir.LastWriteTime.ToString() },
{ "Length", string.Empty },
{ "Name", dir.Name }
};
// If recursive, also the directory name is needed
if (recurse)
currentDir.Add("Directory", dir.FullName);
results.Add(currentDir);
}
// Enumerate files
foreach (FileInfo file in files)
{
if (!includeHidden && ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden))
continue;
ResultRecord currentFile = new ResultRecord()
{
{ "Mode", GetModeFlags(file) },
{ "LastWriteTime", file.LastWriteTime.ToString() },
{ "Length", file.Length.ToString() },
{ "Name", file.Name }
};
// If recursive, also the directory name is needed
if (recurse)
currentFile.Add("Directory", file.Directory.FullName);
results.Add(currentFile);
}
// After adding folders and files in current directory, go depth first
if (recurse && depth > 0)
{
foreach (DirectoryInfo subDir in directories)
{
// Skip hidden directories in case -Force parameter is not provided
if ((subDir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden && !includeHidden)
continue;
CommandResult currentDir = BrowseFilesystem(subDir.FullName, recurse, depth - 1, includeHidden, searchPattern);
results.AddRange(currentDir);
}
}
return results;
}
19
Source : CalendarDay.razor.cs
with MIT License
from BlazorFluentUI
with MIT License
from BlazorFluentUI
private void GenerateWeeks()
{
DateTime date = new(NavigatedDate.Year, NavigatedDate.Month, 1);
DateTime todaysDate = DateTime.Now;
Weeks = new List<List<DayInfo>>();
// cycle backwards to get first day of week
while (date.DayOfWeek != FirstDayOfWeek)
date -= TimeSpan.FromDays(1);
// a flag to indicate whether all days of the week are in the month
bool isAllDaysOfWeekOutOfMonth = false;
// in work week view we want to select the whole week
//DateRangeType selecteDateRangeType = DateRangeType == DateRangeType.WorkWeek ? DateRangeType.Week : DateRangeType;
DateRangeType selecteDateRangeType = DateRangeType;
List<DateTime>? selectedDates = SelectedDate == null ? new List<DateTime>() : DateUtilities.GetDateRangeArray((DateTime)SelectedDate, selecteDateRangeType, FirstDayOfWeek, WorkWeekDays);
if (DateRangeType != DateRangeType.Day)
{
selectedDates = GetBoundedDateRange(selectedDates, MinDate, MaxDate);
}
bool shouldGetWeeks = true;
for (int weekIndex = 0; shouldGetWeeks; weekIndex++)
{
List<DayInfo> week = new();
isAllDaysOfWeekOutOfMonth = true;
for (int dayIndex = 0; dayIndex < 7; dayIndex++)
{
DateTime originalDate = new(date.Year, date.Month, date.Day);
DayInfo? dayInfo = new()
{
Key = date.ToString(),
Date = date.Date.ToString("D"),
OriginalDate = originalDate,
WeekIndex = weekIndex,
IsInMonth = date.Month == NavigatedDate.Month,
IsToday = DateTime.Compare(DateTime.Now.Date, originalDate) == 0,
IsSelected = IsInDateRangeArray(date, selectedDates),
IsHighlightedOnHover = IsInWorkweekRange(date),
OnSelected = () => OnSelectDateInternal(originalDate, false),
IsInBounds =
(DateTime.Compare(MinDate, date) < 1) &&
(DateTime.Compare(date, MaxDate) < 1) &&
!GetIsRestrictedDate(date)
};
week.Add(dayInfo);
if (dayInfo.IsInMonth)
isAllDaysOfWeekOutOfMonth = false;
date = date.AddDays(1);
}
// We append the condition of the loop depending upon the ShowSixWeeksByDefault parameter.
shouldGetWeeks = ShowSixWeeksByDefault ? !isAllDaysOfWeekOutOfMonth || weekIndex <= 5 : !isAllDaysOfWeekOutOfMonth;
if (shouldGetWeeks)
Weeks.Add(week);
}
}
19
Source : BrowserDateTime.cs
with MIT License
from Blazored
with MIT License
from Blazored
public string ConvertToBrowserTime(DateTime dateTime, string format = "")
{
if (string.IsNullOrWhiteSpace(format))
{
return TimeZoneInfo.ConvertTime(dateTime, LocalTimeZoneInfo)
.ToString();
}
return TimeZoneInfo.ConvertTime(dateTime, LocalTimeZoneInfo)
.ToString(format, CultureInfo.CurrentCulture);
}
19
Source : IdentityService.cs
with Apache License 2.0
from bluedoctor
with Apache License 2.0
from bluedoctor
public static void WriteLog(LoginResultModel result,long logTime)
{
string filePath = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, "UserLog.txt");
try
{
string text = string.Format("{0} User :{1} Web Login used time(ms):{2}, ErrorMsg:{3}\r\n", DateTime.Now.ToString(),
result.UserName, logTime, result.ErrorMessage);
System.IO.File.AppendAllText(filePath, text);
}
catch
{
}
}
19
Source : TokenManager.cs
with Apache License 2.0
from bluedoctor
with Apache License 2.0
from bluedoctor
public TokenResponse TakeToken()
{
this.TokenExctionMessage = "";
if (dictUserToken.ContainsKey(this.UserName))
{
UserTokenInfo uti = dictUserToken[this.UserName];
//获取当前用户的读写锁
//this.CurrentTokenLock = uti.TokenLock;
//this.CurrentTokenLock.EnterUpgradeableReadLock();
//Console.WriteLine("...EnterUpgradeableReadLock...,Thread ID:{0}",Thread.CurrentThread.ManagedThreadId);
this.OldToken = uti.Token;
int expiresSeconds = uti.Token.expires_in - 2;
//如果令牌超期,刷新令牌
if (DateTime.Now.Subtract(uti.FirstUseTime).TotalSeconds >= expiresSeconds || NeedRefresh)
{
lock (uti.SyncObject)
{
//防止线程重入,再次判断
if (DateTime.Now.Subtract(uti.FirstUseTime).TotalSeconds >= expiresSeconds || NeedRefresh)
{
//等待之前的用户使用完令牌再刷新
while (uti.UseCount > 0)
{
if (DateTime.Now.Subtract(uti.LastUseTime).TotalSeconds > 5)
{
//如果发出请求超过5秒使用计数还大于0,可以认为资源服务器响应缓慢,最终请求此资源可能会拒绝访问
this.TokenExctionMessage = "Resouce Server maybe Request TimeOut.";
OAuthClient.WriteErrorLog("00", "**警告** "+DateTime.Now.ToString()+":用户"+this.UserName+" 最近一次使用当前令牌("
+uti.Token.AccessToken +")已经超时(5秒),使用次数:"+uti.UseCount+",线程ID:"+System.Threading.Thread.CurrentThread.ManagedThreadId+"。\r\n**下面将刷新令牌,但可能导致之前还未处理完的资源服务器访问被拒绝访问。");
break;
}
System.Threading.Thread.Sleep(100);
}
//刷新令牌
try
{
OAuthClient oc = new OAuthClient();
var newToken = oc.RefreshToken(uti.Token);
if (newToken == null)
throw new Exception("Refresh Token Error:" + oc.ExceptionMessage);
else if( string.IsNullOrEmpty( newToken.AccessToken))
throw new Exception("Refresh Token Error:Empty AccessToken. Other Message:" + oc.ExceptionMessage);
uti.ResetToken(newToken);
this.TokenExctionMessage = oc.ExceptionMessage;
}
catch (Exception ex)
{
this.TokenExctionMessage = ex.Message;
return null;
}
NeedRefresh = false;
}
}//end lock
}
this.CurrentUserTokenInfo = uti;
uti.BeginUse();
//this.CurrentTokenLock.Set();
return uti.Token;
}
else
{
//throw new Exception(this.UserName+" 还没有访问令牌。");
this.TokenExctionMessage = "UserNoToken";
return null;
}
}
19
Source : OpenAuthorizationServerProvider.cs
with Apache License 2.0
from bluedoctor
with Apache License 2.0
from bluedoctor
private void Log(string logText)
{
string logFile = System.Configuration.ConfigurationManager.AppSettings["LogFile"];
if (string.IsNullOrEmpty(logFile))
return;
PWMIS.Core.CommonUtil.ReplaceWebRootPath(ref logFile);
try
{
System.IO.File.AppendAllText(logFile, DateTime.Now.ToString() + "--" + logText + "\r\n");
}
catch(Exception ex)
{
string message = "尝试写日志文件失败:" + ex.Message + "。当前记录的日志消息:" + logText;
Startup.WriteEventLog(message, EventLogEntryType.Warning);
}
}
19
Source : OAuthClient.cs
with Apache License 2.0
from bluedoctor
with Apache License 2.0
from bluedoctor
public static void WriteErrorLog(string errCode, string logText)
{
string filePath = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, "ProxyErrorLog.txt");
try
{
string text = string.Format("{0} ErrorCode:{1} ErrorMsg:{2}\r\n", DateTime.Now.ToString(), errCode, logText);
System.IO.File.AppendAllText(filePath, text);
}
catch
{
}
}
19
Source : DataTypes.cs
with MIT License
from bobtaylor29708
with MIT License
from bobtaylor29708
public string GetDataTypeValue(int index)
{
string ret = "";
switch (index)
{
case 0:
ret = "0x0f0203040500607080900a0b0c";
break;
case 1:
ret = "0x0f0203040500607080900a0b0c";
break;
case 2:
ret = "'" + DateTime.Today.ToShortDateString() + "'";
break;
case 3:
ret = "'" + DateTime.Today.ToShortTimeString() + "'";
break;
case 4:
ret = "3.14";
break;
case 5:
ret = Math.Sqrt(2).ToString();
break;
case 6:
ret = "3.14159265";
break;
case 7:
ret = "42";
break;
case 8:
ret = "65535";
break;
case 9:
ret = "'ABCDEFGHIJ'";
break;
case 10:
ret = "'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ'";
break;
case 11:
ret = "N'ABCDEFGHIJ'";
break;
case 12:
ret = "N'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ'";
break;
case 13:
ret = "'" + DateTime.Today.ToUniversalTime().ToString() + "'";
break;
}
return ret;
}
19
Source : DateTimeExtensions.cs
with MIT License
from BoletoNet
with MIT License
from BoletoNet
public static long FatorVencimento(this DateTime data)
{
var dateBase = new DateTime(1997, 10, 7, 0, 0, 0);
// Verifica se a data esta dentro do range utilizavel
var rangeUtilizavel = DateTime.Now.Date.DateDiff(data, DateInterval.Day);
if (rangeUtilizavel > 5500 || rangeUtilizavel < -3500)
throw new Exception("Data do vencimento ("+data.ToString()+") fora do range de utilização proposto pela CENEGESC. Comunicado FEBRABAN de n° 082/2012 de 14/06/2012");
while (data > dateBase.AddDays(9999))
dateBase = data.AddDays(-(dateBase.DateDiff(data, DateInterval.Day) - 9999 - 1 + 1000));
return dateBase.DateDiff(data, DateInterval.Day);
}
19
Source : ClientListItem.cs
with GNU General Public License v3.0
from boonkerz
with GNU General Public License v3.0
from boonkerz
public override string ToString()
{
return "ID: " + SystemId + " LastSeen: " + LastSeen.ToString();
}
19
Source : LogWriter.cs
with GNU General Public License v3.0
from bosima
with GNU General Public License v3.0
from bosima
public static void Write(string message, LogLevel level)
{
Console.WriteLine(string.Format("{0} [{1}] {2}", DateTime.Now.ToString(), level.ToString(), message));
switch (level)
{
case LogLevel.Trace:
logger.Trace(message);
break;
case LogLevel.Debug:
logger.Debug(message);
break;
case LogLevel.Info:
logger.Info(message);
break;
case LogLevel.Warn:
logger.Warn(message);
break;
case LogLevel.Error:
logger.Error(message);
break;
}
}
19
Source : LogWriter.cs
with GNU General Public License v3.0
from bosima
with GNU General Public License v3.0
from bosima
public static void Write(string message, Exception ex, LogLevel level)
{
Console.WriteLine(string.Format("{0} [{1}] {2}", DateTime.Now.ToString(), level.ToString(), message));
if (ex != null)
{
Console.WriteLine(string.Format("{0} [{1}] {2}", DateTime.Now.ToString(), level.ToString(), ex.Message));
Console.WriteLine(string.Format("{0} [{1}] {2}", DateTime.Now.ToString(), level.ToString(), ex.StackTrace));
}
switch (level)
{
case LogLevel.Trace:
logger.Trace(ex, message);
break;
case LogLevel.Debug:
logger.Debug(ex, message);
break;
case LogLevel.Info:
logger.Info(ex, message);
break;
case LogLevel.Warn:
logger.Warn(ex, message);
break;
case LogLevel.Error:
logger.Error(ex, message);
break;
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from bosima
with GNU General Public License v3.0
from bosima
private static void ShowMessage(IEnumerable<string> messages, bool isStop = false)
{
if (messages.Any())
{
foreach (var msg in messages)
{
Console.WriteLine(string.Format("{0} {1}", DateTime.Now.ToString(), msg));
}
if (isStop)
{
Console.WriteLine("程序已停止运行,按任意键关闭窗口....");
Console.ReadKey();
Environment.Exit(0);
}
}
}
19
Source : BookingDialog.cs
with MIT License
from BotBuilderCommunity
with MIT License
from BotBuilderCommunity
private async Task<DialogTurnResult> ConfirmStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var bookingDetails = (BookingDetails)stepContext.Options;
bookingDetails.TravelDate = DateTime.Now.ToString();
//bookingDetails.TravelDate = (string)stepContext.Result;
var messageText = $"Please confirm, I have you traveling to: {bookingDetails.Destination} from: {bookingDetails.Origin} on: {bookingDetails.TravelDate}. Is this correct?";
var promptMessage = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput);
return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = promptMessage }, cancellationToken);
}
19
Source : Logger.cs
with MIT License
from bp2008
with MIT License
from bp2008
public static void Debug(Exception ex, string additionalInformation = "")
{
if (additionalInformation == null)
additionalInformation = "";
lock (lockObj)
{
if ((logType & LoggingMode.Console) > 0)
{
if (ex != null)
Console.Write("Exception thrown at ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(DateTime.Now.ToString());
if (ex != null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.ToString());
}
if (!string.IsNullOrEmpty(additionalInformation))
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
if (ex != null)
Console.Write("Additional information: ");
Console.WriteLine(additionalInformation);
}
Console.ResetColor();
}
if ((logType & LoggingMode.File) > 0 && (ex != null || !string.IsNullOrEmpty(additionalInformation)))
{
StringBuilder debugMessage = new StringBuilder();
debugMessage.Append("-------------").Append(Environment.NewLine);
if (ex != null)
debugMessage.Append("Exception thrown at ");
debugMessage.Append(DateTime.Now.ToString()).Append(Environment.NewLine);
if (!string.IsNullOrEmpty(additionalInformation))
{
if (ex != null)
debugMessage.Append("Additional information: ");
debugMessage.Append(additionalInformation).Append(Environment.NewLine);
}
if (ex != null)
debugMessage.Append(ex.ToString()).Append(Environment.NewLine);
debugMessage.Append("-------------").Append(Environment.NewLine);
int attempts = 0;
while (attempts < 5)
{
try
{
File.AppendAllText(logFilePath, debugMessage.ToString());
attempts = 10;
}
catch (Exception)
{
attempts++;
}
}
}
}
}
19
Source : Logger.cs
with MIT License
from bp2008
with MIT License
from bp2008
public static void Info(string message)
{
if (message == null)
return;
lock (lockObj)
{
if ((logType & LoggingMode.Console) > 0)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(DateTime.Now.ToString());
Console.ResetColor();
Console.WriteLine(message);
}
if ((logType & LoggingMode.File) > 0)
{
int attempts = 0;
while (attempts < 5)
{
try
{
File.AppendAllText(logFilePath, DateTime.Now.ToString() + Environment.NewLine + message + Environment.NewLine);
attempts = 10;
}
catch (Exception)
{
attempts++;
}
}
}
}
}
19
Source : MainForm.cs
with MIT License
from bp2008
with MIT License
from bp2008
private string GetTimestamp(DateTime time)
{
if (!string.IsNullOrWhiteSpace(settings.customTimeStr))
{
try
{
return time.ToString(settings.customTimeStr);
}
catch { }
}
return time.ToString();
}
19
Source : LogEntry.cs
with GNU General Public License v3.0
from BramDC3
with GNU General Public License v3.0
from BramDC3
public override string ToString()
{
var plusEx = (Exception != null) ? (Environment.NewLine + Exception.ToString()) : "";
return "[" + Timestamp.ToString() + "]"
+ "[" + LoggerName + "]"
+ "[" + LogType.ToString() + "]"
+ Message
+ plusEx;
}
19
Source : GivenARedisTaskQueue.cs
with MIT License
from brthor
with MIT License
from brthor
[Fact]
public async Task ItCapturesArgumentsPreplacededToEnqueuedDelegate()
{
var testFixture = new TaskQueueTestFixture(nameof(ItCapturesArgumentsPreplacededToEnqueuedDelegate));
string variableToExtract = "extracted";
var semapreplacedFile = Path.GetTempFileName();
var now = DateTime.Now;
var utcNow = DateTime.UtcNow;
Func<Expression<Action>, string, Tuple<Expression<Action>, string>> TC = (actionExp, str) =>
Tuple.Create<Expression<Action>, string>(
actionExp,
str);
// Action to expected result
var delgates = new Tuple<Expression<Action>, string>[]
{
// Exception Argument
TC(() => ExceptionFunc(new Exception(), semapreplacedFile), new Exception().ToString()),
TC(() => ExceptionFunc(new CustomException(), semapreplacedFile), new CustomException().ToString()),
// Integer Arguments
TC(() => IntFunc(int.MaxValue, semapreplacedFile), int.MaxValue.ToString()),
TC(() => IntFunc(int.MinValue, semapreplacedFile), int.MinValue.ToString()),
TC(() => NullableIntFunc(null, semapreplacedFile), "-1"),
TC(() => NullableIntFunc(int.MinValue, semapreplacedFile), int.MinValue.ToString()),
TC(() => NullableIntFunc(int.MaxValue, semapreplacedFile), int.MaxValue.ToString()),
// Float Arguments
TC(() => FloatFunc(float.MaxValue, semapreplacedFile), float.MaxValue.ToString()),
TC(() => FloatFunc(float.MinValue, semapreplacedFile), float.MinValue.ToString()),
// Double Arguments
TC(() => DoubleFunc(double.MaxValue, semapreplacedFile), double.MaxValue.ToString()),
TC(() => DoubleFunc(double.MinValue, semapreplacedFile), double.MinValue.ToString()),
// Long Arguments
TC(() => LongFunc(long.MaxValue, semapreplacedFile), long.MaxValue.ToString()),
TC(() => LongFunc(long.MinValue, semapreplacedFile), long.MinValue.ToString()),
TC(() => BoolFunc(true, semapreplacedFile), true.ToString()),
TC(() => BoolFunc(false, semapreplacedFile), false.ToString()),
TC(() => StringFunc("astring", semapreplacedFile), "astring"),
TC(() => StringFunc(variableToExtract, semapreplacedFile), variableToExtract),
// Object Arguments + Overloaded Version
TC(() => ObjectFunc(new TestDataHolder {Value = "astring"}, semapreplacedFile), "astring"),
TC(() => ObjectFunc(null, new TestDataHolder {Value = "astring"}, semapreplacedFile), "astring"),
TC(() => DateTimeFunc(now, semapreplacedFile), now.ToString()),
TC(() => DateTimeFunc(utcNow, semapreplacedFile), utcNow.ToString()),
TC(() => NullableTypeFunc(null, semapreplacedFile), "null"),
TC(() => NullableTypeFunc(now, semapreplacedFile), now.ToString()),
TC(() => ArrayFunc1(new[] {"this", "string", "is"}, semapreplacedFile), "this,string,is"),
TC(() => ArrayFunc2(new[] {1, 2, 3, 4}, semapreplacedFile), "1,2,3,4"),
TC(() => ArrayFunc3(new int?[] {1, 2, 3, null, 5}, semapreplacedFile), "1,2,3,null,5"),
TC(() => TypeFunc(typeof(object), semapreplacedFile), typeof(object).ToString()),
TC(() => TypeFunc(typeof(GivenARedisTaskQueue), semapreplacedFile), typeof(GivenARedisTaskQueue).ToString()),
TC(() => TypeFunc(null, semapreplacedFile), "null"),
// Awaiting inside the lambda is unnecessary, as the method is extracted and serialized.
#pragma warning disable 4014
TC(() => AsyncFunc(semapreplacedFile), "async"),
TC(() => AsyncFuncThatReturnsString(semapreplacedFile), "async"),
#pragma warning restore 4014
TC(() => AsyncFunc(semapreplacedFile).T(), "async"),
TC(() => AsyncFuncThatReturnsString(semapreplacedFile).T(), "async")
};
foreach (var tup in delgates)
{
var actionExpr = tup.Item1;
var expectedString = tup.Item2;
File.Delete(semapreplacedFile);
await testFixture.TaskQueue.Enqueue(actionExpr);
await testFixture.TaskQueue.ExecuteNext();
File.ReadAllText(semapreplacedFile).Should().Be(expectedString);
}
File.Delete(semapreplacedFile);
}
19
Source : Program.cs
with MIT License
from brthor
with MIT License
from brthor
private static void WriteDate()
{
Console.WriteLine(DateTime.UtcNow.ToString());
}
19
Source : AutomateWindow.cs
with MIT License
from builtbybel
with MIT License
from builtbybel
public async void DoAutomate()
{
if (lstPS.CheckedItems.Count == 0)
{
MessageBox.Show("No tasks selected.");
}
else
{
if (!osInfo.IsWin11())
{
MessageBox.Show("We could not recognize this system as Windows 11. Some scripts are not tested on this operating system and could lead to malfunction.");
}
if (MessageBox.Show("Do you want to apply selected tasks?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
for (int i = 0; i < lstPS.Items.Count; i++)
{
if (lstPS.GereplacedemChecked(i))
{
lstPS.SelectedIndex = i;
string psdir = Helpers.Strings.Data.PackagesRootDir + lstPS.SelectedItem.ToString() + ".ps1";
var ps1File = psdir;
var equals = new[] { "Requires -RunSilent" };
var str = rtbDesc.Text;
btnCancel.Visible = true;
progress.Visible = true;
progress.Style = ProgressBarStyle.Marquee;
progress.MarqueeAnimationSpeed = 30;
btnApply.Enabled = false;
lnkSubHeader.Text = "Processing " + lstPS.Text;
if (equals.Any(str.Contains)) // Silent
{
var startInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-executionpolicy bypreplaced -file \"{ps1File}\"",
UseShellExecute = false,
CreateNoWindow = true,
};
await Task.Run(() => { Process.Start(startInfo).WaitForExit(); });
}
else // Create ConsoleWindow
{
var startInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-executionpolicy bypreplaced -noexit -file \"{ps1File}\"",
UseShellExecute = false,
};
await Task.Run(() => { Process.Start(startInfo).WaitForExit(); });
}
btnApply.Enabled = true;
lnkSubHeader.Text = "";
// Write log
CreateLogsDir();
File.WriteAllText(Helpers.Strings.Data.PackagesLogsDir + lstPS.Text + ".txt", "last applied: " + DateTime.Now.ToString() + Environment.NewLine + rtbPS.Text);
}
}
btnApply.Text = "Apply selected";
progress.Visible = false;
btnCancel.Visible = false;
MessageBox.Show("Selected tasks have been successfully executed.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
19
Source : ApiContextTest.cs
with MIT License
from bunq
with MIT License
from bunq
[Fact]
public void TestAutoApiContextReLoad()
{
var contextJson = JObject.Parse(apiContext.ToJson());
var expiredTime = DateTime.Now.Subtract(TimeSpan.FromDays(20));
contextJson.SelectToken(FIELD_FIELD_SESSION_CONTEXT)[FIELD_FIELD_EXPIRY_TIME] = expiredTime.ToString();
var expiredApiContext = ApiContext.FromJson(contextJson.ToString());
replacedert.NotEqual(apiContext, expiredApiContext);
BunqContext.UpdateApiContext(expiredApiContext);
replacedert.Equal(expiredApiContext, BunqContext.ApiContext);
BunqContext.UserContext.RefreshUserContext();
replacedert.True(BunqContext.ApiContext.IsSessionActive());
}
19
Source : BackupManager.cs
with GNU General Public License v3.0
from bykovme
with GNU General Public License v3.0
from bykovme
static void createAutoBackup()
{
try {
var dbDir = PlatformSpecific.GetDBDirectory();
var backupFolder = PlatformSpecific.GetBackupPath();
var currentDateTime = DateTime.Now;
var backupName = GConsts.NSWB + "-" + currentDateTime.ToString(GConsts.BACKUP_DATEFORMAT) + "-" + GConsts.BACKUP_AUTO + ".zip";
Settings.AutoBackupTime = currentDateTime.ToString();
PlatformSpecific.CreateZip(dbDir, backupFolder, backupName);
} catch (Exception ex) {
AppLogs.Log(ex.Message, nameof(createAutoBackup), nameof(BackupManager));
}
}
19
Source : SysUserAOP.cs
with GNU General Public License v3.0
from Caijt
with GNU General Public License v3.0
from Caijt
public void Intercept(IInvocation invocation)
{
string dataIntercept = $"{DateTime.Now.ToString()} " +
$"当前执行方法:{invocation.TargetType.FullName}.{invocation.Method.Name} " +
$"参数:{string.Join(",", invocation.Arguments.Select(a => (a ?? "").ToString()))} \r\n";
invocation.Proceed();
dataIntercept += $"返回结果:{invocation.ReturnValue}";
string path = Directory.GetCurrentDirectory() + @"\Log";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = path + $@"\InterceptLog-{DateTime.Now.ToString("yyyyMMdd")}.log";
StreamWriter sw = File.AppendText(fileName);
sw.WriteLine(dataIntercept);
sw.Close();
}
19
Source : ExceptionJsonHandler.cs
with GNU General Public License v3.0
from Caijt
with GNU General Public License v3.0
from Caijt
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
ResultDto resultDto;
//检测是否是业务抛出的异常
if (ex is ResultException)
{
resultDto = (ex as ResultException).result;
}
else
{
//异常处理
var exceptionGuid = Guid.NewGuid();
string path = Path.Combine(Directory.GetCurrentDirectory(), "Log");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = Path.Combine(path, $"ExceptionLog-{DateTime.Now.ToString("yyyyMMdd")}.log");
using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
string exceptionContent =
$"{DateTime.Now.ToString()}\r\n" +
$"异常Id:{exceptionGuid.ToString()}\r\n" +
$"请求Url:{context.Request.Path}\r\n" +
$"发生异常的方法:{ex.TargetSite.DeclaringType?.FullName}.{ex.TargetSite.Name}\r\n" +
//$"参数:{string.Join(",", ex.TargetSite..Select(a => (a ?? "").ToString()))} " +
$"异常信息:{ex.Message}\r\n" +
$"{ex.StackTrace}\r\n";
sw.WriteLine(exceptionContent);
}
}
resultDto = new ResultDto<Guid>()
{
Code = -1,
Message = ex.Message,
Data = exceptionGuid
};
}
context.Response.ContentType = "application/json";
var setting = new JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
string resultString = JsonConvert.SerializeObject(resultDto, setting);
await context.Response.WriteAsync(resultString).ConfigureAwait(false);
}
}
19
Source : EFLogger.cs
with GNU General Public License v3.0
from Caijt
with GNU General Public License v3.0
from Caijt
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var sqlContent = formatter(state, exception);
//TODO: 拿到日志内容想怎么玩就怎么玩吧
if (logLevel >= LogLevel.Information)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "SqlLog");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = Path.Combine(path, $"Log-{DateTime.Now.ToString("yyyyMMdd")}.log");
using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
string logContent = $"**************{DateTime.Now.ToString()}**************\r\n" +
$"{logLevel.ToString()}\r\n" + sqlContent;
sw.WriteLine(logContent);
}
}
}
}
19
Source : BusinessUser.cs
with MIT License
from Cankirism
with MIT License
from Cankirism
private UsersProperties GetUserProperties(DirectoryEntry de)
{
SearchResult searchResult = user.SetSearchResult(de);
var usersProperties = new UsersProperties();
usersProperties.cannonicalName = de.Properties["cn"].Value.ToString();
usersProperties.samAccountName = de.Properties["samaccountname"][0].ToString();
usersProperties.userAccountControlCode = de.Properties["useraccountcontrol"][0].ToString();
usersProperties.userAccountControl = UserAccountControl(Convert.ToInt32(de.Properties["useraccountcontrol"][0]));
usersProperties.whenCreated = Convert.ToDateTime(de.Properties["whenCreated"].Value).ToLocalTime().ToString();
usersProperties.pwdLastSet = DateTime.FromFileTime((long)searchResult.Properties["pwdLastSet"][0]).ToShortDateString();
usersProperties.lastLogon = DateTime.FromFileTime((long)searchResult.Properties["lastLogon"][0]).ToLocalTime().ToString();
return usersProperties;
}
19
Source : BusinessComputer.cs
with MIT License
from Cankirism
with MIT License
from Cankirism
public IEnumerable<ComputersProperties> GetAllComputers()
{
List<ComputersProperties> computerPropertiesList = new List<ComputersProperties>();
using (var principialContext = _computer.SetPrincipialContext())
using (var computerPrincipial = _computer.SetComputerPrincipial(principialContext))
using (var principialSearcher = _computer.SetPrincipialSearcher())
{
computerPrincipial.Name = "*";
principialSearcher.QueryFilter = computerPrincipial;
PrincipalSearchResult<Principal> _computerSearchResult = principialSearcher.FindAll();
foreach (var p in _computerSearchResult)
{
ComputerPrincipal pc = (ComputerPrincipal)p;
string ipAdress = GetComputerIpAddress(p.Name);
var computerPro = new ComputersProperties(pc.Name, pc.Sid.ToString(), ipAdress, pc.LastPreplacedwordSet.ToString(), pc.LastBadPreplacedwordAttempt.ToString());
computerPropertiesList.Add(computerPro);
}
}
return computerPropertiesList;
}
19
Source : DisplayableLog.cs
with MIT License
from carina-studio
with MIT License
from carina-studio
CompressedString FormatTimestamp(DateTime? timestamp)
{
var level = this.Group.SaveMemoryAgressively ? CompressedString.Level.Fast : CompressedString.Level.None;
var format = this.Group.LogProfile.TimestampFormatForDisplaying;
if (timestamp == null)
return CompressedString.Empty;
if (format != null)
return CompressedString.Create(timestamp.Value.ToString(format), level).AsNonNull();
return CompressedString.Create(timestamp.Value.ToString(), level).AsNonNull();
}
19
Source : InterceptaSQL.cs
with MIT License
from carloscds
with MIT License
from carloscds
private void EscreveLog(string s)
{
StreamWriter log = File.AppendText(arquivoLog);
log.WriteLine(string.Format("{0} - {1}\n", DateTime.Now.ToString(), s));
log.Close();
}
19
Source : CurrentTime.cs
with MIT License
from carloscds
with MIT License
from carloscds
public string GetCurrentTime()
{
return DateTime.Now.ToString();
}
19
Source : TokenModule.cs
with MIT License
from catcherwong
with MIT License
from catcherwong
private string GetJwt(string client_id, IAppConfiguration appConfig)
{
var now = DateTime.UtcNow;
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, client_id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64)
};
var symmetricKeyAsBase64 = appConfig.Audience.Secret;
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
var jwt = new JwtSecurityToken(
issuer: appConfig.Audience.Iss,
audience: appConfig.Audience.Aud,
claims: claims,
notBefore: now,
expires: now.Add(TimeSpan.FromMinutes(2)),
signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256));
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var response = new
{
access_token = encodedJwt,
expires_in = (int)TimeSpan.FromMinutes(2).TotalSeconds
};
return JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented });
}
See More Examples