System.DateTime.ToString(string, System.IFormatProvider)

Here are the examples of the csharp api System.DateTime.ToString(string, System.IFormatProvider) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1254 Examples 7

19 View Source File : DateTimeDdbConverter.cs
License : MIT License
Project Creator : AllocZero

public override AttributeValue Write(ref DateTime value) => new AttributeValue(new StringAttributeValue(value.ToString(Format, CultureInfo)));

19 View Source File : ExcelDateTime.cs
License : MIT License
Project Creator : andersnm

public string ToString(string numberFormat, CultureInfo culture)
        {
            return AdjustedDateTime.ToString(numberFormat, culture);
        }

19 View Source File : BlogSiteMapProvider.cs
License : MIT License
Project Creator : Adoxio

protected CrmSiteMapNode GetBlogMonthArchiveNode(OrganizationServiceContext serviceContext, Enreplacedy enreplacedy, DateTime month)
		{
			enreplacedy.replacedertEnreplacedyName("adx_blog");

			var portal = PortalContext;
			var website = portal.Website.ToEnreplacedyReference();

			var blog = serviceContext.IsAttached(enreplacedy) && Equals(enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_websiteid"), website)
				? enreplacedy
				: GetBlog(serviceContext, website, enreplacedy.Id);

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

			var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, blog);
			var archiveUrl = "{0}{1}{2:yyyy}/{2:MM}/".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", month);
			var blogClone = blog.Clone(false);

			string webTemplateId;

			var node = new CrmSiteMapNode(
				this,
				archiveUrl,
				archiveUrl,
				month.ToString("y", CultureInfo.CurrentCulture),
				blog.GetAttributeValue<string>("adx_summary"),
				GetBlogArchiveRewriteUrl(serviceContext, enreplacedy, out webTemplateId),
				blog.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
				blogClone);

			node[MonthArchiveNodeAttributeKey] = month.ToString("o", CultureInfo.InvariantCulture);

			if (webTemplateId != null)
			{
				node["adx_webtemplateid"] = webTemplateId;
			}

			return node;
		}

19 View Source File : DateTimeAxis.cs
License : MIT License
Project Creator : AlexGyver

public override string FormatValue(double x)
        {
            // convert the double value to a DateTime
            var time = ToDateTime(x);

            string fmt = this.ActualStringFormat;
            if (fmt == null)
            {
                return time.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern);
            }

            int week = this.GetWeek(time);
            fmt = fmt.Replace("ww", week.ToString("00"));
            fmt = fmt.Replace("w", week.ToString(CultureInfo.InvariantCulture));
            return time.ToString(fmt, this.ActualCulture);
        }

19 View Source File : RequestSecurityTokenResponse.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public string Serialize()
        {
            using var ms = new MemoryStream();
            using var writer = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8, false);
            // <t:RequestSecurityTokenResponseCollection>
            writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsFederationConstants.Elements.RequestSecurityTokenResponseCollection, WsTrustConstants.Namespaces.WsTrust1_3);
            // <t:RequestSecurityTokenResponse>
            writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestSecurityTokenResponse, WsTrustConstants.Namespaces.WsTrust1_3);
            // @Context
            writer.WriteAttributeString(WsFederationConstants.Attributes.Context, Context);

            // <t:Lifetime>
            writer.WriteStartElement(WsTrustConstants.Elements.Lifetime, WsTrustConstants.Namespaces.WsTrust1_3);

            // <wsu:Created></wsu:Created>
            writer.WriteElementString(WsUtility.PreferredPrefix, WsUtility.Elements.Created, WsUtility.Namespace, CreatedAt.ToString(SamlConstants.GeneratedDateTimeFormat, DateTimeFormatInfo.InvariantInfo));
            // <wsu:Expires></wsu:Expires>
            writer.WriteElementString(WsUtility.PreferredPrefix, WsUtility.Elements.Expires, WsUtility.Namespace, ExpiresAt.ToString(SamlConstants.GeneratedDateTimeFormat, DateTimeFormatInfo.InvariantInfo));

            // </t:Lifetime>
            writer.WriteEndElement();

            // <wsp:AppliesTo>
            writer.WriteStartElement(WsPolicy.PreferredPrefix, WsPolicy.Elements.AppliesTo, WsPolicy.Namespace);

            // <wsa:EndpointReference>
            writer.WriteStartElement(WsAddressing.PreferredPrefix, WsAddressing.Elements.EndpointReference, WsAddressing.Namespace);

            // <wsa:Address></wsa:Address>
            writer.WriteElementString(WsAddressing.PreferredPrefix, WsAddressing.Elements.Address, WsAddressing.Namespace, AppliesTo);

            writer.WriteEndElement();
            // </wsa:EndpointReference>

            writer.WriteEndElement();
            // </wsp:AppliesTo>

            // <t:RequestedSecurityToken>
            writer.WriteStartElement(WsTrustConstants_1_3.PreferredPrefix, WsTrustConstants.Elements.RequestedSecurityToken, WsTrustConstants.Namespaces.WsTrust1_3);

            // write replacedertion
            SecurityTokenHandler.WriteToken(writer, RequestedSecurityToken);

            // </t:RequestedSecurityToken>
            writer.WriteEndElement();

            // </t:RequestSecurityTokenResponse>
            writer.WriteEndElement();

            // <t:RequestSecurityTokenResponseCollection>
            writer.WriteEndElement();

            writer.Flush();
            return Encoding.UTF8.GetString(ms.ToArray());
        }

19 View Source File : EventAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private string GetEventOccurrenceUrl(OrganizationServiceContext serviceContext, Enreplacedy @event, Enreplacedy eventSchedule, DateTime start)
		{
			var urlProvider = Dependencies.GetUrlProvider();

			var path = urlProvider.GetUrl(serviceContext, @event);

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

			var url = new UrlBuilder(path);

			if (eventSchedule != null)
			{
				url.QueryString["schedule"] = eventSchedule.Id.ToString();
				url.QueryString["start"] = start.ToString("o", CultureInfo.InvariantCulture);
			}

			return url.PathWithQueryString;
		}

19 View Source File : UploadTool.cs
License : MIT License
Project Creator : alonsoalon

public async Task<IResponseEnreplacedy<FileInfo>> UploadFileAsync(IFormFile file, FileUploadConfig config, object args, CancellationToken cancellationToken = default)
        {
            var res = new ResponseEnreplacedy<FileInfo>();

            if (file == null || file.Length < 1)
            {
                return res.Error("请上传文件!");
            }

            //格式限制
            if (!config.ContentType.Contains(file.ContentType))
            {
                return res.Error("文件格式错误");
            }

            //大小限制
            if (!(file.Length <= config.MaxSize))
            {
                return res.Error("文件过大");
            }

            var fileInfo = new File.FileInfo(file.FileName, file.Length)
            {
                UploadPath = config.UploadPath,
                RequestPath = config.RequestPath
            };

            var dateTimeFormat = config.DateTimeFormat.IsNotNull() ? DateTime.Now.ToString(config.DateTimeFormat) : "";
            var format = config.Format.IsNotNull() ? StringHelper.Format(config.Format, args) : "";
            fileInfo.RelativePath = Path.Combine(dateTimeFormat, format).ToPath();

            if (!Directory.Exists(fileInfo.FileDirectory))
            {
                Directory.CreateDirectory(fileInfo.FileDirectory);
            }



            var dataCenterId = _systemConfig.CurrentValue?.DataCenterId ?? 5;
            var workId = _systemConfig.CurrentValue?.WorkId ?? 20;

            fileInfo.SaveName = $"{IdHelper.GenSnowflakeId(dataCenterId, workId)}.{fileInfo.Extension}";

            await SaveAsync(file, fileInfo.FilePath, cancellationToken);

            return res.Ok(fileInfo);
        }

19 View Source File : RemoveInvalidFeature.cs
License : Microsoft Public License
Project Creator : achimismaili

private void btnScopeCancel_Click(object sender, EventArgs e)
        {
            string msgString = "Action canceled.";
            parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);
            this.Close();
            this.Dispose();
        }

19 View Source File : DateTimeValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsLowerThan(DateTime val, DateTime comparer, string key) =>
            IsLowerThan(val, comparer, key, FluntErrorMessages.IsLowerThanErrorMessage(key, comparer.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : RemoveInvalidFeature.cs
License : Microsoft Public License
Project Creator : achimismaili

private void btnScopeSelected_Click(object sender, EventArgs e)
        {
            string msgString = string.Empty;
            int featurefound = 0;

            this.Hide();
            try
            {
                if (radioScopeWeb.Checked)
                {
                    scopeWindowScope = SPFeatureScope.Web;
                }
                else
                {
                    if (radioScopeSite.Checked)
                    {
                        scopeWindowScope = SPFeatureScope.Site;
                    }
                    else
                    {
                        if (radioScopeWebApp.Checked)
                        {
                            scopeWindowScope = SPFeatureScope.WebApplication;
                        }
                        else
                        {
                            if (radioScopeFarm.Checked)
                            {
                                scopeWindowScope = SPFeatureScope.Farm;
                            }
                            else
                                msgString = "Error in scope selection! Task canceled";
                            MessageBox.Show(msgString);
                            ((FrmMain)parentWindow).logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);

                            return;
                        }
                    }
                }
                featurefound = parentWindow.removeFeaturesWithinFarm(featureID, scopeWindowScope);
                if (featurefound == 0)
                {
                    msgString = "Feature not found in Scope:'" + scopeWindowScope.ToString() + "'. Do you want to try something else?";
                    if (MessageBox.Show(msgString, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        this.Show();
                    }
                    else
                    {

                    }
                }
                else
                {
                    msgString = "Success! Feature was found and deactivated " + featurefound + " times in Scope:'" + scopeWindowScope.ToString() + "'!";
                    MessageBox.Show(msgString);
                    parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);

                    SPFarm.Local.FeatureDefinitions.Remove(featureID, true);
                    parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - FeatureDefinition was uninstalled." + Environment.NewLine);

                }
            }
            catch
            {
            }
            finally
            {
                        this.Close();
                        this.Dispose();
            }

        }

19 View Source File : DHLProvider.cs
License : MIT License
Project Creator : alexeybusygin

private string BuildRatesRequestMessage(
            DateTime requestDateTime,
            DateTime pickupDateTime,
            string messageReference)
        {
            var requestCulture = CultureInfo.CreateSpecificCulture("en-US");
            var xmlSettings = new XmlWriterSettings()
            {
                Indent = true,
                Encoding = Encoding.UTF8
            };

            var isDomestic = Shipment.OriginAddress.CountryCode == Shipment.DestinationAddress.CountryCode;
            var isDutiable = !Shipment.HasDoreplacedentsOnly && !isDomestic;

            using (var memoryStream = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(memoryStream, xmlSettings))
                {
                    writer.WriteStartDoreplacedent();
                    writer.WriteStartElement("p", "DCTRequest", "http://www.dhl.com");
                    writer.WriteStartElement("GetQuote");

                    writer.WriteStartElement("Request");
                    writer.WriteStartElement("ServiceHeader");
                    writer.WriteElementString("MessageTime", requestDateTime.ToString("O", requestCulture));
                    writer.WriteElementString("MessageReference", messageReference);
                    writer.WriteElementString("SiteID", _configuration.SiteId);
                    writer.WriteElementString("Preplacedword", _configuration.Preplacedword);
                    writer.WriteEndElement(); // </ServiceHeader>
                    writer.WriteEndElement(); // </Request>

                    WriteAddress(writer, "From", Shipment.OriginAddress);

                    writer.WriteStartElement("BkgDetails");
                    writer.WriteElementString("PaymentCountryCode", Shipment.OriginAddress.CountryCode);
                    writer.WriteElementString("Date", pickupDateTime.ToString("yyyy-MM-dd", requestCulture));
                    writer.WriteElementString("ReadyTime", $"PT{pickupDateTime:HH}H{pickupDateTime:mm}M");
                    writer.WriteElementString("ReadyTimeGMTOffset", pickupDateTime.ToString("zzz", requestCulture));
                    writer.WriteElementString("DimensionUnit", "IN");
                    writer.WriteElementString("WeightUnit", "LB");

                    writer.WriteStartElement("Pieces");
                    for (var i = 0; i < Shipment.Packages.Count; i++)
                    {
                        writer.WriteStartElement("Piece");
                        writer.WriteElementString("PieceID", $"{i + 1}");
                        writer.WriteElementString("Height", Shipment.Packages[i].RoundedHeight.ToString(requestCulture));
                        writer.WriteElementString("Depth", Shipment.Packages[i].RoundedLength.ToString(requestCulture));
                        writer.WriteElementString("Width", Shipment.Packages[i].RoundedWidth.ToString(requestCulture));
                        writer.WriteElementString("Weight", Shipment.Packages[i].RoundedWeight.ToString(requestCulture));
                        writer.WriteEndElement(); // </Piece>
                    }
                    writer.WriteEndElement(); // </Pieces>

                    if (!string.IsNullOrEmpty(_configuration.PaymentAccountNumber))
                    {
                        writer.WriteElementString("PaymentAccountNumber", _configuration.PaymentAccountNumber);
                    }
                    writer.WriteElementString("IsDutiable", isDutiable ? "Y" : "N");
                    writer.WriteElementString("NetworkTypeCode", "AL");

                    writer.WriteStartElement("QtdShp");
                    if (_configuration.ServicesIncluded.Any())
                    {
                        foreach (var serviceCode in _configuration.ServicesIncluded)
                        {
                            writer.WriteElementString("GlobalProductCode", serviceCode.ToString());
                        }
                    }
                    if (Shipment.Options.SaturdayDelivery)
                    {
                        writer.WriteStartElement("QtdShpExChrg");
                        writer.WriteElementString("SpecialServiceType", isDomestic ? "AG" : "AA");
                        writer.WriteEndElement(); // </QtdShpExChrg>
                    }
                    writer.WriteEndElement(); // </QtdShp>

                    var totalInsurance = Shipment.Packages.Sum(p => p.InsuredValue);
                    if (totalInsurance > 0)
                    {
                        writer.WriteElementString("InsuredValue", $"{totalInsurance:N}");
                        writer.WriteElementString("InsuredCurrency", "USD");
                    }

                    writer.WriteEndElement(); // </BkgDetails>

                    WriteAddress(writer, "To", Shipment.DestinationAddress);

                    if (isDutiable)
                    {
                        writer.WriteStartElement("Dutiable");
                        writer.WriteElementString("DeclaredCurrency", "USD");
                        writer.WriteElementString("DeclaredValue", $"{totalInsurance:N}");
                        writer.WriteEndElement(); // </Dutiable>
                    }

                    writer.WriteEndElement(); // </GetQuote>
                    writer.WriteEndElement(); // </p:DCTRequest>
                    writer.WriteEndDoreplacedent();
                    writer.Flush();
                    writer.Close();
                }
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }

19 View Source File : MemoryTraceWriter.cs
License : MIT License
Project Creator : akaskela

public void Trace(TraceLevel level, string message, Exception ex)
        {
            if (_traceMessages.Count >= 1000)
            {
                _traceMessages.Dequeue();
            }

            StringBuilder sb = new StringBuilder();
            sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture));
            sb.Append(" ");
            sb.Append(level.ToString("g"));
            sb.Append(" ");
            sb.Append(message);

            _traceMessages.Enqueue(sb.ToString());
        }

19 View Source File : DateRangeWebsiteBlogAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public override int SelectPostCount()
		{
			var serviceContext = Dependencies.GetServiceContext();

			return serviceContext.FetchBlogPostCountForWebsite(Website.Id, addCondition =>
			{
				addCondition("adx_date", "ge", Min.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
				addCondition("adx_date", "le", Max.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
			});
		}

19 View Source File : MessagePackSerializer.Json.cs
License : Apache License 2.0
Project Creator : allenai

private static void ToJsonCore(ref MessagePackReader reader, TextWriter writer, MessagePackSerializerOptions options)
        {
            MessagePackType type = reader.NextMessagePackType;
            switch (type)
            {
                case MessagePackType.Integer:
                    if (MessagePackCode.IsSignedInteger(reader.NextCode))
                    {
                        writer.Write(reader.ReadInt64().ToString(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        writer.Write(reader.ReadUInt64().ToString(CultureInfo.InvariantCulture));
                    }

                    break;
                case MessagePackType.Boolean:
                    writer.Write(reader.ReadBoolean() ? "true" : "false");
                    break;
                case MessagePackType.Float:
                    if (reader.NextCode == MessagePackCode.Float32)
                    {
                        writer.Write(reader.ReadSingle().ToString(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        writer.Write(reader.ReadDouble().ToString(CultureInfo.InvariantCulture));
                    }

                    break;
                case MessagePackType.String:
                    WriteJsonString(reader.ReadString(), writer);
                    break;
                case MessagePackType.Binary:
                    ArraySegment<byte> segment = ByteArraySegmentFormatter.Instance.Deserialize(ref reader, DefaultOptions);
                    writer.Write("\"" + Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) + "\"");
                    break;
                case MessagePackType.Array:
                    {
                        int length = reader.ReadArrayHeader();
                        options.Security.DepthStep(ref reader);
                        try
                        {
                            writer.Write("[");
                            for (int i = 0; i < length; i++)
                            {
                                ToJsonCore(ref reader, writer, options);

                                if (i != length - 1)
                                {
                                    writer.Write(",");
                                }
                            }

                            writer.Write("]");
                        }
                        finally
                        {
                            reader.Depth--;
                        }

                        return;
                    }

                case MessagePackType.Map:
                    {
                        int length = reader.ReadMapHeader();
                        options.Security.DepthStep(ref reader);
                        try
                        {
                            writer.Write("{");
                            for (int i = 0; i < length; i++)
                            {
                                // write key
                                {
                                    MessagePackType keyType = reader.NextMessagePackType;
                                    if (keyType == MessagePackType.String || keyType == MessagePackType.Binary)
                                    {
                                        ToJsonCore(ref reader, writer, options);
                                    }
                                    else
                                    {
                                        writer.Write("\"");
                                        ToJsonCore(ref reader, writer, options);
                                        writer.Write("\"");
                                    }
                                }

                                writer.Write(":");

                                // write body
                                {
                                    ToJsonCore(ref reader, writer, options);
                                }

                                if (i != length - 1)
                                {
                                    writer.Write(",");
                                }
                            }

                            writer.Write("}");
                        }
                        finally
                        {
                            reader.Depth--;
                        }

                        return;
                    }

                case MessagePackType.Extension:
                    ExtensionHeader extHeader = reader.ReadExtensionFormatHeader();
                    if (extHeader.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime)
                    {
                        DateTime dt = reader.ReadDateTime(extHeader);
                        writer.Write("\"");
                        writer.Write(dt.ToString("o", CultureInfo.InvariantCulture));
                        writer.Write("\"");
                    }
#if !UNITY_2018_3_OR_NEWER
                    else if (extHeader.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter)
                    {
                        // prepare type name token
                        var privateBuilder = new StringBuilder();
                        var typeNameTokenBuilder = new StringBuilder();
                        SequencePosition positionBeforeTypeNameRead = reader.Position;
                        ToJsonCore(ref reader, new StringWriter(typeNameTokenBuilder), options);
                        int typeNameReadSize = (int)reader.Sequence.Slice(positionBeforeTypeNameRead, reader.Position).Length;
                        if (extHeader.Length > typeNameReadSize)
                        {
                            // object map or array
                            MessagePackType typeInside = reader.NextMessagePackType;
                            if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
                            {
                                privateBuilder.Append("{");
                            }

                            ToJsonCore(ref reader, new StringWriter(privateBuilder), options);

                            // insert type name token to start of object map or array
                            if (typeInside != MessagePackType.Array)
                            {
                                typeNameTokenBuilder.Insert(0, "\"$type\":");
                            }

                            if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
                            {
                                privateBuilder.Append("}");
                            }

                            if (privateBuilder.Length > 2)
                            {
                                typeNameTokenBuilder.Append(",");
                            }

                            privateBuilder.Insert(1, typeNameTokenBuilder.ToString());

                            writer.Write(privateBuilder.ToString());
                        }
                        else
                        {
                            writer.Write("{\"$type\":\"" + typeNameTokenBuilder.ToString() + "}");
                        }
                    }
#endif
                    else
                    {
                        var data = reader.ReadRaw((long)extHeader.Length);
                        writer.Write("[");
                        writer.Write(extHeader.TypeCode);
                        writer.Write(",");
                        writer.Write("\"");
                        writer.Write(Convert.ToBase64String(data.ToArray()));
                        writer.Write("\"");
                        writer.Write("]");
                    }

                    break;
                case MessagePackType.Nil:
                    reader.Skip();
                    writer.Write("null");
                    break;
                default:
                    throw new MessagePackSerializationException($"code is invalid. code: {reader.NextCode} format: {MessagePackCode.ToFormatName(reader.NextCode)}");
            }
        }

19 View Source File : RemoveInvalidFeature.cs
License : Microsoft Public License
Project Creator : achimismaili

private bool tryToRemove(Guid featureID, SPFeatureScope scope)
        {
            string msgString = string.Empty;
            int featurefound;

            featurefound = parentWindow.RemoveFeaturesWithinFarm(featureID, scope);
            /// search all webs
            if (featurefound == 0)
            {
                msgString = "Search through all Scopes:'" + scope.ToString() + "' done..., feature not found.";
                parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);
                return false;
            }
            else
            {
                msgString = "Success! Feature was found and deactivated " + featurefound + " times in Scope:'" + scope.ToString() + "'!";
                MessageBox.Show(msgString);
                parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);
                return true;
            }


        }

19 View Source File : DateTimeFormattingExtensions.cs
License : MIT License
Project Creator : AllocZero

public static string ToIso8601BasicDateTime(this DateTime dateTime) =>
            dateTime.ToString(DateTimeFormats.Iso8601BasicDateTimeFormat, CultureInfo.InvariantCulture);

19 View Source File : DateFilters.cs
License : MIT License
Project Creator : Adoxio

public static string DateToRfc822(DateTime? date)
		{
			if (date == null)
			{
				return null;
			}

			if (date.Value.Kind == DateTimeKind.Utc)
			{
				return date.Value.ToString("ddd, dd MMM yyyy HH:mm:ss Z", CultureInfo.InvariantCulture);
			}

			var builder = new StringBuilder(date.Value.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture));

			builder.Remove(builder.Length - 3, 1);

			return builder.ToString();
		}

19 View Source File : DateTimeHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static string RepresentAsIso8601Utc(DateTime date)
        {
            return date.ToString(Iso8601UtcFormat, CultureInfo.InvariantCulture);
        }

19 View Source File : ServerManager.cs
License : Apache License 2.0
Project Creator : 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 View Source File : DateTimeValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsGreaterOrEqualsThan(DateTime val, DateTime comparer, string key) =>
            IsGreaterOrEqualsThan(val, comparer, key, FluntErrorMessages.IsGreaterOrEqualsThanErrorMessage(key, comparer.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : EntityNotesController.cs
License : MIT License
Project Creator : Adoxio

protected void SetPropertyValues(IAnnotation annotation, DataAdapterDependencies dataAdapterDependencies)
			{
				CreatedOn = annotation.CreatedOn;
				CreatedOnDisplay = CreatedOn.ToString(DateTimeClientFormat);
				var text = annotation.NoteText;
				Text = AnnotationHelper.FormatNoteText(text).ToString();
				UnformattedText = text.Replace(AnnotationHelper.WebAnnotationPrefix, string.Empty);
				if (annotation.FileAttachment != null)
				{
					AttachmentFileName = annotation.FileAttachment.FileName;
					HasAttachment = annotation.FileAttachment != null;
					AttachmentContentType = annotation.FileAttachment.MimeType;
					AttachmentUrl = HasAttachment
						? annotation.Enreplacedy.GetFileAttachmentUrl(dataAdapterDependencies.GetWebsite())
						: string.Empty;
					AttachmentSize = annotation.FileAttachment.FileSize;
					AttachmentSizeDisplay = AttachmentSize.ToString();
					AttachmentIsImage = HasAttachment &&
						(new List<string> { "image/jpeg", "image/gif", "image/png" }).Contains(AttachmentContentType);
				}
				var subject = annotation.Subject;
				Subject = subject;
				IsPrivate = AnnotationHelper.GetNotePrivacy(annotation);
				var noteContact = AnnotationHelper.GetNoteContact(subject);
				var user = dataAdapterDependencies.GetPortalUser();
				IsPostedByCurrentUser = noteContact != null && user != null && noteContact.Id == user.Id;
				PostedByName = noteContact == null ? AnnotationHelper.GetNoteCreatedByName(annotation) : noteContact.Name;
				if (CanWrite)
				{
					CanWrite = IsPostedByCurrentUser;
				}
				if (CanDelete)
				{
					CanDelete = IsPostedByCurrentUser;
				}
				DisplayToolbar = CanWrite || CanDelete;
			}

19 View Source File : EntityActivityController.cs
License : MIT License
Project Creator : Adoxio

private void SetPropertyValues(IActivity activity, DataAdapterDependencies dataAdapterDependencies)
			{
				var attributes = activity.Enreplacedy.Attributes;

				IsCustomActivity = false;

				ViewFields = attributes.SelectMany(FlattenAllPartiesAttribute).ToDictionary(attribute => attribute.Key, attribute =>
				{
					var optionSetValue = attribute.Value as OptionSetValue;

					if (optionSetValue != null)
					{
						return optionSetValue.Value;
					}

					if (attribute.Key == "activitytypecode" && !predefinedTemplates.Contains((string)attribute.Value))
					{
						IsCustomActivity = true;
					}

					if (attribute.Key == "description")
					{
						string formattedValue = FormatViewFieldsValue(attribute.Value);
						if (!string.IsNullOrWhiteSpace(formattedValue))
						{
							return formattedValue;
						}
					}
					return attribute.Value;
				});

				CreatedOn = activity.Enreplacedy.GetAttributeValue<DateTime>("createdon");
				CreatedOnDisplay = CreatedOn.ToString(DateTimeClientFormat);

				var noteContact = activity.Enreplacedy.GetAttributeValue<EnreplacedyReference>("from");
				PostedByName = noteContact == null
					? activity.Enreplacedy.GetAttributeValue<EnreplacedyReference>("createdby").Name
					: noteContact.Name;

				DisplayToolbar = false;
			}

19 View Source File : OADateLabelProvider.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatCursorLabel(IComparable dataValue)
        {
            var oaDateTime = dataValue.ToDouble();
            var dateTime = DateTime.FromOADate(oaDateTime);
            var formattedText = ParentAxis.CursorTextFormatting.IsNullOrEmpty()
                ? FormatLabel(dataValue)
                : dateTime.ToString(ParentAxis.CursorTextFormatting);

            return formattedText;
        }

19 View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public RateLimitBucket GetBucket(RestRequestMethod method, string route, object route_params, out string url)
        {
            var rparams_props = route_params.GetType()
                .GetTypeInfo()
                .DeclaredProperties;
            var rparams = new Dictionary<string, string>();
            foreach (var xp in rparams_props)
            {
                var val = xp.GetValue(route_params);
                rparams[xp.Name] = val is string xs
                    ? xs
                    : val is DateTime dt
                    ? dt.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)
                    : val is DateTimeOffset dto
                    ? dto.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)
                    : val is IFormattable xf ? xf.ToString(null, CultureInfo.InvariantCulture) : val.ToString();
            }

            var guild_id = rparams.ContainsKey("guild_id") ? rparams["guild_id"] : "";
            var channel_id = rparams.ContainsKey("channel_id") ? rparams["channel_id"] : "";
            var webhook_id = rparams.ContainsKey("webhook_id") ? rparams["webhook_id"] : "";

            // Create a generic route (minus major params) key
            // ex: POST:/channels/channel_id/messages
            var hashKey = RateLimitBucket.GenerateHashKey(method, route);

            // We check if the hash is present, using our generic route (without major params)
            // ex: in POST:/channels/channel_id/messages, out 80c17d2f203122d936070c88c8d10f33
            // If it doesn't exist, we create an unlimited hash as our initial key in the form of the hash key + the unlimited constant
            // and replacedign this to the route to hash cache
            // ex: this.RoutesToHashes[POST:/channels/channel_id/messages] = POST:/channels/channel_id/messages:unlimited
            var hash = this.RoutesToHashes.GetOrAdd(hashKey, RateLimitBucket.GenerateUnlimitedHash(method, route));

            // Next we use the hash to generate the key to obtain the bucket.
            // ex: 80c17d2f203122d936070c88c8d10f33:guild_id:506128773926879242:webhook_id
            // or if unlimited: POST:/channels/channel_id/messages:unlimited:guild_id:506128773926879242:webhook_id
            var bucketId = RateLimitBucket.GenerateBucketId(hash, guild_id, channel_id, webhook_id);

            // If it's not in cache, create a new bucket and index it by its bucket id.
            var bucket = this.HashesToBuckets.GetOrAdd(bucketId, new RateLimitBucket(hash, guild_id, channel_id, webhook_id));

            bucket.LastAttemptAt = DateTimeOffset.UtcNow;

            // Cache the routes for each bucket so it can be used for GC later.
            if (!bucket.RouteHashes.Contains(bucketId))
                bucket.RouteHashes.Add(bucketId);

            // Add the current route to the request queue, which indexes the amount
            // of requests occurring to the bucket id.
            _ = this.RequestQueue.TryGetValue(bucketId, out var count);

            // Increment by one atomically due to concurrency
            this.RequestQueue[bucketId] = Interlocked.Increment(ref count);

            // Start bucket cleaner if not already running.
            if (!this._cleanerRunning)
            {
                this._cleanerRunning = true;
                this._bucketCleanerTokenSource = new CancellationTokenSource();
                this._cleanerTask = Task.Run(this.CleanupBucketsAsync, this._bucketCleanerTokenSource.Token);
                this.Logger.LogDebug(LoggerEvents.RestCleaner, "Bucket cleaner task started.");
            }

            url = RouteArgumentRegex.Replace(route, xm => rparams[xm.Groups[1].Value]);
            return bucket;
        }

19 View Source File : HostTraceListener.cs
License : MIT License
Project Creator : actions

private void WriteFooter(TraceEventCache eventCache)
        {
            if (eventCache == null)
                return;

            IndentLevel++;
            if (IsEnabled(TraceOptions.ProcessId))
                WriteLine("ProcessId=" + eventCache.ProcessId);

            if (IsEnabled(TraceOptions.ThreadId))
                WriteLine("ThreadId=" + eventCache.ThreadId);

            if (IsEnabled(TraceOptions.DateTime))
                WriteLine("DateTime=" + eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture));

            if (IsEnabled(TraceOptions.Timestamp))
                WriteLine("Timestamp=" + eventCache.Timestamp);

            IndentLevel--;
        }

19 View Source File : DateTimeUtils.cs
License : MIT License
Project Creator : akaskela

internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, string formatString, CultureInfo culture)
        {
            if (string.IsNullOrEmpty(formatString))
            {
                char[] chars = new char[64];
                int pos = WriteDateTimeString(chars, 0, value, null, value.Kind, format);
                writer.Write(chars, 0, pos);
            }
            else
            {
                writer.Write(value.ToString(formatString, culture));
            }
        }

19 View Source File : JsonTextWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteValue(DateTime value)
        {
            InternalWriteValue(JsonToken.Date);
            value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);

            if (string.IsNullOrEmpty(DateFormatString))
            {
                EnsureWriteBuffer();

                int pos = 0;
                _writeBuffer[pos++] = _quoteChar;
                pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, value, null, value.Kind, DateFormatHandling);
                _writeBuffer[pos++] = _quoteChar;

                _writer.Write(_writeBuffer, 0, pos);
            }
            else
            {
                _writer.Write(_quoteChar);
                _writer.Write(value.ToString(DateFormatString, Culture));
                _writer.Write(_quoteChar);
            }
        }

19 View Source File : DateRangeBlogDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public int SelectPostCount()
		{
			var serviceContext = Dependencies.GetServiceContext();

			return serviceContext.FetchBlogPostCount(Blog.Id, addCondition =>
			{
				addCondition("adx_date", "ge", Min.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
				addCondition("adx_date", "le", Max.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
			}, !Security.UserHasAuthorPermission);
		}

19 View Source File : Logger.cs
License : MIT License
Project Creator : AlexGyver

public void Log() {      
      var now = DateTime.Now;

      if (lastLoggedTime + LoggingInterval - new TimeSpan(5000000) > now)
        return;      

      if (day != now.Date || !File.Exists(fileName)) {
        day = now.Date;
        fileName = GetFileName(day);

        if (!OpenExistingLogFile())
          CreateNewLogFile();
      }

      try {
        using (StreamWriter writer = new StreamWriter(new FileStream(fileName,
          FileMode.Append, FileAccess.Write, FileShare.ReadWrite))) {
          writer.Write(now.ToString("G", CultureInfo.InvariantCulture));
          writer.Write(",");
          for (int i = 0; i < sensors.Length; i++) {
            if (sensors[i] != null) {
              float? value = sensors[i].Value;
              if (value.HasValue)
                writer.Write(
                  value.Value.ToString("R", CultureInfo.InvariantCulture));
            }
            if (i < sensors.Length - 1)
              writer.Write(",");
            else
              writer.WriteLine();
          }
        }
      } catch (IOException) { }

      lastLoggedTime = now;
    }

19 View Source File : RemoveInvalidFeature.cs
License : Microsoft Public License
Project Creator : achimismaili

private void btnScopeSelected_Click(object sender, EventArgs e)
        {
            string msgString = string.Empty;
            int featurefound = 0;

            this.Hide();
            try
            {
                if (radioScopeWeb.Checked)
                {
                    scopeWindowScope = SPFeatureScope.Web;
                }
                else
                {
                    if (radioScopeSite.Checked)
                    {
                        scopeWindowScope = SPFeatureScope.Site;
                    }
                    else
                    {
                        if (radioScopeWebApp.Checked)
                        {
                            scopeWindowScope = SPFeatureScope.WebApplication;
                        }
                        else
                        {
                            if (radioScopeFarm.Checked)
                            {
                                scopeWindowScope = SPFeatureScope.Farm;
                            }
                            else
                                msgString = "Error in scope selection! Task canceled";
                            MessageBox.Show(msgString);
                            ((FrmMain)parentWindow).logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);

                            return;
                        }
                    }
                }
                featurefound = parentWindow.RemoveFeaturesWithinFarm(featureID, scopeWindowScope);
                if (featurefound == 0)
                {
                    msgString = "Feature not found in Scope:'" + scopeWindowScope.ToString() + "'. Do you want to try something else?";
                    if (MessageBox.Show(msgString, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        this.Show();
                    }
                    else
                    {

                    }
                }
                else
                {
                    msgString = "Success! Feature was found and deactivated " + featurefound + " times in Scope:'" + scopeWindowScope.ToString() + "'!";
                    MessageBox.Show(msgString);
                    parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);

                    SPFarm.Local.FeatureDefinitions.Remove(featureID, true);
                    parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - FeatureDefinition was uninstalled." + Environment.NewLine);

                }
            }
            catch
            {
            }
            finally
            {
                        this.Close();
                        this.Dispose();
            }

        }

19 View Source File : AliyunSDKUtils.cs
License : MIT License
Project Creator : aliyunmq

public static string GetFormattedTimestampRFC822(int minutesFromNow)
        {
            DateTime dateTime = DateTime.UtcNow.AddMinutes(minutesFromNow);
            DateTime formatted = new DateTime(
                dateTime.Year,
                dateTime.Month,
                dateTime.Day,
                dateTime.Hour,
                dateTime.Minute,
                dateTime.Second,
                dateTime.Millisecond,
                DateTimeKind.Local
                );
            return formatted.ToString(
                RFC822DateFormat,
                CultureInfo.InvariantCulture
                );
        }

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : 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 View Source File : DateTimeFormattingExtensions.cs
License : MIT License
Project Creator : AllocZero

public static string ToIso8601BasicDate(this DateTime dateTime) =>
            dateTime.ToString(DateTimeFormats.Iso8601BasicDateFormat, CultureInfo.InvariantCulture);

19 View Source File : CallIncident.cs
License : Apache License 2.0
Project Creator : 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 View Source File : DateTimeDdbConverter.cs
License : MIT License
Project Creator : AllocZero

public virtual string WriteStringValue(ref DateTime value) => value.ToString(Format, CultureInfo);

19 View Source File : CrmChartBuilder.cs
License : MIT License
Project Creator : Adoxio

private Dictionary<string, string> CreateResourceManagerStringOverrides()
		{
			var resources = new Dictionary<string, string>
			{
				{ "ActivityContainerControl.SubjectEllipsesText", ResourceManager.GetString("Visualization_SubjectEllipsesText") },
				{ "Web.Visualization.Axisreplacedle", ResourceManager.GetString("Visualization_Axisreplacedle") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping") },
				{ "Web.Visualization.EmptyAxisLabel", ResourceManager.GetString("Visualization_EmptyAxisLabel") },
				{ "Web.Visualization.Axisreplacedle.AVG", ResourceManager.GetString("Visualization_Axisreplacedle_AVG") },
				{ "Web.Visualization.Axisreplacedle.SUM", ResourceManager.GetString("Visualization_Axisreplacedle_SUM") },
				{ "Web.Visualization.Axisreplacedle.MIN", ResourceManager.GetString("Visualization_Axisreplacedle_MIN") },
				{ "Web.Visualization.Axisreplacedle.MAX", ResourceManager.GetString("Visualization_Axisreplacedle_MAX") },
				{ "Web.Visualization.Axisreplacedle.NONE", ResourceManager.GetString("Visualization_Axisreplacedle_NONE") },
				{ "Web.Visualization.Axisreplacedle.COUNT", ResourceManager.GetString("Visualization_Axisreplacedle_COUNT") },
				{ "Web.Visualization.Axisreplacedle.COUNTCOLUMN", ResourceManager.GetString("Visualization_Axisreplacedle_COUNTCOLUMN") },
				{ "Web.Visualization.Axisreplacedle.CurrencySymbol", ResourceManager.GetString("Visualization_Axisreplacedle_CurrencySymbol") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.DAY", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_DAY") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.FISCALPERIOD", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_FISCALPERIOD") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.FISCALYEAR", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_FISCALYEAR") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.MONTH", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_MONTH") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.QUARTER", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_QUARTER") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.WEEK", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_WEEK") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.YEAR", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_YEAR") },
				{ "Web.Visualization.Year.Quarter", ResourceManager.GetString("Visualization_Year_Quarter") },
				{ "Web.Visualization.Year.Week", ResourceManager.GetString("Visualization_Year_Week") },
				{ "Chart_NoData_Message", ResourceManager.GetString("Visualization_Chart_NoData_Message") }
			};

			var shortMonthCsv = new StringBuilder(string.Empty);
			for (int i = 1; i <= this.culture.Calendar.GetMonthsInYear(DateTime.Now.Year); i++)
			{
				DateTime month = new DateTime(DateTime.Now.Year, i, 1, this.culture.Calendar);
				shortMonthCsv.AppendFormat("{0},", month.ToString("MMM", this.culture));
			}
			resources.Add("Calendar_Short_Months", shortMonthCsv.ToString().TrimEnd(','));

			return resources;
		}

19 View Source File : SharedKeyAuthHandler.cs
License : Apache License 2.0
Project Creator : aloneguid

private void Authenticate(HttpRequestMessage request)
      {
         //auth

         DateTime now = DateTime.UtcNow;
         request.Headers.Add("x-ms-date", now.ToString("R", CultureInfo.InvariantCulture));
         request.Headers.Add("x-ms-version", "2017-04-17");

         // any extra headers to be added here, before creating auth header!

         string signature = GetAuthSignature(request, _accountName, _sharedKey);

         request.Headers.Authorization = new AuthenticationHeaderValue("SharedKey", $"{_accountName}:{signature}");
      }

19 View Source File : RemoveInvalidFeature.cs
License : Microsoft Public License
Project Creator : achimismaili

private void btnScopeUnknown_Click(object sender, EventArgs e)
        {
            string msgString = "All scopes will be checked for this feature. This might take a while. Continue?";
            if (MessageBox.Show(msgString, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                this.Hide();
                try
                {
                    // search all webs
                    if (!tryToRemove(featureID, SPFeatureScope.Web))
                    {
                        // search all Sites     
                        if (!tryToRemove(featureID, SPFeatureScope.Site))
                        {


                            // search all Web Applications     
                            if (!tryToRemove(featureID, SPFeatureScope.WebApplication))
                            {
                                // search in Farm Scope     
                                tryToRemove(featureID, SPFeatureScope.Farm);
                            }
                        }
                    }

                    SPFarm.Local.FeatureDefinitions.Remove(featureID, true);
                    parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - FeatureDefinition was uninstalled." + Environment.NewLine);
                    this.Close();
                    this.Dispose();
                }

                catch
                {
                    parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - An error occured iterating through the features ..." + Environment.NewLine);

                }
                finally
                {
                    this.Close();
                    this.Dispose();
                }
            }
        }

19 View Source File : DateTimeHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static DateTime? ConvertToUniversalTime(DateTime? date)
        {
            if (date.HasValue)
            {
                DateTime timestamp = date.Value;

                if (timestamp.Kind == DateTimeKind.Utc)
                {
                    return timestamp;
                }
                else if (timestamp.Kind == DateTimeKind.Local)
                {
                    return timestamp.ToUniversalTime();
                }
                else if (timestamp.Kind == DateTimeKind.Unspecified)
                {
                    // force unspecified timezone to be interpreted as UTC
                    string unspecifiedTimezoneDateTime = timestamp.ToString(Iso8601Format, CultureInfo.InvariantCulture);
                    DateTime utc = DateTime.ParseExact(unspecifiedTimezoneDateTime + "Z", Iso8601UtcFormat, CultureInfo.InvariantCulture);
                    return utc.ToUniversalTime();
                }
            }

            return null;
        }

19 View Source File : DateTimeControlTemplate.cs
License : MIT License
Project Creator : Adoxio

protected override void InstantiateControlIn(Control container)
		{
			RegisterClientSideDependencies(container);

			var textbox = new TextBox
			{
				ID = ControlID,
				TextMode = TextBoxMode.SingleLine,
				CssClreplaced = string.Join(" ", CssClreplaced, Metadata.CssClreplaced),
				ToolTip = Metadata.ToolTip
			};

			textbox.Attributes["data-ui"] = "datetimepicker";
			textbox.Attributes["data-type"] = IncludesTime ? "datetime" : "date";
			textbox.Attributes["data-attribute"] = Metadata.DataFieldName;
			textbox.Attributes["data-behavior"] = Metadata.DateTimeBehavior.Value;
			if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
			{
				textbox.Attributes.Add("required", string.Empty);
			}

			if (Metadata.ReadOnly)
			{
				textbox.CssClreplaced += " readonly";
				textbox.Attributes["readonly"] = "readonly";
			}

			container.Controls.Add(textbox);

			Bindings[Metadata.DataFieldName] = new CellBinding
			{
				Get = () =>
				{
					DateTime parsed;

					return TryParse(textbox.Text, out parsed)
						? new DateTime?(parsed)
						: null;
				},
				Set = obj =>
				{
					var initialValue = obj as DateTime?;
					
					textbox.Text = initialValue.HasValue
                        ? initialValue.Value.ToString(Globalization.DateTimeFormatInfo.RoundTripPattern)
						: string.Empty;
				}
			};
		}

19 View Source File : ApiClient.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public string ParameterToString(object obj)
        {
            if (obj is DateTime)
            {
                // Return a formatted date string - Can be customized with Configuration.DateTimeFormat
                // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
                // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
                // For example: 2009-06-15T13:45:30.0000000
                return ((DateTime)obj).ToString(Configuration.DateTimeFormat);
            }
            else if (obj is DateTimeOffset)
            {
                // Return a formatted date string - Can be customized with Configuration.DateTimeFormat
                // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
                // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
                // For example: 2009-06-15T13:45:30.0000000
                return ((DateTimeOffset)obj).ToString(Configuration.DateTimeFormat);
            }
            else if (obj is IList)
            {
                var flattenedString = new StringBuilder();
                foreach (var param in (IList)obj)
                {
                    if (flattenedString.Length > 0)
                    {
                        flattenedString.Append(",");
                    }

                    flattenedString.Append(param);
                }

                return flattenedString.ToString();
            }
            else
            {
                return Convert.ToString(obj);
            }
        }

19 View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099

internal object SerializeRedisValue(object value)
        {
            switch (value)
            {
                case null: return null;
                case string _:
                case byte[] _: return value;

                case bool b: return b ? "1" : "0";
                case char c: return value;
                case decimal _:
                case double _:
                case float _:
                case int _:
                case long _:
                case sbyte _:
                case short _:
                case uint _:
                case ulong _:
                case ushort _: return value.ToInvariantCultureToString();

                case DateTime time: return time.ToString("yyyy-MM-ddTHH:mm:sszzzz", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                case DateTimeOffset _: return value.ToString();
                case TimeSpan span: return span.Ticks;
                case Guid _: return value.ToString();
                default:
                    if (Adapter.TopOwner.Serialize != null) return Adapter.TopOwner.Serialize(value);
                    return value.ConvertTo<string>();
            }
        }

19 View Source File : DateTimeValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsGreaterThan(DateTime val, DateTime comparer, string key) =>
            IsGreaterThan(val, comparer, key, FluntErrorMessages.IsGreaterThanErrorMessage(key, comparer.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : BlogSiteMapProvider.cs
License : MIT License
Project Creator : Adoxio

protected CrmSiteMapNode GetBlogAggregationMonthArchiveNode(OrganizationServiceContext serviceContext, Enreplacedy enreplacedy, DateTime month)
		{
			enreplacedy.replacedertEnreplacedyName("adx_webpage");

			var portal = PortalContext;
			var website = portal.Website.ToEnreplacedyReference();

			var page = serviceContext.IsAttached(enreplacedy) && Equals(enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_websiteid"), website)
				? enreplacedy
				: GetPage(serviceContext, website, enreplacedy.Id);

			var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, page);
			var archiveUrl = "{0}{1}{2:yyyy}/{2:MM}/".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", month);

			var pageTemplate = page.GetRelatedEnreplacedy(serviceContext, "adx_pagetemplate_webpage");
			var pageClone = page.Clone(false);

			string webTemplateId;

			var node = new CrmSiteMapNode(
				this,
				archiveUrl,
				archiveUrl,
				month.ToString("y", CultureInfo.CurrentCulture),
				page.GetAttributeValue<string>("adx_summary"),
				GetRewriteUrl(pageTemplate, out webTemplateId),
				page.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
				pageClone);

			node[MonthArchiveNodeAttributeKey] = month.ToString("o", CultureInfo.InvariantCulture);
			node["IsAggregationArchiveNode"] = "true";

			if (webTemplateId != null)
			{
				node["adx_webtemplateid"] = webTemplateId;
			}

			return node;
		}

19 View Source File : RemoveInvalidFeature.cs
License : Microsoft Public License
Project Creator : achimismaili

private bool tryToRemove(Guid featureID, SPFeatureScope scope)
        {
            string msgString = string.Empty;
            int featurefound;

            featurefound = parentWindow.removeFeaturesWithinFarm(featureID, scope);
            /// search all webs
            if (featurefound == 0)
            {
                msgString = "Search through all Scopes:'" + scope.ToString() + "' done..., feature not found.";
                parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);
                return false;
            }
            else
            {
                msgString = "Success! Feature was found and deactivated " + featurefound + " times in Scope:'" + scope.ToString() + "'!";
                MessageBox.Show(msgString);
                parentWindow.logTxt(DateTime.Now.ToString(FrmMain.DATETIMEFORMAT) + " - " + msgString + Environment.NewLine);
                return true;
            }


        }

19 View Source File : DateTimeConverter.cs
License : MIT License
Project Creator : 17MKH

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
    }

19 View Source File : MainHelper.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string ToGoodUtcString(this DateTime that, string format)
        {
            if (that == DateTime.MinValue) return that.ToString(format, Culture);
            var nowUtc = DateTime.Now - DateTime.UtcNow;
            return (that + nowUtc).ToString(format, Culture);
        }

19 View Source File : HeatMapWithTextInCellsExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatLabel(IComparable dataValue)
            {
                var h = (int) Math.Ceiling(dataValue.ToDouble());
                var dt = new DateTime(2000, 1, 1, 1, 0, 0);
                try
                {
                    dt = dt.AddHours(h);
                }
                catch (ArgumentOutOfRangeException)
                {
                    dt = h < 0 ? DateTime.MinValue : DateTime.MaxValue;
                }
                return dt.ToString("hh:mm tt", new CultureInfo("en-US"));
            }

19 View Source File : BarChartSlottingViewModel.cs
License : MIT License
Project Creator : Actipro

private static string GetAxisLabel(DateTime slotStart, DateTime slotEnd) {
			if(slotStart.Year == slotEnd.Year && slotStart.Month == slotEnd.Month)
				return slotStart.ToString("MMM", CultureInfo.CurrentCulture);

			return slotStart.ToString("MMM", CultureInfo.CurrentCulture) + " - " + slotEnd.ToString("MMM", CultureInfo.CurrentCulture);
		}

19 View Source File : IsoDateTimeConverter.cs
License : MIT License
Project Creator : akaskela

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string text;

            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;

                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                    || (_dateTimeStyles & DateTimeStyles.replacedumeUniversal) == DateTimeStyles.replacedumeUniversal)
                {
                    dateTime = dateTime.ToUniversalTime();
                }

                text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#if !NET20
            else if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                    || (_dateTimeStyles & DateTimeStyles.replacedumeUniversal) == DateTimeStyles.replacedumeUniversal)
                {
                    dateTimeOffset = dateTimeOffset.ToUniversalTime();
                }

                text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#endif
            else
            {
                throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
            }

            writer.WriteValue(text);
        }

See More Examples