System.DateTime.ToString(string)

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 7

19 Source : Loger.cs
with Apache License 2.0
from AantCoder

private static void LogWrite(string msg, bool withCatch, int threadId = 0)
        {
            var thn = threadId != 0 ? threadId : Thread.CurrentThread.ManagedThreadId;
            var dn = DateTime.Now;
            var dd = !LastMsg.ContainsKey(thn) ? 0 : (long)(dn - LastMsg[thn]).TotalMilliseconds;
            LastMsg[thn] = dn;
            if (dd >= 1000000) dd = 0;
            var logMsg = dn.ToString(Culture) + " |" + dd.ToString().PadLeft(6) + " |" + thn.ToString().PadLeft(4) + " | " + msg;
            var fileName = $"Log_{DateTime.Now.ToString("yyyy-MM-dd")}_{MainHelper.RandomSeed}.txt";

            if (withCatch) Console.WriteLine(logMsg);
            lock (ObjLock)
            {
                try
                {
                    //if (LogMessage != null) LogMessage(logMsg);
                    File.AppendAllText(PathLog + fileName, logMsg + Environment.NewLine, Encoding.UTF8);
                }
                catch (Exception exp)
                {
                    if (withCatch)
                    {
                        LogErr = "Log exception: " + exp.Message + Environment.NewLine + logMsg;
                        LogErrThr = thn;
                    }
                }
            }
        }

19 Source : RepositorySaveData.cs
with Apache License 2.0
from AantCoder

public List<string> GetListPlayerDatas(string login)
        {
            return GetListPlayerFiles(login)
                .Select(fn => new FileInfo(fn).LastWriteTime.ToString("yyyy-MM-dd"))
                .ToList();
        }

19 Source : ServerManager.cs
with Apache License 2.0
from AantCoder

public void SavePlayerStatisticsFile()
        {
            try
            {
                var msg = "Command SaveListPlayerFileStats";
                Loger.Log(msg);

                Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);

                var content = $"Login;LastOnlineTime;LastOnlineDay;GameDays;BaseCount;CaravanCount;MarketValue;MarketValuePawn" +
                    $";AttacksWonCount;AttacksInitiatorCount;ColonistsCount;ColonistsDownCount;ColonistsBleedCount;PawnMaxSkill" +
                    $";KillsHumanlikes;KillsMechanoids;KillsBestPawnHN;KillsBestPawnH;KillsBestPawnMN;KillsBestPawnM" +
                    $";Grants;EnablePVP;EMail;DiscordUserName;IntruderKeys;StartMarketValue;StartMarketValuePawn" +
                    $";MarketValueBy15Day;MarketValuePawnBy15Day;MarketValueByHour;MarketValuePawnByHour;TicksByHour;HourInGame" + Environment.NewLine;
                foreach (var player in Repository.GetData.PlayersAll)
                {
                    var costAll = player.CostWorldObjects();

                    var newLine = $"{player.Public.Login};" +
                        $"{dateTimeToStr(player.Public.LastOnlineTime)};" +
                        $"{(int)(DateTime.UtcNow - player.Public.LastOnlineTime).TotalDays};" +
                        $"{(int)(player.Public.LastTick / 60000)};" +
                        $"{costAll.BaseCount};" +
                        $"{costAll.CaravanCount};" +
                        $"{costAll.MarketValue};" +
                        $"{costAll.MarketValuePawn};" +
                        $"{player.AttacksWonCount};" +
                        $"{player.AttacksInitiatorCount};" +
                        $"{player.GameProgress?.ColonistsCount};" +
                        $"{player.GameProgress?.ColonistsDownCount};" +
                        $"{player.GameProgress?.ColonistsBleedCount};" +
                        $"{player.GameProgress?.PawnMaxSkill};" +
                        $"{player.GameProgress?.KillsHumanlikes};" +
                        $"{player.GameProgress?.KillsMechanoids};" +
                        $"{player.GameProgress?.KillsBestHumanlikesPawnName};" +
                        $"{player.GameProgress?.KillsBestHumanlikes};" +
                        $"{player.GameProgress?.KillsBestMechanoidsPawnName};" +
                        $"{player.GameProgress?.KillsBestMechanoids};" +
                        $"{player.Public.Grants.ToString()};" +
                        $"{(player.Public.EnablePVP ? 1 : 0)};" +
                        $"{player.Public.EMail};" +
                        $"{player.Public.DiscordUserName};" +
                        $"{player.IntruderKeys};" +
                        $"{player.StartMarketValue};" +
                        $"{player.StartMarketValuePawn};" +
                        $"{player.StatMaxDeltaGameMarketValue};" +
                        $"{player.StatMaxDeltaGameMarketValuePawn};" +
                        $"{player.StatMaxDeltaRealMarketValue};" +
                        $"{player.StatMaxDeltaRealMarketValuePawn};" +
                        $"{player.StatMaxDeltaRealTicks};" +
                        $"{player.TotalRealSecond / 60f / 60f};"
                        ;
                    newLine = newLine.Replace(Environment.NewLine, " ")
                        .Replace("/r", "").Replace("/n", "");

                    content += newLine + Environment.NewLine;
                }

                var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
                    , $"Players_{DateTime.Now.ToString("yyyy-MM-dd_hh-mm")}.csv");
                File.WriteAllText(fileName, content, Encoding.UTF8);
            }
            catch (Exception e)
            {
                Loger.Log("Command Exception " + e.ToString());
            }
        }

19 Source : CommonUtils.cs
with Apache License 2.0
from AantCoder

static string Process(object obj, int level, string prefLine, Dictionary<object, int> forParentLink, HashSet<string> excludeTypes)
        {
            try
            {
                if (obj == null) return "";
                Type type = obj.GetType();
                if (excludeTypes.Contains(type.Name)) return "<skip>";
                if (type == typeof(DateTime))
                {
                    return ((DateTime)obj).ToString("g");
                }
                else if (type.IsValueType || type == typeof(string))
                {
                    return obj.ToString();
                }
                else if (type.IsArray || obj is IEnumerable)
                {
                    string elementType = null;
                    Array array = null;

                    if (type.IsArray)
                    {
                        var tt = Type.GetType(type.FullName.Replace("[]", string.Empty));
                        if (tt != null)
                        {
                            elementType = tt.ToString();
                            if (excludeTypes.Contains(tt.Name)) return "<skips>";
                        }
                        //else return "<EEEEEEE" + type.FullName;
                        array = obj as Array;
                    }
                    else
                    {
                        //как лучше узнать кол-во и тип?
                        int cnt = 0;
                        foreach (var o in obj as IEnumerable) cnt++;
                        array = Array.CreateInstance(typeof(object), cnt);
                        int i = 0;
                        foreach (var o in obj as IEnumerable)
                        {
                            if (elementType == null && o != null)
                            {
                                var tt = o.GetType();
                                if (excludeTypes.Contains(tt.Name)) return "<skips>";
                                elementType = tt.ToString();
                            }
                            array.SetValue(o, i++);
                        }
                    }

                    if (elementType == null) elementType = "Object";

                    if (excludeTypes.Contains(elementType)) return "<skips>";

                    var info = "<" + elementType + "[" + array.Length.ToString() + "]" + ">";

                    if (level == 0)
                    {
                        return info + "[...]";
                    }

                    if (array.Length > 0)
                    {
                        var ress = new string[array.Length];
                        var resl = 0;
                        for (int i = 0; i < array.Length; i++)
                        {
                            ress[i] = Process(array.GetValue(i), level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "[" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "]";
                        }
                        else
                        {
                            var res = info + "["
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "]";
                        }
                    }
                    return info + "[]";
                }
                else if (obj is Type) return "<Type>" + obj.ToString();
                else if (type.IsClreplaced)
                {
                    var info = "<" + type.Name + ">";

                    if (forParentLink.ContainsKey(obj))
                    {
                        if (forParentLink[obj] >= level)
                            return info + "{duplicate}";
                        else
                            forParentLink[obj] = level;
                    }
                    else
                        forParentLink.Add(obj, level);

                    if (level == 0)
                    {
                        return info + "{...}";
                    }

                    FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                                BindingFlags.NonPublic | BindingFlags.Instance);

                    if (fields.Length > 0)
                    {
                        var ress = new string[fields.Length];
                        var resl = 0;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            object fieldValue = fields[i].GetValue(obj);
                            ress[i] = fieldValue == null
                                ? fields[i].Name + ": null"
                                : fields[i].Name + ": " + Process(fieldValue, level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "{" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "}";
                        }
                        else
                        {
                            var res = info + "{"
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "}";
                        }
                    }
                    return info + "{}";
                }
                else
                    throw new ArgumentException("Unknown type");
            }
            catch
            {
                return "<exception>";
            }
        }

19 Source : CallIncident.cs
with Apache License 2.0
from AantCoder

public static void IncidentLogAppend(string record, ModelMailStartIncident mail, string data, int fromWorth = 0, int toWorth = 0)
        {
            Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);

            var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
                , $"Incidents_{DateTime.Now.ToString("yyyy-MM")}.csv");
            if (!File.Exists(fileName))
            { 
                File.WriteAllText(fileName, $"time;record" +
                    $";fromLogin;toLogin;fromDay;toDay;fromWorth;toWorth;paramIncident;serverId" +
                    //структура data:
                    $";worthTarget;delayAfterMail;numberOrder;countInOrder" + 
                    Environment.NewLine, Encoding.UTF8);
            }

            if (fromWorth == 0) fromWorth = (int)Repository.GetPlayerByLogin(mail.From.Login).AllCostWorldObjects();
            if (toWorth == 0) toWorth = (int)Repository.GetPlayerByLogin(mail.To.Login).AllCostWorldObjects();

            var param = $"{mail.IncidentType} lvl:{mail.IncidentMult} mode:{mail.IncidentArrivalMode} who:{mail.IncidentFaction}";

            var contentLog = dateTimeToStr(DateTime.Now) + ";" + record
                + $";{mail.From.Login};{mail.To.Login};{mail.From.LastTick / 60000};{mail.To.LastTick / 60000};{fromWorth};{toWorth};{param};{mail.PlaceServerId}"
                + ";" + data + Environment.NewLine;

            Loger.Log("IncidentLogAppend. " + contentLog);

            try
            {
                File.AppendAllText(fileName, contentLog, Encoding.UTF8);
            }
            catch
            {
                try
                {
                    File.AppendAllText(fileName + "add", contentLog, Encoding.UTF8);
                }
                catch
                {
                    Loger.Log("IncidentLogAppend. Error write file " + fileName);
                }
            }
        }

19 Source : SettingViewModel.cs
with MIT License
from Abdesol

public void SyncCommand(string syncType)
        {
            string message = "";

            if(syncType == "Import")
            {
                var fileDialog = new OpenFileDialog();
                fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                fileDialog.DefaultExt = "whl";
                fileDialog.Filter = "whl files (*.whl)|*.whl";
                var dialogResult = fileDialog.ShowDialog();

                if (dialogResult != DialogResult.Cancel && !string.IsNullOrEmpty(fileDialog.FileName))
                {
                    message = database.ImportData(fileDialog.FileName);
                }
            }
            else
            {
                var fileDialog = new SaveFileDialog();
                fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                fileDialog.DefaultExt = "whl";
                fileDialog.FileName = $"Export_CutCode_{DateTime.Now.ToString("yyyyMMddhhmmss")}.whl";
                fileDialog.Filter = "whl files (*.whl)|*.whl";
                var dialogResult = fileDialog.ShowDialog();
                if (dialogResult != DialogResult.Cancel)
                {
                    message = database.ExportData(fileDialog.FileName);
                }
            }
            if(!string.IsNullOrEmpty(message)) notificationManager.CreateNotification(message, 4);
        }

19 Source : ExtensionMethods.cs
with MIT License
from Abdesol

[Conditional("DEBUG")]
		public static void Log(bool condition, string format, params object[] args)
		{
			if (condition) {
				string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args) + Environment.NewLine + Environment.StackTrace;
				Console.WriteLine(output);
				Debug.WriteLine(output);
			}
		}

19 Source : SimRuntime.cs
with MIT License
from abdullin

public string GetSimulationFolder() {
            if (_folder != null) {
                return _folder;
            }

            // HINT: create a memory disk here
            var root = "/Volumes/SimDisk";
            if (!Directory.Exists(root)) {
                root = Path.GetTempPath();
            }

            var folder = Path.Combine(root, "sim", DateTime.UtcNow.ToString("yy-MM-dd-HH-mm-ss"));
            _folder = folder;
            return folder;
        }

19 Source : WindowsMixedRealityHandRecorder.cs
with Apache License 2.0
from abist-co-ltd

public void RecordHandStop()
        {
            MixedRealityPose[] jointPoses = new MixedRealityPose[jointCount];
            for (int i = 0; i < jointCount; ++i)
            {
                HandJointUtils.TryGetJointPose((TrackedHandJoint)i, recordingHand, out jointPoses[i]);
            }

            ArticulatedHandPose pose = new ArticulatedHandPose();
            pose.ParseFromJointPoses(jointPoses, recordingHand, Quaternion.idenreplacedy, offset);

            recordingHand = Handedness.None;

            var filename = String.Format("{0}-{1}.json", OutputFileName, DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"));
            StoreRecordedHandPose(pose.ToJson(), filename);
        }

19 Source : InputAnimationSerializationUtils.cs
with Apache License 2.0
from abist-co-ltd

public static string GetOutputFilename(string baseName="InputAnimation", bool appendTimestamp=true)
        {
            string filename;
            if (appendTimestamp)
            {
                filename = String.Format("{0}-{1}.{2}", baseName, DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"), InputAnimationSerializationUtils.Extension);
            }
            else
            {
                filename = baseName;
            }
            return filename;
        }

19 Source : OVRCubemapCapture.cs
with MIT License
from absurd-joy

public static bool SaveCubemapCapture(Cubemap cubemap, string pathName = null)
	{
		string fileName;
		string dirName;
		int width = cubemap.width;
		int height = cubemap.height;
		int x = 0;
		int y = 0;
		bool saveToPNG = true;

		if (string.IsNullOrEmpty(pathName))
		{
			dirName = Application.persistentDataPath + "/OVR_ScreenShot360/";
			fileName = null;
		}
		else
		{
			dirName = Path.GetDirectoryName(pathName);
			fileName = Path.GetFileName(pathName);

			if (dirName[dirName.Length - 1] != '/' || dirName[dirName.Length - 1] != '\\')
				dirName += "/";
		}

		if (string.IsNullOrEmpty(fileName))
			fileName = "OVR_" + System.DateTime.Now.ToString("hh_mm_ss") + ".png";

		string extName = Path.GetExtension(fileName);
		if (extName == ".png")
		{
			saveToPNG = true;
		}
		else if (extName == ".jpg")
		{
			saveToPNG = false;
		}
		else
		{
            Debug.LogError("Unsupported file format" + extName);
			return false;
		}

		// Validate path
		try
		{
			System.IO.Directory.CreateDirectory(dirName);
		}
		catch (System.Exception e)
		{
            Debug.LogError("Failed to create path " + dirName + " since " + e.ToString());
			return false;
		}


		// Create the new texture
		Texture2D tex = new Texture2D(width * 6, height, TextureFormat.RGB24, false);
		if (tex == null)
		{
			Debug.LogError("[OVRScreenshotWizard] Failed creating the texture!");
			return false;
		}

		// Merge all the cubemap faces into the texture
		// Reference cubemap format: http://docs.unity3d.com/Manual/clreplaced-Cubemap.html
		CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
		for (int i = 0; i < faces.Length; i++)
		{
			// get the pixels from the cubemap
			Color[] srcPixels = null;
			Color[] pixels = cubemap.GetPixels(faces[i]);
			// if desired, flip them as they are ordered left to right, bottom to top
			srcPixels = new Color[pixels.Length];
			for (int y1 = 0; y1 < height; y1++)
			{
				for (int x1 = 0; x1 < width; x1++)
				{
					srcPixels[y1 * width + x1] = pixels[((height - 1 - y1) * width) + x1];
				}
			}
			// Copy them to the dest texture
			tex.SetPixels(x, y, width, height, srcPixels);
			x += width;
		}

        try
        {
            // Encode the texture and save it to disk
            byte[] bytes = saveToPNG ? tex.EncodeToPNG() : tex.EncodeToJPG();

            System.IO.File.WriteAllBytes(dirName + fileName, bytes);
            Debug.Log("Cubemap file created " + dirName + fileName);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Failed to save cubemap file since " + e.ToString());
			return false;
        }

		DestroyImmediate(tex);
		return true;
	}

19 Source : VitalSignsIndicatorsProvider.cs
with MIT License
from ABTSoftware

private static string GetTimeString()
        {
            return DateTime.Now.ToString("HH:mm");
        }

19 Source : App.xaml.cs
with MIT License
from ABTSoftware

private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.Args.Contains(_devMode, StringComparer.InvariantCultureIgnoreCase))
            {
                DeveloperModManager.Manage.IsDeveloperMode = true;
            }

            if (e.Args.Contains(_quickStart, StringComparer.InvariantCultureIgnoreCase))
            {
                // Used in automation testing, disable animations and delays in transitions 
                UIAutomationTestMode = true;
                SeriesAnimationBase.GlobalEnableAnimations = false;
            }

            try
            {
                Thread.CurrentThread.Name = "UI Thread";

                Log.Debug("--------------------------------------------------------------");
                Log.DebugFormat("SciChart.Examples.Demo: Session Started {0}",
                    DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"));
                Log.Debug("--------------------------------------------------------------");

                var replacedembliesToSearch = new[]
                {
                    typeof (MainWindowViewModel).replacedembly,
                    typeof (AbtBootstrapper).replacedembly, // SciChart.UI.Bootstrap
                    typeof (IViewModelTrait).replacedembly, // SciChart.UI.Reactive 
                };

                _bootStrapper = new Bootstrapper(ServiceLocator.Container, new AttributedTypeDiscoveryService(new ExplicitreplacedemblyDiscovery(replacedembliesToSearch)));
                _bootStrapper.InitializeAsync().Then(() =>
                {
                    if (!UIAutomationTestMode)
                    {
                        // Do this on background thread
                        Task.Run(() =>
                        {
                            //Syncing usages 
                            var syncHelper = ServiceLocator.Container.Resolve<ISyncUsageHelper>();
                            syncHelper.LoadFromIsolatedStorage();

                            //Try sync with service
                            syncHelper.GetRatingsFromServer();
                            syncHelper.SendUsagesToServer();
                            syncHelper.SetUsageOnExamples();
                        });
                    }

                    _bootStrapper.OnInitComplete();
                }).Catch(ex =>
                {
                    Log.Error("Exception:\n\n{0}", ex);
                    MessageBox.Show("Exception occurred in SciChart.Examples.Demo.\r\n. Please send log files located at %CurrentUser%\\AppData\\Local\\SciChart\\SciChart.Examples.Demo.log to support");
                });
            }
            catch (Exception caught)
            {
                Log.Error("Exception:\n\n{0}", caught);
                MessageBox.Show("Exception occurred in SciChart.Examples.Demo.\r\n. Please send log files located at %CurrentUser%\\AppData\\Local\\SciChart\\SciChart.Examples.Demo.log to support");
            }
        }

19 Source : SyncUsageHelper.cs
with MIT License
from ABTSoftware

public void WriteToIsolatedStorage()
        {
            try
            {
                using (var isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.replacedembly,
                    null, null))
                {
                    using (var stream = new IsolatedStorageFileStream("Usage.xml", FileMode.Create, isf))
                    {
                        var xml = SerializationUtil.Serialize(
                            _usageCalculator.Usages.Values.Where(e => e.VisitCount > 0));
                        xml.Root.Add(new XAttribute("UserId", userId));
                        xml.Root.Add(new XAttribute("Enabled", Enabled));
                        xml.Root.Add(new XAttribute("LastSent", lastSent.ToString("o")));

                        using (var stringWriter = new StringWriter())
                        {
                            xml.Save(stringWriter);

                            var encryptedUsage = _encryptionHelper.Encrypt(stringWriter.ToString());
                            using (StreamWriter writer = new StreamWriter(stream))
                            {
                                writer.Write(encryptedUsage);
                            }
                        }
                    }
                }
            }
            catch { }
        }

19 Source : UsageServiceClient.cs
with MIT License
from ABTSoftware

private string GetAuthHeader(string username)
        {
            // Get salt
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] four_bytes = new byte[4];
            rng.GetBytes(four_bytes);
            var salt = BitConverter.ToUInt32(four_bytes, 0).ToString();
            // Get timestamp
            string timestamp = DateTime.UtcNow.ToString("o");
            // create signature
            string rawSig = (username ?? "") + timestamp + salt;
            var encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secretKey);
            byte[] messageBytes = encoding.GetBytes(rawSig);
            string signature;
            // hash and base64 encode 
            using (var sha256 = new HMACSHA256(keyByte))
            {
                byte[] hashMessage = sha256.ComputeHash(messageBytes);
                signature = Convert.ToBase64String(hashMessage);
            }
            // build auth header
            return timestamp + "," + salt + "," + signature;
        }

19 Source : ValidateDateFormatStringConverter.cs
with MIT License
from ABTSoftware

private static object ValidateFormatString(object value)
        {
            try
            {
                var testDate = new DateTime(2013, 03, 2);

                testDate.ToString((string) value);
            }
            catch 
            {
                return null;
            }
            return value;
        }

19 Source : OADateLabelProvider.cs
with MIT License
from ABTSoftware

public override string FormatLabel(IComparable dataValue)
        {
            var nAxis = ParentAxis as NumericAxis3D;
            if (nAxis == null)
            {
                throw new InvalidOperationException("The DateTimeLabelFormatter is only valid on instances of DateTimeAxis");
            }

            var oadt = dataValue.ToDouble();
            var dt = DateTime.FromOADate(oadt);

            return dt.ToString("hh:mm:ss");
        }

19 Source : RecordCast.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void Output(string line)
        {
            var timestamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss,fff");

            var timestamp_line = $"[{timestamp}] {line}";

            Buffer.AppendLine(timestamp_line);
            Console.WriteLine(timestamp_line);
        }

19 Source : Corpse.cs
with GNU Affero General Public License v3.0
from ACEmulator

protected override void OnInitialInventoryLoadCompleted()
        {
            if (Level.HasValue)
            {
                var dtTimeToRot = DateTime.UtcNow.AddSeconds(TimeToRot ?? 0);
                var tsDecay = dtTimeToRot - DateTime.UtcNow;

                log.Debug($"[CORPSE] {Name} (0x{Guid}) Reloaded from Database: Corpse Level: {Level ?? 0} | InventoryLoaded: {InventoryLoaded} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now.");
            }
        }

19 Source : Corpse.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void RecalculateDecayTime(Player player)
        {
            // empty corpses decay faster
            if (Inventory.Count == 0)
                TimeToRot = EmptyDecayTime;
            else
                // a player corpse decays after 5 mins * playerLevel with a minimum of 1 hour
                TimeToRot = Math.Max(3600, (player.Level ?? 1) * 300);

            var dtTimeToRot = DateTime.UtcNow.AddSeconds(TimeToRot ?? 0);
            var tsDecay = dtTimeToRot - DateTime.UtcNow;

            Level = player.Level ?? 1;

            log.Debug($"[CORPSE] {Name}.RecalculateDecayTime({player.Name}) 0x{Guid}: Player Level: {player.Level} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now.");
        }

19 Source : HostContext.cs
with MIT License
from actions

public void WritePerfCounter(string counter)
        {
            if (!string.IsNullOrEmpty(_perfFile))
            {
                string normalizedCounter = counter.Replace(':', '_');
                lock (_perfLock)
                {
                    try
                    {
                        File.AppendAllLines(_perfFile, new[] { $"{normalizedCounter}:{DateTime.UtcNow.ToString("O")}" });
                    }
                    catch (Exception ex)
                    {
                        _trace.Error(ex);
                    }
                }
            }
        }

19 Source : Logging.cs
with MIT License
from actions

public void Write(string message)
        {
            // lazy creation on write
            if (_pageWriter == null)
            {
                Create();
            }

            string line = $"{DateTime.UtcNow.ToString("O")} {message}";
            _pageWriter.WriteLine(line);

            _totalLines++;
            if (line.IndexOf('\n') != -1)
            {
                foreach (char c in line)
                {
                    if (c == '\n')
                    {
                        _totalLines++;
                    }
                }
            }

            _byteCount += System.Text.Encoding.UTF8.GetByteCount(line);
            if (_byteCount >= PageSize)
            {
                NewPage();
            }
        }

19 Source : CheckUtil.cs
with MIT License
from actions

public static async Task<CheckResult> CheckDns(string targetUrl)
        {
            var result = new CheckResult();
            var url = new Uri(targetUrl);
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Try DNS lookup for {url.Host} ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                IPHostEntry host = await Dns.GetHostEntryAsync(url.Host);
                foreach (var address in host.AddressList)
                {
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Resolved DNS for {url.Host} to '{address}'");
                }

                result.Preplaced = true;
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Resolved DNS for {url.Host} failed with error: {ex}");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return result;
        }

19 Source : CheckUtil.cs
with MIT License
from actions

public static async Task<CheckResult> CheckPing(string targetUrl)
        {
            var result = new CheckResult();
            var url = new Uri(targetUrl);
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Try ping {url.Host} ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                using (var ping = new Ping())
                {
                    var reply = await ping.SendPingAsync(url.Host);
                    if (reply.Status == IPStatus.Success)
                    {
                        result.Preplaced = true;
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Ping {url.Host} ({reply.Address}) succeed within to '{reply.RoundtripTime} ms'");
                    }
                    else
                    {
                        result.Preplaced = false;
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Ping {url.Host} ({reply.Address}) failed with '{reply.Status}'");
                    }
                }
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Ping api.github.com failed with error: {ex}");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return result;
        }

19 Source : CheckUtil.cs
with MIT License
from actions

public static async Task<CheckResult> CheckHttpsGetRequests(this IHostContext hostContext, string url, string pat, string expectedHeader)
        {
            var result = new CheckResult();
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Send HTTPS Request (GET) to {url} ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                using (var _ = new HttpEventSourceListener(result.Logs))
                using (var httpClientHandler = hostContext.CreateHttpClientHandler())
                using (var httpClient = new HttpClient(httpClientHandler))
                {
                    httpClient.DefaultRequestHeaders.UserAgent.AddRange(hostContext.UserAgents);
                    if (!string.IsNullOrEmpty(pat))
                    {
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", pat);
                    }

                    var response = await httpClient.GetAsync(url);

                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http status code: {response.StatusCode}");
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http response headers: {response.Headers}");

                    var responseContent = await response.Content.ReadreplacedtringAsync();
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http response body: {responseContent}");
                    if (response.IsSuccessStatusCode)
                    {
                        if (response.Headers.Contains(expectedHeader))
                        {
                            result.Preplaced = true;
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'GET' to {url} succeed");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        }
                        else
                        {
                            result.Preplaced = false;
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'GET' to {url} succeed but doesn't have expected HTTP response Header '{expectedHeader}'.");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        }
                    }
                    else
                    {
                        result.Preplaced = false;
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'GET' to {url} failed with {response.StatusCode}");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                    }
                }
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Https request 'GET' to {url} failed with error: {ex}");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return result;
        }

19 Source : CheckUtil.cs
with MIT License
from actions

public static async Task<CheckResult> CheckHttpsPostRequests(this IHostContext hostContext, string url, string pat, string expectedHeader)
        {
            var result = new CheckResult();
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Send HTTPS Request (POST) to {url} ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                using (var _ = new HttpEventSourceListener(result.Logs))
                using (var httpClientHandler = hostContext.CreateHttpClientHandler())
                using (var httpClient = new HttpClient(httpClientHandler))
                {
                    httpClient.DefaultRequestHeaders.UserAgent.AddRange(hostContext.UserAgents);
                    if (!string.IsNullOrEmpty(pat))
                    {
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", pat);
                    }

                    // Send empty JSON '{}' to service
                    var response = await httpClient.PostAsJsonAsync<Dictionary<string, string>>(url, new Dictionary<string, string>());

                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http status code: {response.StatusCode}");
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http response headers: {response.Headers}");

                    var responseContent = await response.Content.ReadreplacedtringAsync();
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http response body: {responseContent}");
                    if (response.Headers.Contains(expectedHeader))
                    {
                        result.Preplaced = true;
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'POST' to {url} has expected HTTP response header");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                    }
                    else
                    {
                        result.Preplaced = false;
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Http request 'POST' to {url} doesn't have expected HTTP response Header '{expectedHeader}'.");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                        result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ");
                    }
                }
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Https request 'POST' to {url} failed with error: {ex}");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return result;
        }

19 Source : CheckUtil.cs
with MIT License
from actions

public static async Task<CheckResult> DownloadExtraCA(this IHostContext hostContext, string url, string pat)
        {
            var result = new CheckResult();
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Download SSL Certificate from {url} ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");

                var uri = new Uri(url);
                var env = new Dictionary<string, string>()
                {
                    { "HOSTNAME", uri.Host },
                    { "PORT", uri.IsDefaultPort ? (uri.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : uri.Port.ToString() },
                    { "PATH", uri.AbsolutePath },
                    { "PAT", pat }
                };

                var proxy = hostContext.WebProxy.GetProxy(uri);
                if (proxy != null)
                {
                    env["PROXYHOST"] = proxy.Host;
                    env["PROXYPORT"] = proxy.IsDefaultPort ? (proxy.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : proxy.Port.ToString();
                    if (hostContext.WebProxy.HttpProxyUsername != null ||
                        hostContext.WebProxy.HttpsProxyUsername != null)
                    {
                        env["PROXYUSERNAME"] = hostContext.WebProxy.HttpProxyUsername ?? hostContext.WebProxy.HttpsProxyUsername;
                        env["PROXYPreplacedWORD"] = hostContext.WebProxy.HttpProxyPreplacedword ?? hostContext.WebProxy.HttpsProxyPreplacedword;
                    }
                    else
                    {
                        env["PROXYUSERNAME"] = "";
                        env["PROXYPreplacedWORD"] = "";
                    }
                }
                else
                {
                    env["PROXYHOST"] = "";
                    env["PROXYPORT"] = "";
                    env["PROXYUSERNAME"] = "";
                    env["PROXYPreplacedWORD"] = "";
                }

                using (var processInvoker = hostContext.CreateService<IProcessInvoker>())
                {
                    processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data))
                        {
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDOUT] {args.Data}");
                        }
                    });

                    processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data))
                        {
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDERR] {args.Data}");
                        }
                    });

                    var downloadCertScript = Path.Combine(hostContext.GetDirectory(WellKnownDirectory.Bin), "checkScripts", "downloadCert");
                    var node12 = Path.Combine(hostContext.GetDirectory(WellKnownDirectory.Externals), "node12", "bin", $"node{IOUtil.ExeExtension}");
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Run '{node12} \"{downloadCertScript}\"' ");
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} {StringUtil.ConvertToJson(env)}");
                    await processInvoker.ExecuteAsync(
                        hostContext.GetDirectory(WellKnownDirectory.Root),
                        node12,
                        $"\"{downloadCertScript}\"",
                        env,
                        true,
                        CancellationToken.None);
                }

                result.Preplaced = true;
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Download SSL Certificate from '{url}' failed with error: {ex}");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return result;
        }

19 Source : CheckUtil.cs
with MIT License
from actions

protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            base.OnEventWritten(eventData);
            lock (_lock)
            {
                if (_ignoredEvent.TryGetValue(eventData.EventSource.Name, out var ignored) &&
                    ignored.Contains(eventData.EventName))
                {
                    return;
                }

                _logs.Add($"{DateTime.UtcNow.ToString("O")} [START {eventData.EventSource.Name} - {eventData.EventName}]");
                _logs.AddRange(eventData.Payload.Select(x => string.Join(Environment.NewLine, x.ToString().Split(Environment.NewLine).Select(y => $"{DateTime.UtcNow.ToString("O")} {y}"))));
                _logs.Add($"{DateTime.UtcNow.ToString("O")} [END {eventData.EventSource.Name} - {eventData.EventName}]");
            }
        }

19 Source : GitCheck.cs
with MIT License
from actions

public async Task<bool> RunCheck(string url, string pat)
        {
            await File.AppendAllLinesAsync(_logFile, HostContext.WarnLog());
            await File.AppendAllLinesAsync(_logFile, HostContext.CheckProxy());

            if (string.IsNullOrEmpty(_gitPath))
            {
                await File.AppendAllLinesAsync(_logFile, new[] { $"{DateTime.UtcNow.ToString("O")} Can't verify git with GitHub.com or GitHub Enterprise Server since git is not installed." });
                return false;
            }

            var checkGit = await CheckGit(url, pat);
            var result = checkGit.Preplaced;
            await File.AppendAllLinesAsync(_logFile, checkGit.Logs);

            // try fix SSL error by providing extra CA certificate.
            if (checkGit.SslError)
            {
                await File.AppendAllLinesAsync(_logFile, new[] { $"{DateTime.UtcNow.ToString("O")} Try fix SSL error by providing extra CA certificate." });
                var downloadCert = await HostContext.DownloadExtraCA(url, pat);
                await File.AppendAllLinesAsync(_logFile, downloadCert.Logs);

                if (downloadCert.Preplaced)
                {
                    var recheckGit = await CheckGit(url, pat, extraCA: true);
                    await File.AppendAllLinesAsync(_logFile, recheckGit.Logs);
                    if (recheckGit.Preplaced)
                    {
                        await File.AppendAllLinesAsync(_logFile, new[] { $"{DateTime.UtcNow.ToString("O")} Fixed SSL error by providing extra CA certs." });
                    }
                }
            }

            return result;
        }

19 Source : GitCheck.cs
with MIT License
from actions

private async Task<CheckResult> CheckGit(string url, string pat, bool extraCA = false)
        {
            var result = new CheckResult();
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Validate server cert and proxy configuration with Git ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                var repoUrlBuilder = new UriBuilder(url);
                repoUrlBuilder.Path = "actions/checkout";
                repoUrlBuilder.UserName = "gh";
                repoUrlBuilder.Preplacedword = pat;

                var gitProxy = "";
                var proxy = HostContext.WebProxy.GetProxy(repoUrlBuilder.Uri);
                if (proxy != null)
                {
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Runner is behind http proxy '{proxy.AbsoluteUri}'");
                    if (HostContext.WebProxy.HttpProxyUsername != null ||
                        HostContext.WebProxy.HttpsProxyUsername != null)
                    {
                        var proxyUrlWithCred = UrlUtil.GetCredentialEmbeddedUrl(
                            proxy,
                            HostContext.WebProxy.HttpProxyUsername ?? HostContext.WebProxy.HttpsProxyUsername,
                            HostContext.WebProxy.HttpProxyPreplacedword ?? HostContext.WebProxy.HttpsProxyPreplacedword);
                        gitProxy = $"-c http.proxy={proxyUrlWithCred}";
                    }
                    else
                    {
                        gitProxy = $"-c http.proxy={proxy.AbsoluteUri}";
                    }
                }

                using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
                {
                    processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data))
                        {
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} {args.Data}");
                        }
                    });

                    processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data))
                        {
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} {args.Data}");
                        }
                    });

                    var gitArgs = $"{gitProxy} ls-remote --exit-code {repoUrlBuilder.Uri.AbsoluteUri} HEAD";
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Run 'git {gitArgs}' ");

                    var env = new Dictionary<string, string>
                    {
                        { "GIT_TRACE", "1" },
                        { "GIT_CURL_VERBOSE", "1" }
                    };

                    if (extraCA)
                    {
                        env["GIT_SSL_CAINFO"] = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), "download_ca_cert.pem");
                    }

                    await processInvoker.ExecuteAsync(
                        HostContext.GetDirectory(WellKnownDirectory.Root),
                        _gitPath,
                        gitArgs,
                        env,
                        true,
                        CancellationToken.None);
                }

                result.Preplaced = true;
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     git ls-remote failed with error: {ex}");
                if (result.Logs.Any(x => x.Contains("SSL Certificate problem", StringComparison.OrdinalIgnoreCase)))
                {
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     git ls-remote failed due to SSL cert issue.");
                    result.SslError = true;
                }
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");

            }

            return result;
        }

19 Source : NodeJsCheck.cs
with MIT License
from actions

public async Task<bool> RunCheck(string url, string pat)
        {
            await File.AppendAllLinesAsync(_logFile, HostContext.WarnLog());
            await File.AppendAllLinesAsync(_logFile, HostContext.CheckProxy());

            // Request to github.com or ghes server
            var urlBuilder = new UriBuilder(url);
            if (UrlUtil.IsHostedServer(urlBuilder))
            {
                urlBuilder.Host = $"api.{urlBuilder.Host}";
                urlBuilder.Path = "";
            }
            else
            {
                urlBuilder.Path = "api/v3";
            }

            var checkNode = await CheckNodeJs(urlBuilder.Uri.AbsoluteUri, pat);
            var result = checkNode.Preplaced;
            await File.AppendAllLinesAsync(_logFile, checkNode.Logs);

            // try fix SSL error by providing extra CA certificate.
            if (checkNode.SslError)
            {
                var downloadCert = await HostContext.DownloadExtraCA(urlBuilder.Uri.AbsoluteUri, pat);
                await File.AppendAllLinesAsync(_logFile, downloadCert.Logs);

                if (downloadCert.Preplaced)
                {
                    var recheckNode = await CheckNodeJs(urlBuilder.Uri.AbsoluteUri, pat, extraCA: true);
                    await File.AppendAllLinesAsync(_logFile, recheckNode.Logs);
                    if (recheckNode.Preplaced)
                    {
                        await File.AppendAllLinesAsync(_logFile, new[] { $"{DateTime.UtcNow.ToString("O")} Fixed SSL error by providing extra CA certs." });
                    }
                }
            }

            return result;
        }

19 Source : NodeJsCheck.cs
with MIT License
from actions

private async Task<CheckResult> CheckNodeJs(string url, string pat, bool extraCA = false)
        {
            var result = new CheckResult();
            try
            {
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Make Http request to {url} using node.js ");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");

                // Request to github.com or ghes server
                Uri requestUrl = new Uri(url);
                var env = new Dictionary<string, string>()
                {
                    { "HOSTNAME", requestUrl.Host },
                    { "PORT", requestUrl.IsDefaultPort ? (requestUrl.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : requestUrl.Port.ToString() },
                    { "PATH", requestUrl.AbsolutePath },
                    { "PAT", pat }
                };

                var proxy = HostContext.WebProxy.GetProxy(requestUrl);
                if (proxy != null)
                {
                    env["PROXYHOST"] = proxy.Host;
                    env["PROXYPORT"] = proxy.IsDefaultPort ? (proxy.Scheme.ToLowerInvariant() == "https" ? "443" : "80") : proxy.Port.ToString();
                    if (HostContext.WebProxy.HttpProxyUsername != null ||
                        HostContext.WebProxy.HttpsProxyUsername != null)
                    {
                        env["PROXYUSERNAME"] = HostContext.WebProxy.HttpProxyUsername ?? HostContext.WebProxy.HttpsProxyUsername;
                        env["PROXYPreplacedWORD"] = HostContext.WebProxy.HttpProxyPreplacedword ?? HostContext.WebProxy.HttpsProxyPreplacedword;
                    }
                    else
                    {
                        env["PROXYUSERNAME"] = "";
                        env["PROXYPreplacedWORD"] = "";
                    }
                }
                else
                {
                    env["PROXYHOST"] = "";
                    env["PROXYPORT"] = "";
                    env["PROXYUSERNAME"] = "";
                    env["PROXYPreplacedWORD"] = "";
                }

                if (extraCA)
                {
                    env["NODE_EXTRA_CA_CERTS"] = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), "download_ca_cert.pem");
                }

                using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
                {
                    processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data))
                        {
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDOUT] {args.Data}");
                        }
                    });

                    processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data))
                        {
                            result.Logs.Add($"{DateTime.UtcNow.ToString("O")} [STDERR] {args.Data}");
                        }
                    });

                    var makeWebRequestScript = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "checkScripts", "makeWebRequest.js");
                    var node12 = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "node12", "bin", $"node{IOUtil.ExeExtension}");
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} Run '{node12} \"{makeWebRequestScript}\"' ");
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} {StringUtil.ConvertToJson(env)}");
                    await processInvoker.ExecuteAsync(
                        HostContext.GetDirectory(WellKnownDirectory.Root),
                        node12,
                        $"\"{makeWebRequestScript}\"",
                        env,
                        true,
                        CancellationToken.None);
                }

                result.Preplaced = true;
            }
            catch (Exception ex)
            {
                result.Preplaced = false;
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Make https request to {url} using node.js failed with error: {ex}");
                if (result.Logs.Any(x => x.Contains("UNABLE_TO_VERIFY_LEAF_SIGNATURE") ||
                                         x.Contains("UNABLE_TO_GET_ISSUER_CERT_LOCALLY") ||
                                         x.Contains("SELF_SIGNED_CERT_IN_CHAIN")))
                {
                    result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Https request failed due to SSL cert issue.");
                    result.SslError = true;
                }
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                result.Logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return result;
        }

19 Source : SelfUpdater.cs
with MIT License
from actions

private string GenerateUpdateScript(bool restartInteractiveRunner)
        {
            int processId = Process.GetCurrentProcess().Id;
            string updateLog = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Diag), $"SelfUpdate-{DateTime.UtcNow.ToString("yyyyMMdd-HHmmss")}.log");
            string runnerRoot = HostContext.GetDirectory(WellKnownDirectory.Root);

#if OS_WINDOWS
            string templateName = "update.cmd.template";
#else
            string templateName = "update.sh.template";
#endif

            string templatePath = Path.Combine(runnerRoot, $"bin.{_targetPackage.Version}", templateName);
            string template = File.ReadAllText(templatePath);

            template = template.Replace("_PROCESS_ID_", processId.ToString());
            template = template.Replace("_RUNNER_PROCESS_NAME_", $"Runner.Listener{IOUtil.ExeExtension}");
            template = template.Replace("_ROOT_FOLDER_", runnerRoot);
            template = template.Replace("_EXIST_RUNNER_VERSION_", BuildConstants.RunnerPackage.Version);
            template = template.Replace("_DOWNLOAD_RUNNER_VERSION_", _targetPackage.Version);
            template = template.Replace("_UPDATE_LOG_", updateLog);
            template = template.Replace("_RESTART_INTERACTIVE_RUNNER_", restartInteractiveRunner ? "1" : "0");

#if OS_WINDOWS
            string scriptName = "_update.cmd";
#else
            string scriptName = "_update.sh";
#endif

            string updateScript = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), scriptName);
            if (File.Exists(updateScript))
            {
                IOUtil.DeleteFile(updateScript);
            }

            File.WriteAllText(updateScript, template);
            return updateScript;
        }

19 Source : CheckUtil.cs
with MIT License
from actions

public static List<string> WarnLog(this IHostContext hostContext)
        {
            var logs = new List<string>();
            logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
            logs.Add($"{DateTime.UtcNow.ToString("O")} ****     !!! WARNING !!! ");
            logs.Add($"{DateTime.UtcNow.ToString("O")} ****     DO NOT share the log in public place! The log may contains secrets in plain text. ");
            logs.Add($"{DateTime.UtcNow.ToString("O")} ****     !!! WARNING !!! ");
            logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
            logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            return logs;
        }

19 Source : CheckUtil.cs
with MIT License
from actions

public static List<string> CheckProxy(this IHostContext hostContext)
        {
            var logs = new List<string>();
            if (!string.IsNullOrEmpty(hostContext.WebProxy.HttpProxyAddress) ||
                !string.IsNullOrEmpty(hostContext.WebProxy.HttpsProxyAddress))
            {
                logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
                logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                logs.Add($"{DateTime.UtcNow.ToString("O")} ****     Runner is behind web proxy {hostContext.WebProxy.HttpsProxyAddress ?? hostContext.WebProxy.HttpProxyAddress} ");
                logs.Add($"{DateTime.UtcNow.ToString("O")} ****                                                                                                       ****");
                logs.Add($"{DateTime.UtcNow.ToString("O")} ***************************************************************************************************************");
            }

            return logs;
        }

19 Source : JwtSerializer.cs
with MIT License
from ActiveLogin

public static string GetBirthdate(DateTime birthdate)
        {
            return birthdate.Date.ToString("yyyy-MM-dd");
        }

19 Source : JwtSerializer.cs
with MIT License
from ActiveLogin

public static string GetExpires(DateTimeOffset expiresUtc)
        {
            return expiresUtc.Date.ToString("yyyy-MM-dd");
        }

19 Source : ScreenshotTaker.cs
with Apache License 2.0
from activey

public string ScreenShotName(int width, int height) {

		string strPath="";

		strPath = string.Format("{0}/screen_{1}x{2}_{3}.png", 
		                     path, 
		                     width, height, 
		                               System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
		lastScreenshot = strPath;
	
		return strPath;
	}

19 Source : SetVersionInfoTask.cs
with MIT License
from adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            //increase the build number
            BuildNumber = BuildNumber + 1;

            //process the package version
            var ver = $"{Major}.{Minor}.{Patch}";

            var dt = System.DateTime.Now.ToString("yyMMddHHmmss");

            if (Configuration.ToLower() != "release")
            {
                PackageVersionShort = $"{ver}-dev.{BuildNumber}.{dt}";
                PackageVersionFull = $"{PackageVersionShort}+{GitCommits}.{GitBranch}.{GitCommit}";
            }
            else
            {
                PackageVersionShort = ver;
                PackageVersionFull = $"{PackageVersionShort}+{BuildNumber}.{dt}.{GitBranch}.{GitCommit}";
            }

            //update version file
            var doreplacedent = XDoreplacedent.Load(VersionFile);
            var projectNode = GetOrCreateElement(doreplacedent, "Project");

            SetProjectPropertyNode(projectNode, "RadBuild", BuildNumber.ToString());
            SetProjectPropertyNode(projectNode, "PackageVersionShort", PackageVersionShort);
            SetProjectPropertyNode(projectNode, "PackageVersionFull", PackageVersionFull);
            SetProjectPropertyNode(projectNode, "GitCommit", GitCommit);
            SetProjectPropertyNode(projectNode, "GitBranch", GitBranch);

            File.WriteAllText(VersionFile, doreplacedent.ToString());

            Log.LogMessage($@"Updated version file: version {Major}.{Minor}.{Patch}, package: {PackageVersionFull}, build #{BuildNumber} to {VersionFile}");

            return true;
        }

19 Source : FileManager.cs
with GNU General Public License v3.0
from AdamMYoung

internal static string GetGroupShortcut(GroupViewModel group)
        {
            var appDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
            var folderPath = Path.Combine(appDirectory, @"Groupr\Shortcuts\");

            Regex illegalInFileName = new Regex(@"[\\/:*?""<>|]");
            var fileName = group.Name + " " + DateTime.Now.ToString($"yyyy-MM-dd") + ".lnk";
            var sanitizedFileName = illegalInFileName.Replace(fileName, "");

            var shortcutPath = Path.Combine(folderPath, sanitizedFileName);

            Directory.CreateDirectory(folderPath);
            if (!File.Exists(shortcutPath))
                CreateGroupShortcut(group, shortcutPath);

            return folderPath;
        }

19 Source : Logging.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static string GetTimestamp()
		{
			DateTime now = DateTime.Now;
			return $"[{now.DayOfYear}.{now.Year} @ {now.ToString("HH:mm:ss")}]  ";
		}

19 Source : SearchAutomation.cs
with MIT License
from ADeltaX

private static async Task SearchRun(string name, string ringName)
        {
            var res = await _edgeUpdate.GetLatestFiles(name);
            if (res.Success && !SharedDBcmd.UpdateExists(ringName, res.Value.Version))
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] !!! New update !!! {ringName} - Version: {res.Value.Version}");
                Console.ResetColor();

                var edgeFileFull = res.Value.EdgeFile.Where(file => file.EdgeFileUpdateType == EdgeFileUpdateType.Full).First();
                var SHA1Hex = BitConverter.ToString(edgeFileFull.Sha1).Replace("-", "");
                var SHA256Hex = BitConverter.ToString(edgeFileFull.Sha256).Replace("-", "");

                SharedDBcmd.AddNewUpdate(ring: ringName, version: res.Value.Version,
                                                filename: edgeFileFull.FileName, filesize: edgeFileFull.Size,
                                                sha256: SHA256Hex, url: edgeFileFull.Url);

                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] <<< Downloading from MSEdge fe3 server");
                Console.ResetColor();
                await Download(name, res.Value.Version, edgeFileFull);

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] >>> Uploading to Telegram via TDLib");
                Console.ResetColor();
                await UploadAndSendMessage(edgeFileFull, string.Format(messageEdgeUpdate, ringName, res.Value.Version, SHA1Hex));

            }
        }

19 Source : SearchAutomation.cs
with MIT License
from ADeltaX

private static async Task Download(string name, string version, EdgeFile fileElement, int numTries = 0)
        {
            if (numTries >= _numMaxDLAttempts)
                return;

            try
            {
                string filename = Path.Combine(DownloadFolder, fileElement.FileName);

                if (File.Exists(filename))
                {
                    byte[] fileHash = GetSHA1HashFile(filename);

                    //We already have this update, no need to download it again
                    if (fileHash.SequenceEqual(fileElement.Sha1))
                    {
                        Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] --- The file is already downloaded and valid, using this...");
                        return;
                    }
                    else
                    {
                        File.Delete(filename);
                    }
                }

                using (WebClient wb = new WebClient())
                {
                    await wb.DownloadFileTaskAsync(fileElement.Url, filename);
                    byte[] fileHash = GetSHA1HashFile(filename);

                    if (!fileHash.SequenceEqual(fileElement.Sha1))
                    {
                        if (File.Exists(filename))
                            File.Delete(filename);

                        throw new DataMisalignedException("Rip SHA1 hash");
                    }
                }
            }
            catch (Exception ex)
            {
                var errorMessageIter = ex.Message;

                var currException = ex;

                while ((currException = currException.InnerException) != null)
                    errorMessageIter += "\n\nINNER EXCEPTION: " + currException.Message;

                SharedDBcmd.TraceError($"Internal error: {errorMessageIter}");

                Console.WriteLine("[ERROR] Failed downloading... retrying...");

                //Generate a new link.... just in case
                var res = await _edgeUpdate.GetFiles(name, version);

                if (res.Success)
                {
                    var edgeFileFull = res.Value.EdgeFile.Where(file => file.EdgeFileUpdateType == EdgeFileUpdateType.Full).First();
                    await Download(name, version, edgeFileFull, ++numTries);
                }
                else
                {
                    await Download(name, version, fileElement, ++numTries);
                }
            }
        }

19 Source : SearchAutomation.cs
with MIT License
from ADeltaX

public static bool Execute()
        {
            if (IsRunning)
                return false;

            try
            {
                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] Doing searches.");

                IsRunning = true;

                SearchRun(EdgeUpdate.Canary_Win_x86, "Canary (x86)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Canary_Win_x64, "Canary (x64)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Canary_Win_arm64, "Canary (ARM64)").GetAwaiter().GetResult();

                SearchRun(EdgeUpdate.Dev_Win_x86, "Dev (x86)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Dev_Win_x64, "Dev (x64)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Dev_Win_arm64, "Dev (ARM64)").GetAwaiter().GetResult();

                SearchRun(EdgeUpdate.Beta_Win_x86, "Beta (x86)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Beta_Win_x64, "Beta (x64)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Beta_Win_arm64, "Beta (ARM64)").GetAwaiter().GetResult();

                SearchRun(EdgeUpdate.Stable_Win_x86, "Stable (x86)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Stable_Win_x64, "Stable (x64)").GetAwaiter().GetResult();
                SearchRun(EdgeUpdate.Stable_Win_arm64, "Stable (ARM64)").GetAwaiter().GetResult();
                
                IsRunning = false;

                Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] Finished doing searches.");
                return true;
            }
            catch (Exception ex)
            {
                //RIP
                Console.WriteLine($"[Error] {ex.Message}");
                SharedDBcmd.TraceError($"Internal error: {ex.Message}");
                IsRunning = false;
                return false;
            }
        }

19 Source : DateTimePicker.xaml.cs
with MIT License
from ADeltaX

void ReformatDateText()
		{
			// Changes DateDisplay.Text to match the current DateFormat
			DateTime? date = ParseDateText(true);
			if (date != null)
			{
				string newText = date.Value.ToString(DateFormat);
				if (DateDisplay.Text != newText)
					DateDisplay.Text = newText;
			}
		}

19 Source : DateTimePicker.xaml.cs
with MIT License
from ADeltaX

private void DateDisplay_LostFocus(object sender, System.Windows.RoutedEventArgs e)
		{
			DateDisplay.Text = SelectedDate.ToString(DateFormat);
			// When the user selects a field again, then the box loses focus, then
			// the user clicks the same field again, the selection is cleared, 
			// causing the arrows not to appear. To fix, clear selection in advance.
			try
			{
				DateDisplay.SelectionLength = 0;
			}
			catch (NullReferenceException)
			{
				// Occurs during shutdown. Bug in WPF? Ain't doreplacedented, that's for sure.
			}
		}

19 Source : DateTimePicker.xaml.cs
with MIT License
from ADeltaX

public static void OnDateFormatChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
		{
			var me = (DateTimePicker)obj;
			me._inputDateFormat = null; // will be recomputed on-demand
			me.DateDisplay.Text = me.SelectedDate.ToString(me.DateFormat);
		}

19 Source : DateTimePicker.xaml.cs
with MIT License
from ADeltaX

public static void OnSelectedDateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
		{
			var me = (DateTimePicker)obj;

			var date = (DateTime)args.NewValue;
			me.CalDisplay.SelectedDate = date;
			me.CalDisplay.DisplayDate = date;
			if (me.DateDisplay.IsFocused && !me._forceTextUpdateNow)
			{
				DateTime? oldDate = me.ParseDateText(true);
				if (oldDate != null)
					me.DateTextIsWrong = date != oldDate.Value;
			}
			else
			{
				me.DateTextIsWrong = false;
				me._forceTextUpdateNow = false;
				me.DateDisplay.Text = date.ToString(me.DateFormat);
			}
		}

19 Source : EnumerableExtensions.cs
with MIT License
from Adoxio

private static void AddDataToTable(IEnumerable<Enreplacedy> enreplacedies, DataTable table, bool autogenerateColumns, string dateTimeFormat = null, IFormatProvider dateTimeFormatProvider = null)
		{
			foreach (var enreplacedy in enreplacedies)
			{
				var row = table.NewRow();

				foreach (var attribute in enreplacedy.Attributes)
				{
					if (!table.Columns.Contains(attribute.Key) && autogenerateColumns)
					{
						table.Columns.Add(attribute.Key);
					}

					if (table.Columns.Contains(attribute.Key))
					{
						var aliasedValue = attribute.Value as AliasedValue;

						object value = aliasedValue != null ? aliasedValue.Value : attribute.Value;

						var enreplacedyReference = value as EnreplacedyReference;

						if (enreplacedyReference != null)
						{
							row[attribute.Key] = enreplacedyReference.Name ??
								enreplacedyReference.Id.ToString();
						}
						else
						{
							var dateTime = value as DateTime?;

							if (dateTimeFormat != null && dateTime != null)
							{
								row[attribute.Key] = dateTimeFormatProvider == null
									? dateTime.Value.ToString(dateTimeFormat)
									: dateTime.Value.ToString(dateTimeFormat, dateTimeFormatProvider);
							}
							else
							{
								row[attribute.Key] = enreplacedy.FormattedValues.Contains(attribute.Key)
									? enreplacedy.FormattedValues[attribute.Key]
									: value ?? DBNull.Value;
							}
						}
					}
				}

				table.Rows.Add(row);
			}
		}

19 Source : EntityListDataAdapter.cs
with MIT License
from Adoxio

protected static Condition GetSearchFilterConditionForAttribute(string attribute, string query, EnreplacedyMetadata enreplacedyMetadata)
		{
			var attributeMetadata = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute);

			if (attributeMetadata == null)
			{
				return null;
			}

			switch (attributeMetadata.AttributeType)
			{
				case AttributeTypeCode.String:
					return new Condition(attribute, ConditionOperator.Like, "{0}%".FormatWith(query));

				case AttributeTypeCode.Lookup:
				case AttributeTypeCode.Customer:
				case AttributeTypeCode.Picklist:
				case AttributeTypeCode.State:
				case AttributeTypeCode.Status:
				case AttributeTypeCode.Owner:
					return new Condition("{0}name".FormatWith(attribute), ConditionOperator.Like, "{0}%".FormatWith(query));

				case AttributeTypeCode.BigInt:
					long parsedLong;
					return long.TryParse(query, out parsedLong)
						? new Condition(attribute, ConditionOperator.Equal, parsedLong)
						: null;

				case AttributeTypeCode.Integer:
					int parsedInt;
					return int.TryParse(query, out parsedInt)
						? new Condition(attribute, ConditionOperator.Equal, parsedInt)
						: null;

				case AttributeTypeCode.Double:
					double parsedDouble;
					return double.TryParse(query, out parsedDouble)
						? new Condition(attribute, ConditionOperator.Equal, parsedDouble)
						: null;

				case AttributeTypeCode.Decimal:
				case AttributeTypeCode.Money:
					decimal parsedDecimal;
					return decimal.TryParse(query, out parsedDecimal)
						? new Condition(attribute, ConditionOperator.Equal, parsedDecimal)
						: null;

				case AttributeTypeCode.DateTime:
					DateTime parsedDate;
					return DateTime.TryParse(query, out parsedDate)
						? new Condition(attribute, ConditionOperator.On, parsedDate.ToString("yyyy-MM-dd"))
						: null;

				default:
					return null;
			}
		}

See More Examples