int.ToString(System.IFormatProvider)

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

1836 Examples 7

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

[EditorBrowsable(EditorBrowsableState.Never)]
        public static void WriteAuthorizationToken(
            string token,
            IDictionary<string, string> attributes)
        {
            int i = 0;
            for (int j = 0; j < token.Length; i++, j += 128)
            {
                attributes["AuthTokenSegment" + i] = token.Substring(j, Math.Min(128, token.Length - j));
            }

            attributes["AuthTokenSegmentCount"] = i.ToString(CultureInfo.InvariantCulture);
        }

19 View Source File : Compatibility.cs
License : MIT License
Project Creator : adams85

public static StringBuilder Append(this StringBuilder builder, int value, IFormatProvider provider)
        {
            // TODO: .NET 6 will provide a more efficient solution:
            // https://github.com/dotnet/runtime/issues/50674#issuecomment-812782309

            return builder.Append(value.ToString(provider));
        }

19 View Source File : Rope.cs
License : MIT License
Project Creator : Abdesol

public void InsertRange(int index, T[] array, int arrayIndex, int count)
		{
			if (index < 0 || index > this.Length) {
				throw new ArgumentOutOfRangeException("index", index, "0 <= index <= " + this.Length.ToString(CultureInfo.InvariantCulture));
			}
			VerifyArrayWithRange(array, arrayIndex, count);
			if (count > 0) {
				root = root.Insert(index, array, arrayIndex, count);
				OnChanged();
			}
		}

19 View Source File : SolarAnalysisManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private bool CreateWinterViews(ModelSetupWizard.TransactionLog log)
        {
            var id = GetViewFamilyId(doc, ViewFamily.ThreeDimensional);

            // FIXME add error message here
            if (id == null) {
                log.AddFailure("Could not gererate 3d view. FamilyId not found");
                return false;
            }

            while (StartTime <= EndTime)
            {
                using (var t = new Transaction(doc))
                {
                    t.Start("Create Solar View");
                    View view = View3D.CreateIsometric(doc, id);
                    view.ViewTemplateId = ElementId.InvalidElementId;
                    var niceMinutes = "00";
                    if (StartTime.Minute > 0)
                    {
                        niceMinutes = StartTime.Minute.ToString(CultureInfo.CurrentCulture);
                    }
                    var vname = "SOLAR ACCESS - " + StartTime.ToShortDateString() + "-" + StartTime.Hour + "." +
                                niceMinutes;
                    view.Name = GetNiceViewName(doc, vname);
                    var sunSettings = view.SunAndShadowSettings;
                    sunSettings.StartDateAndTime = StartTime;

                    if (StartTime <= sunSettings.GetSunrise(StartTime).ToLocalTime() || StartTime >= sunSettings.GetSunset(EndTime).ToLocalTime())
                    {
                        doc.Delete(view.Id);
                        log.AddFailure("Cannot rotate a view that is not in daylight hours: " + vname);
                        StartTime = StartTime.Add(ExportTimeInterval);
                        continue;
                    }

                    sunSettings.SunAndShadowType = SunAndShadowType.StillImage;
                    t.Commit();

                    if (!RotateView(view)) {
                        doc.Delete(view.Id);
                        log.AddFailure("Could not rotate view: " + vname);
                        continue;
                    }
                    log.AddSuccess("View created: " + vname);
                    StartTime = StartTime.Add(ExportTimeInterval);
                }
            } 
            return true;
        }

19 View Source File : LineNumberMargin.cs
License : MIT License
Project Creator : Abdesol

protected override void OnRender(DrawingContext drawingContext)
		{
			TextView textView = this.TextView;
			Size renderSize = this.RenderSize;
			if (textView != null && textView.VisualLinesValid) {
				var foreground = (Brush)GetValue(Control.ForegroundProperty);
				foreach (VisualLine line in textView.VisualLines) {
					int lineNumber = line.FirstDoreplacedentLine.LineNumber;
					FormattedText text = TextFormatterFactory.CreateFormattedText(
						this,
						lineNumber.ToString(CultureInfo.CurrentCulture),
						typeface, emSize, foreground
					);
					double y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
					drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset));
				}
			}
		}

19 View Source File : PrefixWriterTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test, RequiresThread]
        public void should_write_thread_id()
        {
            var prefixWriter = new PrefixWriter("%thread");

            var logEventHeader = new LogEventHeader
            {
                Thread = Thread.CurrentThread
            };

            var result = GetResult(prefixWriter, logEventHeader);
            Check.That(result).IsEqualTo(Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));
        }

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

private ScalarToken ParseScalar(
            LiteralToken token,
            String[] allowedContext)
        {
            // Not a string
            if (token.Type != TokenType.String)
            {
                return token;
            }

            // Check if the value is definitely a literal
            var raw = token.ToString();
            Int32 startExpression;
            if (String.IsNullOrEmpty(raw) ||
                (startExpression = raw.IndexOf(TemplateConstants.OpenExpression)) < 0) // Doesn't contain ${{
            {
                return token;
            }

            // Break the value into segments of LiteralToken and ExpressionToken
            var segments = new List<ScalarToken>();
            var i = 0;
            while (i < raw.Length)
            {
                // An expression starts here:
                if (i == startExpression)
                {
                    // Find the end of the expression - i.e. }}
                    startExpression = i;
                    var endExpression = -1;
                    var inString = false;
                    for (i += TemplateConstants.OpenExpression.Length; i < raw.Length; i++)
                    {
                        if (raw[i] == '\'')
                        {
                            inString = !inString; // Note, this handles escaped single quotes gracefully. Ex. 'foo''bar'
                        }
                        else if (!inString && raw[i] == '}' && raw[i - 1] == '}')
                        {
                            endExpression = i;
                            i++;
                            break;
                        }
                    }

                    // Check if not closed
                    if (endExpression < startExpression)
                    {
                        m_context.Error(token, TemplateStrings.ExpressionNotClosed());
                        return token;
                    }

                    // Parse the expression
                    var rawExpression = raw.Substring(
                        startExpression + TemplateConstants.OpenExpression.Length,
                        endExpression - startExpression + 1 - TemplateConstants.OpenExpression.Length - TemplateConstants.CloseExpression.Length);
                    var expression = ParseExpression(token.Line, token.Column, rawExpression, allowedContext, out Exception ex);

                    // Check for error
                    if (ex != null)
                    {
                        m_context.Error(token, ex);
                        return token;
                    }

                    // Check if a directive was used when not allowed
                    if (!String.IsNullOrEmpty(expression.Directive) &&
                        ((startExpression != 0) || (i < raw.Length)))
                    {
                        m_context.Error(token, TemplateStrings.DirectiveNotAllowedInline(expression.Directive));
                        return token;
                    }

                    // Add the segment
                    segments.Add(expression);

                    // Look for the next expression
                    startExpression = raw.IndexOf(TemplateConstants.OpenExpression, i);
                }
                // The next expression is further ahead:
                else if (i < startExpression)
                {
                    // Append the segment
                    AddString(segments, token.Line, token.Column, raw.Substring(i, startExpression - i));

                    // Adjust the position
                    i = startExpression;
                }
                // No remaining expressions:
                else
                {
                    AddString(segments, token.Line, token.Column, raw.Substring(i));
                    break;
                }
            }

            // Check if can convert to a literal
            // For example, the escaped expression: ${{ '{{ this is a literal }}' }}
            if (segments.Count == 1 &&
                segments[0] is BasicExpressionToken basicExpression &&
                IsExpressionString(basicExpression.Expression, out String str))
            {
                return new StringToken(m_fileId, token.Line, token.Column, str);
            }

            // Check if only ony segment
            if (segments.Count == 1)
            {
                return segments[0];
            }

            // Build the new expression, using the format function
            var format = new StringBuilder();
            var args = new StringBuilder();
            var argIndex = 0;
            foreach (var segment in segments)
            {
                if (segment is StringToken literal)
                {
                    var text = ExpressionUtility.StringEscape(literal.Value) // Escape quotes
                        .Replace("{", "{{") // Escape braces
                        .Replace("}", "}}");
                    format.Append(text);
                }
                else
                {
                    format.Append("{" + argIndex.ToString(CultureInfo.InvariantCulture) + "}"); // Append formatter
                    argIndex++;

                    var expression = segment as BasicExpressionToken;
                    args.Append(", ");
                    args.Append(expression.Expression);
                }
            }

            return new BasicExpressionToken(m_fileId, token.Line, token.Column, $"format('{format}'{args})");
        }

19 View Source File : HuobiAPI.cs
License : MIT License
Project Creator : aabiryukov

private int InternalTrade(decimal price, decimal amount, bool isSell)
	    {
	        var method = isSell ? "sell" : "buy";
            var args = new NameValueCollection
	        {
		        {"coin_type", ((int)CoinType.Btc).ToString(CultureInfo.InvariantCulture)},
				{"price", price.ToString(CultureInfo.InvariantCulture)},
				{"amount", amount.ToString(CultureInfo.InvariantCulture)}
	        };

			var response = DoMethod2(method, args);
	        var orderResult = JsonConvert.DeserializeObject<HuobiOrderResult>(response);
            if(orderResult.Result != "success")
                throw new HuobiException(method, "Failed to create order: " + method);

            if (orderResult.Id > int.MaxValue)
                throw new HuobiException(method, "Order value too large for int: " + orderResult.Id);

            return (int)orderResult.Id;
		}

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

internal static string TryConvertAttributeValueToString(OrganizationServiceContext context, Dictionary<string, AttributeTypeCode?> attributeTypeCodeDictionary, string enreplacedyName, string attributeName, object value)
		{
			if (context == null || string.IsNullOrWhiteSpace(enreplacedyName) || string.IsNullOrWhiteSpace(attributeName))
			{
				return string.Empty;
			}

			var newValue = string.Empty;
			var attributeTypeCode = attributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;

			if (attributeTypeCode == null)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, "Unable to recognize the attribute specified.");
				return string.Empty;
			}

			try
			{
				switch (attributeTypeCode)
				{
					case AttributeTypeCode.BigInt:
						newValue = value == null ? string.Empty : Convert.ToInt64(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Boolean:
						newValue = value == null ? string.Empty : Convert.ToBoolean(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Customer:
						if (value is EnreplacedyReference)
						{
							var enreplacedyref = value as EnreplacedyReference;
							newValue = enreplacedyref.Id.ToString();
						}
						break;
					case AttributeTypeCode.DateTime:
						newValue = value == null ? string.Empty : Convert.ToDateTime(value).ToUniversalTime().ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Decimal:
						newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Double:
						newValue = value == null ? string.Empty : Convert.ToDouble(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Integer:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Lookup:
						if (value is EnreplacedyReference)
						{
							var enreplacedyref = value as EnreplacedyReference;
							newValue = enreplacedyref.Id.ToString();
						}
						break;
					case AttributeTypeCode.Memo:
						newValue = value as string;
						break;
					case AttributeTypeCode.Money:
						newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Picklist:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.State:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.Status:
						newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
						break;
					case AttributeTypeCode.String:
						newValue = value as string;
						break;
					case AttributeTypeCode.Uniqueidentifier:
						if (value is Guid)
						{
							var id = (Guid)value;
							newValue = id.ToString();
						}
						break;
					default:
						ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute type '{0}' is unsupported.", attributeTypeCode));
						break;
				}
			}
			catch (Exception ex)
			{
				WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute specified is expecting a {0}. The value provided is not valid.", attributeTypeCode));
			}
			return newValue;
		}

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public TransHistory GetTransHistory(
            int? from = null,
            int? count = null,
            int? fromId = null,
            int? endId = null,
            bool? orderAsc = null,
            DateTime? since = null,
            DateTime? end = null
            )
        {
            var args = new NameValueDictionary();

            if (from != null) args.Add("from", from.Value.ToString(CultureInfo.InvariantCulture));
			if (count != null) args.Add("count", count.Value.ToString(CultureInfo.InvariantCulture));
			if (fromId != null) args.Add("from_id", fromId.Value.ToString(CultureInfo.InvariantCulture));
			if (endId != null) args.Add("end_id", endId.Value.ToString(CultureInfo.InvariantCulture));
            if (orderAsc != null) args.Add("order", orderAsc.Value ? "ASC" : "DESC");
			if (since != null) args.Add("since", UnixTime.GetFromDateTime(since.Value).ToString(CultureInfo.InvariantCulture));
			if (end != null) args.Add("end", UnixTime.GetFromDateTime(end.Value).ToString(CultureInfo.InvariantCulture));
            
			var json = Query("TransHistory", args);
	        var result = DeserializeBtceObject<TransHistory>(json);
	        return result;
        }

19 View Source File : SolarAnalysisManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private static List<DirectSunTestFace> CreateEmptyTestFaces(IList<Reference> faceSelection, Doreplacedent doc)
        {
            int n = 0;
            List<DirectSunTestFace> result = new List<DirectSunTestFace>();
            foreach (Reference r in faceSelection) {
                n++;
                Element elem = doc.GetElement(r);
                Face f = (Face)elem.GetGeometryObjectFromReference(r);
                f.ComputeNormal(new UV(0, 0));
                result.Add(new DirectSunTestFace(r, @"DirectSun(" + n.ToString(CultureInfo.CurrentCulture) + @")", doc));
            }
            return result;
        }

19 View Source File : Rope.cs
License : MIT License
Project Creator : Abdesol

public void InsertRange(int index, Rope<T> newElements)
		{
			if (index < 0 || index > this.Length) {
				throw new ArgumentOutOfRangeException("index", index, "0 <= index <= " + this.Length.ToString(CultureInfo.InvariantCulture));
			}
			if (newElements == null)
				throw new ArgumentNullException("newElements");
			newElements.root.Publish();
			root = root.Insert(index, newElements.root);
			OnChanged();
		}

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public string getWithdrawal(int withdrawalID, CurrencyType currency = CurrencyType.BTC)
        {
            const string method = "getWithdrawal";
			string mParams = withdrawalID.ToString(CultureInfo.InvariantCulture);
            if (currency != CurrencyType.BTC)
                mParams += ",\"" + System.Enum.GetName(typeof(CurrencyType), currency) + "\"";//should be "LTC" but for further implmentations
            return DoMethod(BuildParams(method, mParams));
        }

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

public async Task<List<IStep>> InitializeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message)
        {
            Trace.Entering();
            ArgUtil.NotNull(jobContext, nameof(jobContext));
            ArgUtil.NotNull(message, nameof(message));

            // Create a new timeline record for 'Set up job'
            IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Set up job", $"{nameof(JobExtension)}_Init", null, null, ActionRunStage.Pre);

            List<IStep> preJobSteps = new List<IStep>();
            List<IStep> jobSteps = new List<IStep>();
            using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
            {
                try
                {
                    context.Start();
                    context.Debug($"Starting: Set up job");
                    context.Output($"Current runner version: '{BuildConstants.RunnerPackage.Version}'");

                    var setting = HostContext.GetService<IConfigurationStore>().GetSettings();
                    var credFile = HostContext.GetConfigFile(WellKnownConfigFile.Credentials);
                    if (File.Exists(credFile))
                    {
                        var credData = IOUtil.LoadObject<CredentialData>(credFile);
                        if (credData != null &&
                            credData.Data.TryGetValue("clientId", out var clientId))
                        {
                            // print out HostName for self-hosted runner
                            context.Output($"Runner name: '{setting.AgentName}'");
                            if (message.Variables.TryGetValue("system.runnerGroupName", out VariableValue runnerGroupName))
                            {
                                context.Output($"Runner group name: '{runnerGroupName.Value}'");
                            }
                            context.Output($"Machine name: '{Environment.MachineName}'");
                        }
                    }

                    var setupInfoFile = HostContext.GetConfigFile(WellKnownConfigFile.SetupInfo);
                    if (File.Exists(setupInfoFile))
                    {
                        Trace.Info($"Load machine setup info from {setupInfoFile}");
                        try
                        {
                            var setupInfo = IOUtil.LoadObject<List<SetupInfo>>(setupInfoFile);
                            if (setupInfo?.Count > 0)
                            {
                                foreach (var info in setupInfo)
                                {
                                    if (!string.IsNullOrEmpty(info?.Detail))
                                    {
                                        var groupName = info.Group;
                                        if (string.IsNullOrEmpty(groupName))
                                        {
                                            groupName = "Machine Setup Info";
                                        }

                                        context.Output($"##[group]{groupName}");
                                        var multiLines = info.Detail.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
                                        foreach (var line in multiLines)
                                        {
                                            context.Output(line);
                                        }
                                        context.Output("##[endgroup]");
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Output($"Fail to load and print machine setup info: {ex.Message}");
                            Trace.Error(ex);
                        }
                    }

                    try 
                    {
                        var tokenPermissions = jobContext.Global.Variables.Get("system.github.token.permissions") ?? "";
                        if (!string.IsNullOrEmpty(tokenPermissions))
                        {
                            context.Output($"##[group]GITHUB_TOKEN Permissions");
                            var permissions = StringUtil.ConvertFromJson<Dictionary<string, string>>(tokenPermissions);
                            foreach(KeyValuePair<string, string> entry in permissions)
                            {
                                context.Output($"{entry.Key}: {entry.Value}");
                            }
                            context.Output("##[endgroup]");
                        }
                    } 
                    catch (Exception ex)
                    {
                        context.Output($"Fail to parse and display GITHUB_TOKEN permissions list: {ex.Message}");
                        Trace.Error(ex);
                    }

                    var repoFullName = context.GetGitHubContext("repository");
                    ArgUtil.NotNull(repoFullName, nameof(repoFullName));
                    context.Debug($"Primary repository: {repoFullName}");

                    // Print proxy setting information for better diagnostic experience
                    if (!string.IsNullOrEmpty(HostContext.WebProxy.HttpProxyAddress))
                    {
                        context.Output($"Runner is running behind proxy server '{HostContext.WebProxy.HttpProxyAddress}' for all HTTP requests.");
                    }
                    if (!string.IsNullOrEmpty(HostContext.WebProxy.HttpsProxyAddress))
                    {
                        context.Output($"Runner is running behind proxy server '{HostContext.WebProxy.HttpsProxyAddress}' for all HTTPS requests.");
                    }

                    // Prepare the workflow directory
                    context.Output("Prepare workflow directory");
                    var directoryManager = HostContext.GetService<IPipelineDirectoryManager>();
                    TrackingConfig trackingConfig = directoryManager.PrepareDirectory(
                        context,
                        message.Workspace);

                    // Set the directory variables
                    context.Debug("Update context data");
                    string _workDirectory = HostContext.GetDirectory(WellKnownDirectory.Work);
                    context.SetRunnerContext("workspace", Path.Combine(_workDirectory, trackingConfig.PipelineDirectory));
                    context.SetGitHubContext("workspace", Path.Combine(_workDirectory, trackingConfig.WorkspaceDirectory));

                    // Temporary hack for GHES alpha
                    var configurationStore = HostContext.GetService<IConfigurationStore>();
                    var runnerSettings = configurationStore.GetSettings();
                    if (string.IsNullOrEmpty(context.GetGitHubContext("server_url")) && !runnerSettings.IsHostedServer && !string.IsNullOrEmpty(runnerSettings.GitHubUrl))
                    {
                        var url = new Uri(runnerSettings.GitHubUrl);
                        var portInfo = url.IsDefaultPort ? string.Empty : $":{url.Port.ToString(CultureInfo.InvariantCulture)}";
                        context.SetGitHubContext("server_url", $"{url.Scheme}://{url.Host}{portInfo}");
                        context.SetGitHubContext("api_url", $"{url.Scheme}://{url.Host}{portInfo}/api/v3");
                        context.SetGitHubContext("graphql_url", $"{url.Scheme}://{url.Host}{portInfo}/api/graphql");
                    }

                    // Evaluate the job-level environment variables
                    context.Debug("Evaluating job-level environment variables");
                    var templateEvaluator = context.ToPipelineTemplateEvaluator();
                    foreach (var token in message.EnvironmentVariables)
                    {
                        var environmentVariables = templateEvaluator.EvaluateStepEnvironment(token, jobContext.ExpressionValues, jobContext.ExpressionFunctions, VarUtil.EnvironmentVariableKeyComparer);
                        foreach (var pair in environmentVariables)
                        {
                            context.Global.EnvironmentVariables[pair.Key] = pair.Value ?? string.Empty;
                            context.SetEnvContext(pair.Key, pair.Value ?? string.Empty);
                        }
                    }

                    // Evaluate the job container
                    context.Debug("Evaluating job container");
                    var container = templateEvaluator.EvaluateJobContainer(message.JobContainer, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
                    if (container != null)
                    {
                        jobContext.Global.Container = new Container.ContainerInfo(HostContext, container);
                    }

                    // Evaluate the job service containers
                    context.Debug("Evaluating job service containers");
                    var serviceContainers = templateEvaluator.EvaluateJobServiceContainers(message.JobServiceContainers, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
                    if (serviceContainers?.Count > 0)
                    {
                        foreach (var pair in serviceContainers)
                        {
                            var networkAlias = pair.Key;
                            var serviceContainer = pair.Value;
                            jobContext.Global.ServiceContainers.Add(new Container.ContainerInfo(HostContext, serviceContainer, false, networkAlias));
                        }
                    }

                    // Evaluate the job defaults
                    context.Debug("Evaluating job defaults");
                    foreach (var token in message.Defaults)
                    {
                        var defaults = token.replacedertMapping("defaults");
                        if (defaults.Any(x => string.Equals(x.Key.replacedertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase)))
                        {
                            context.Global.JobDefaults["run"] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                            var defaultsRun = defaults.First(x => string.Equals(x.Key.replacedertString("defaults key").Value, "run", StringComparison.OrdinalIgnoreCase));
                            var jobDefaults = templateEvaluator.EvaluateJobDefaultsRun(defaultsRun.Value, jobContext.ExpressionValues, jobContext.ExpressionFunctions);
                            foreach (var pair in jobDefaults)
                            {
                                if (!string.IsNullOrEmpty(pair.Value))
                                {
                                    context.Global.JobDefaults["run"][pair.Key] = pair.Value;
                                }
                            }
                        }
                    }

                    // Build up 2 lists of steps, pre-job, job
                    // Download actions not already in the cache
                    Trace.Info("Downloading actions");
                    var actionManager = HostContext.GetService<IActionManager>();
                    var prepareResult = await actionManager.PrepareActionsAsync(context, message.Steps);
                    preJobSteps.AddRange(prepareResult.ContainerSetupSteps);

                    // Add start-container steps, record and stop-container steps
                    if (jobContext.Global.Container != null || jobContext.Global.ServiceContainers.Count > 0)
                    {
                        var containerProvider = HostContext.GetService<IContainerOperationProvider>();
                        var containers = new List<Container.ContainerInfo>();
                        if (jobContext.Global.Container != null)
                        {
                            containers.Add(jobContext.Global.Container);
                        }
                        containers.AddRange(jobContext.Global.ServiceContainers);

                        preJobSteps.Add(new JobExtensionRunner(runAsync: containerProvider.StartContainersAsync,
                                                                          condition: $"{PipelineTemplateConstants.Success}()",
                                                                          displayName: "Initialize containers",
                                                                          data: (object)containers));
                    }

                    // Add action steps
                    foreach (var step in message.Steps)
                    {
                        if (step.Type == Pipelines.StepType.Action)
                        {
                            var action = step as Pipelines.ActionStep;
                            Trace.Info($"Adding {action.DisplayName}.");
                            var actionRunner = HostContext.CreateService<IActionRunner>();
                            actionRunner.Action = action;
                            actionRunner.Stage = ActionRunStage.Main;
                            actionRunner.Condition = step.Condition;
                            var contextData = new Pipelines.ContextData.DictionaryContextData();
                            if (message.ContextData?.Count > 0)
                            {
                                foreach (var pair in message.ContextData)
                                {
                                    contextData[pair.Key] = pair.Value;
                                }
                            }

                            actionRunner.TryEvaluateDisplayName(contextData, context);
                            jobSteps.Add(actionRunner);

                            if (prepareResult.PreStepTracker.TryGetValue(step.Id, out var preStep))
                            {
                                Trace.Info($"Adding pre-{action.DisplayName}.");
                                preStep.TryEvaluateDisplayName(contextData, context);
                                preStep.DisplayName = $"Pre {preStep.DisplayName}";
                                preJobSteps.Add(preStep);
                            }
                        }
                    }

                    var intraActionStates = new Dictionary<Guid, Dictionary<string, string>>();
                    foreach (var preStep in prepareResult.PreStepTracker)
                    {
                        intraActionStates[preStep.Key] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    }

                    // Create execution context for pre-job steps
                    foreach (var step in preJobSteps)
                    {
                        if (step is JobExtensionRunner)
                        {
                            JobExtensionRunner extensionStep = step as JobExtensionRunner;
                            ArgUtil.NotNull(extensionStep, extensionStep.DisplayName);
                            Guid stepId = Guid.NewGuid();
                            extensionStep.ExecutionContext = jobContext.CreateChild(stepId, extensionStep.DisplayName, null, null, stepId.ToString("N"), ActionRunStage.Pre);
                        }
                        else if (step is IActionRunner actionStep)
                        {
                            ArgUtil.NotNull(actionStep, step.DisplayName);
                            Guid stepId = Guid.NewGuid();
                            actionStep.ExecutionContext = jobContext.CreateChild(stepId, actionStep.DisplayName, stepId.ToString("N"), null, null, ActionRunStage.Pre, intraActionStates[actionStep.Action.Id]);
                        }
                    }

                    // Create execution context for job steps
                    foreach (var step in jobSteps)
                    {
                        if (step is IActionRunner actionStep)
                        {
                            ArgUtil.NotNull(actionStep, step.DisplayName);
                            intraActionStates.TryGetValue(actionStep.Action.Id, out var intraActionState);
                            actionStep.ExecutionContext = jobContext.CreateChild(actionStep.Action.Id, actionStep.DisplayName, actionStep.Action.Name, null, actionStep.Action.ContextName, ActionRunStage.Main, intraActionState);
                        }
                    }

                    List<IStep> steps = new List<IStep>();
                    steps.AddRange(preJobSteps);
                    steps.AddRange(jobSteps);

                    // Prepare for orphan process cleanup
                    _processCleanup = jobContext.Global.Variables.GetBoolean("process.clean") ?? true;
                    if (_processCleanup)
                    {
                        // Set the RUNNER_TRACKING_ID env variable.
                        Environment.SetEnvironmentVariable(Constants.ProcessTrackingId, _processLookupId);
                        context.Debug("Collect running processes for tracking orphan processes.");

                        // Take a snapshot of current running processes
                        Dictionary<int, Process> processes = SnapshotProcesses();
                        foreach (var proc in processes)
                        {
                            // Pid_ProcessName
                            _existingProcesses.Add($"{proc.Key}_{proc.Value.ProcessName}");
                        }
                    }

                    jobContext.Global.EnvironmentVariables.TryGetValue(Constants.Runner.Features.DiskSpaceWarning, out var enableWarning);
                    if (StringUtil.ConvertToBoolean(enableWarning, defaultValue: true))
                    {
                        _diskSpaceCheckTask = CheckDiskSpaceAsync(context, _diskSpaceCheckToken.Token);
                    }

                    return steps;
                }
                catch (OperationCanceledException ex) when (jobContext.CancellationToken.IsCancellationRequested)
                {
                    // Log the exception and cancel the JobExtension Initialization.
                    Trace.Error($"Caught cancellation exception from JobExtension Initialization: {ex}");
                    context.Error(ex);
                    context.Result = TaskResult.Canceled;
                    throw;
                }
                catch (FailedToResolveActionDownloadInfoException ex)
                {
                    // Log the error and fail the JobExtension Initialization.
                    Trace.Error($"Caught exception from JobExtenion Initialization: {ex}");
                    context.InfrastructureError(ex.Message);
                    context.Result = TaskResult.Failed;
                    throw;
                }
                catch (Exception ex)
                {
                    // Log the error and fail the JobExtension Initialization.
                    Trace.Error($"Caught exception from JobExtension Initialization: {ex}");
                    context.Error(ex);
                    context.Result = TaskResult.Failed;
                    throw;
                }
                finally
                {
                    context.Debug("Finishing: Set up job");
                    context.Complete();
                }
            }
        }

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

private string DoMethod(NameValueCollection jParams)
	    {
		    const int RequestTimeoutMilliseconds = 2*1000; // 2 sec 

		    string tempResult = "";

		    try
		    {
			    lock (m_tonceLock)
			    {
				    //get tonce
				    TimeSpan timeSpan = DateTime.UtcNow - genesis;
				    long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
				    jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
				    //mock json request id
				    jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
				    //build http head
				    string paramsHash = GetHMACSHA1Hash(jParams);
				    string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
				    string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
				                      jParams[pId] + "}";

				    //get webrequest,respawn new object per call for multiple connections
				    var webRequest = (HttpWebRequest) WebRequest.Create(url);
				    webRequest.Timeout = RequestTimeoutMilliseconds;

				    var bytes = Encoding.ASCII.GetBytes(postData);

				    webRequest.Method = jParams[pRequestMethod];
				    webRequest.ContentType = "application/json-rpc";
				    webRequest.ContentLength = bytes.Length;
				    webRequest.Headers["Authorization"] = "Basic " + base64String;
				    webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];

				    // Send the json authentication post request
				    using (var dataStream = webRequest.GetRequestStream())
				    {
					    dataStream.Write(bytes, 0, bytes.Length);
				    }

				    // Get authentication response
				    using (var response = webRequest.GetResponse())
				    {
					    using (var stream = response.GetResponseStream())
					    {
// ReSharper disable once replacedignNullToNotNullAttribute
						    using (var reader = new StreamReader(stream))
						    {
							    tempResult = reader.ReadToEnd();
						    }
					    }
				    }
			    }
		    }
		    catch (WebException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
		    }

		    //there are two kinds of API response, result or error.
		    if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
		    }

		    //compare response id with request id and remove it from result
		    try
		    {
			    int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
			    string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
			    if (idString != jParams[pId])
			    {
				    throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
			    }
			    else
			    {
				    //remove json request id from response json string
				    int fromComma = tempResult.LastIndexOf(',');
				    int toLastBrace = tempResult.Length - 1;
				    tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
			    }
		    }
		    catch (ArgumentOutOfRangeException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
		    }

		    return tempResult;
	    }

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

[EditorBrowsable(EditorBrowsableState.Never)]
        public virtual Task<List<PackageMetadata>> GetPackagesAsync(
            string packageType,
            string platform = null,
            int? top = null,
            bool? includeToken = null,
            object userState = null,
            CancellationToken cancellationToken = default)
        {
            HttpMethod httpMethod = new HttpMethod("GET");
            Guid locationId = new Guid("8ffcd551-079c-493a-9c02-54346299d144");
            object routeValues = new { packageType = packageType, platform = platform };

            List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
            if (top != null)
            {
                queryParams.Add("$top", top.Value.ToString(CultureInfo.InvariantCulture));
            }
            if (includeToken != null)
            {
                queryParams.Add("includeToken", includeToken.Value.ToString());
            }

            return SendAsync<List<PackageMetadata>>(
                httpMethod,
                locationId,
                routeValues: routeValues,
                version: new ApiResourceVersion(5.1, 2),
                queryParameters: queryParams,
                userState: userState,
                cancellationToken: cancellationToken);
        }

19 View Source File : SimpleSegment.cs
License : MIT License
Project Creator : Abdesol

public override string ToString()
		{
			return "[Offset=" + Offset.ToString(CultureInfo.InvariantCulture) + ", EndOffset=" + EndOffset.ToString(CultureInfo.InvariantCulture) + "]";
		}

19 View Source File : Repository.cs
License : Apache License 2.0
Project Creator : adamralph

public Version GetVersion(string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log)
        {
            var commit = this.head;

            if (commit == null)
            {
                var version = new Version(defaultPreReleasePhase);

                log.Info($"No commits found. Using default version {version}.");

                return version;
            }

            var tagsAndVersions = this.tags
                .Select(tag => (tag, Version.ParseOrDefault(tag.Name, tagPrefix)))
                .OrderBy(tagAndVersion => tagAndVersion.Item2)
                .ThenBy(tagsAndVersion => tagsAndVersion.tag.Name)
                .ToList();

            var commitsChecked = new HashSet<string>();
            var count = 0;
            var height = 0;
            var candidates = new List<Candidate>();
            var commitsToCheck = new Stack<(Commit, int, Commit)>();
            Commit previousCommit = null;

            if (log.IsTraceEnabled)
            {
                log.Trace($"Starting at commit {commit.ShortSha} (height {height})...");
            }

            while (true)
            {
                var parentCount = 0;

                if (commitsChecked.Add(commit.Sha))
                {
                    ++count;

                    var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Sha == commit.Sha).ToList();
                    var foundVersion = false;

                    foreach (var (tag, commitVersion) in commitTagsAndVersions)
                    {
                        var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.Name, Version = commitVersion, Index = candidates.Count };

                        foundVersion = foundVersion || candidate.Version != null;

                        if (log.IsTraceEnabled)
                        {
                            log.Trace($"Found {(candidate.Version == null ? "non-" : null)}version tag {candidate}.");
                        }

                        candidates.Add(candidate);
                    }

                    if (!foundVersion)
                    {
                        if (log.IsTraceEnabled)
                        {
                            var parentIndex = 0;
                            Commit firstParent = null;

                            foreach (var parent in commit.Parents)
                            {
                                switch (parentIndex)
                                {
                                    case 0:
                                        firstParent = parent;
                                        break;
                                    case 1:
                                        log.Trace($"History diverges from {commit.ShortSha} (height {height}) to:");
                                        log.Trace($"- {firstParent.ShortSha} (height {height + 1})");
                                        goto default;
                                    default:
                                        log.Trace($"- {parent.ShortSha} (height {height + 1})");
                                        break;
                                }

                                ++parentIndex;
                                parentCount = parentIndex;
                            }
                        }

                        foreach (var parent in ((IEnumerable<Commit>)commit.Parents).Reverse())
                        {
                            commitsToCheck.Push((parent, height + 1, commit));
                        }

                        if (commitsToCheck.Count == 0 || commitsToCheck.Peek().Item2 <= height)
                        {
                            var candidate = new Candidate { Commit = commit, Height = height, Tag = null, Version = new Version(defaultPreReleasePhase), Index = candidates.Count };

                            if (log.IsTraceEnabled)
                            {
                                log.Trace($"Found root commit {candidate}.");
                            }

                            candidates.Add(candidate);
                        }
                    }
                }
                else
                {
                    if (log.IsTraceEnabled)
                    {
                        log.Trace($"History converges from {previousCommit.ShortSha} (height {height - 1}) back to previously seen commit {commit.ShortSha} (height {height}). Abandoning path.");
                    }
                }

                if (commitsToCheck.Count == 0)
                {
                    break;
                }

                if (log.IsTraceEnabled)
                {
                    previousCommit = commit;
                }

                var oldHeight = height;
                Commit child;
                (commit, height, child) = commitsToCheck.Pop();

                if (log.IsTraceEnabled)
                {
                    if (parentCount > 1)
                    {
                        log.Trace($"Following path from {child.ShortSha} (height {height - 1}) through first parent {commit.ShortSha} (height {height})...");
                    }
                    else if (height <= oldHeight)
                    {
                        if (commitsToCheck.Any() && commitsToCheck.Peek().Item2 == height)
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through next parent {commit.ShortSha} (height {height})...");
                        }
                        else
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through last parent {commit.ShortSha} (height {height})...");
                        }
                    }
                }
            }

            log.Debug($"{count:N0} commits checked.");

            var orderedCandidates = candidates.OrderBy(candidate => candidate.Version).ThenByDescending(candidate => candidate.Index).ToList();

            var tagWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Tag?.Length ?? 2) : 0;
            var versionWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Version?.ToString().Length ?? 4) : 0;
            var heightWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Height).ToString(CultureInfo.CurrentCulture).Length : 0;

            if (log.IsDebugEnabled)
            {
                foreach (var candidate in orderedCandidates.Take(orderedCandidates.Count - 1))
                {
                    log.Debug($"Ignoring {candidate.ToString(tagWidth, versionWidth, heightWidth)}.");
                }
            }

            var selectedCandidate = orderedCandidates.Last();

            if (selectedCandidate.Tag == null)
            {
                log.Info($"No commit found with a valid SemVer 2.0 version{(tagPrefix == null ? null : $" prefixed with '{tagPrefix}'")}. Using default version {selectedCandidate.Version}.");
            }

            log.Info($"Using{(log.IsDebugEnabled && orderedCandidates.Count > 1 ? "    " : " ")}{selectedCandidate.ToString(tagWidth, versionWidth, heightWidth)}.");

            return selectedCandidate.Version.WithHeight(selectedCandidate.Height, autoIncrement, defaultPreReleasePhase);
        }

19 View Source File : HuobiAPI.cs
License : MIT License
Project Creator : aabiryukov

public bool CancelOrder(int orderId)
        {
	        var args = new NameValueCollection
	        {
                {"coin_type", ((int)CoinType.Btc).ToString(CultureInfo.InvariantCulture)},
                {"id", orderId.ToString(CultureInfo.InvariantCulture)}
	        };

	        var response = DoMethod2("cancel_order", args);
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");

	        return success;
        }

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

private static void SetResponseParameters(HttpResponseBase response, HttpCacheability defaultCacheability,
			Enreplacedy attachment, Enreplacedy webfile, ICollection<byte> data)
		{
			response.StatusCode = (int)HttpStatusCode.OK;
			response.ContentType = attachment.GetAttributeValue<string>("mimetype");

			var contentDispositionText = "inline";

			if (webfile != null)
			{
				var contentDispositionOptionSetValue = webfile.GetAttributeValue<OptionSetValue>("adx_contentdisposition");

				if (contentDispositionOptionSetValue != null)
				{
					switch (contentDispositionOptionSetValue.Value)
					{
						case 756150000: // inline
							contentDispositionText = "inline";
							break;
						case 756150001: // attachment
							contentDispositionText = "attachment";
							break;
						default:
							contentDispositionText = "inline";
							break;
					}
				}
			}

			if (string.Equals(response.ContentType, "text/html", StringComparison.OrdinalIgnoreCase) ||
				string.Equals(response.ContentType, "application/octet-stream", StringComparison.OrdinalIgnoreCase))
			{
				contentDispositionText = "attachment";
			}

			var contentDisposition = new StringBuilder(contentDispositionText);

			AppendFilenameToContentDisposition(attachment, contentDisposition);

			response.AppendHeader("Content-Disposition", contentDisposition.ToString());
			response.AppendHeader("Content-Length", data.Count.ToString(CultureInfo.InvariantCulture));

			var section = PortalCrmConfigurationManager.GetPortalCrmSection();
			var policy = section.CachePolicy.Annotation;

			Utility.SetResponseCachePolicy(policy, response, defaultCacheability);
		}

19 View Source File : Rope.cs
License : MIT License
Project Creator : Abdesol

internal static void VerifyArrayWithRange(T[] array, int arrayIndex, int count)
		{
			if (array == null)
				throw new ArgumentNullException("array");
			if (arrayIndex < 0 || arrayIndex > array.Length) {
				throw new ArgumentOutOfRangeException("startIndex", arrayIndex, "0 <= arrayIndex <= " + array.Length.ToString(CultureInfo.InvariantCulture));
			}
			if (count < 0 || arrayIndex + count > array.Length) {
				throw new ArgumentOutOfRangeException("count", count, "0 <= length, arrayIndex(" + arrayIndex + ")+count <= " + array.Length.ToString(CultureInfo.InvariantCulture));
			}
		}

19 View Source File : ThrowUtil.cs
License : MIT License
Project Creator : Abdesol

public static int CheckInRangeInclusive(int val, string parameterName, int lower, int upper)
		{
			if (val < lower || val > upper)
				throw new ArgumentOutOfRangeException(parameterName, val, "Expected: " + lower.ToString(CultureInfo.InvariantCulture) + " <= " + parameterName + " <= " + upper.ToString(CultureInfo.InvariantCulture));
			return val;
		}

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public static Dictionary<WexPair, Depth> GetDepth(WexPair[] pairlist, int limit = 150)
        {
			return MakeRequest(
				"depth", 
				pairlist, 
				x => Depth.ReadFromJObject(x as JObject), 
				new Dictionary<string, string> { { "limit", limit.ToString(CultureInfo.InvariantCulture) } }
				);
        }

19 View Source File : LineNumberMargin.cs
License : MIT License
Project Creator : Abdesol

void OnDoreplacedentLineCountChanged()
		{
			int doreplacedentLineCount = Doreplacedent != null ? Doreplacedent.LineCount : 1;
			int newLength = doreplacedentLineCount.ToString(CultureInfo.CurrentCulture).Length;

			// The margin looks too small when there is only one digit, so always reserve space for
			// at least two digits
			if (newLength < 2)
				newLength = 2;

			if (newLength != maxLineNumberLength) {
				maxLineNumberLength = newLength;
				InvalidateMeasure();
			}
		}

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public TradeHistory GetTradeHistory(
            int? from = null,
            int? count = null,
            int? fromId = null,
            int? endId = null,
            bool? orderAsc = null,
            DateTime? since = null,
            DateTime? end = null
            )
        {
			var args = new NameValueDictionary();

			if (from != null) args.Add("from", from.Value.ToString(CultureInfo.InvariantCulture));
			if (count != null) args.Add("count", count.Value.ToString(CultureInfo.InvariantCulture));
			if (fromId != null) args.Add("from_id", fromId.Value.ToString(CultureInfo.InvariantCulture));
			if (endId != null) args.Add("end_id", endId.Value.ToString(CultureInfo.InvariantCulture));
            if (orderAsc != null) args.Add("order", orderAsc.Value ? "ASC" : "DESC");
			if (since != null) args.Add("since", UnixTime.GetFromDateTime(since.Value).ToString(CultureInfo.InvariantCulture));
			if (end != null) args.Add("end", UnixTime.GetFromDateTime(end.Value).ToString(CultureInfo.InvariantCulture));

			var json = Query("TradeHistory", args);
			var result = DeserializeBtceObject<TradeHistory>(json);
			return result;
        }

19 View Source File : SheetCopierManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public string GetNewSheetNumber(string originalNumber)
        {
            if (string.IsNullOrEmpty(originalNumber)) {
                return null;
            }
            int inc = 0;
            do {
                inc++;
            } while (!SheetNumberAvailable(originalNumber + "-" + inc.ToString(CultureInfo.InvariantCulture)));
            return originalNumber + "-" + inc.ToString(CultureInfo.InvariantCulture);
        }

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static void RegisterDefaultConverters()
		{
			//TODO: there is too much generic type combinations! need to refactor this ...

			RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
			RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
			RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
			RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
			RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
			RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
			RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
			RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
			RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
			RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
			RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
			RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
			RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);

			RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<int, bool>((value) => value != 0);
			RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<int, byte>((value) => checked((byte)value));
			RegisterUnsafe<int, short>((value) => checked((short)value));
			RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<int, uint>((value) => (uint)value);
			RegisterUnsafe<int, long>((value) => value);
			RegisterUnsafe<int, ulong>((value) => (ulong)value);
			RegisterUnsafe<int, double>((value) => value);
			RegisterUnsafe<int, float>((value) => checked((float)value));
			RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<uint, bool>((value) => value != 0);
			RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<uint, byte>((value) => checked((byte)value));
			RegisterUnsafe<uint, short>((value) => checked((short)value));
			RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<uint, int>((value) => (int)value);
			RegisterUnsafe<uint, long>((value) => value);
			RegisterUnsafe<uint, ulong>((value) => value);
			RegisterUnsafe<uint, double>((value) => value);
			RegisterUnsafe<uint, float>((value) => checked((float)value));

			RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<long, bool>((value) => value != 0);
			RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<long, byte>((value) => checked((byte)value));
			RegisterUnsafe<long, short>((value) => checked((short)value));
			RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<long, int>((value) => checked((int)value));
			RegisterUnsafe<long, uint>((value) => (uint)value);
			RegisterUnsafe<long, ulong>((value) => (ulong)value);
			RegisterUnsafe<long, double>((value) => checked((double)value));
			RegisterUnsafe<long, float>((value) => checked((float)value));
			RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
			RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));

			RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ulong, bool>((value) => value != 0);
			RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
			RegisterUnsafe<ulong, short>((value) => checked((short)value));
			RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<ulong, int>((value) => checked((int)value));
			RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
			RegisterUnsafe<ulong, long>((value) => checked((long)value));
			RegisterUnsafe<ulong, double>((value) => checked((double)value));
			RegisterUnsafe<ulong, float>((value) => checked((float)value));
			RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));

			RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<short, bool>((value) => value != 0);
			RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<short, byte>((value) => checked((byte)value));
			RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<short, int>((value) => value);
			RegisterUnsafe<short, uint>((value) => checked((uint)value));
			RegisterUnsafe<short, long>((value) => value);
			RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<short, double>((value) => value);
			RegisterUnsafe<short, float>((value) => value);
			RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ushort, bool>((value) => value != 0);
			RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
			RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ushort, short>((value) => checked((short)value));
			RegisterUnsafe<ushort, int>((value) => value);
			RegisterUnsafe<ushort, uint>((value) => value);
			RegisterUnsafe<ushort, long>((value) => value);
			RegisterUnsafe<ushort, ulong>((value) => value);
			RegisterUnsafe<ushort, double>((value) => value);
			RegisterUnsafe<ushort, float>((value) => value);

			RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<byte, bool>((value) => value != 0);
			RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<byte, short>((value) => value);
			RegisterUnsafe<byte, ushort>((value) => value);
			RegisterUnsafe<byte, int>((value) => value);
			RegisterUnsafe<byte, uint>((value) => value);
			RegisterUnsafe<byte, long>((value) => value);
			RegisterUnsafe<byte, ulong>((value) => value);
			RegisterUnsafe<byte, double>((value) => value);
			RegisterUnsafe<byte, float>((value) => value);
			RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<sbyte, bool>((value) => value != 0);
			RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
			RegisterUnsafe<sbyte, short>((value) => value);
			RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<sbyte, int>((value) => value);
			RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
			RegisterUnsafe<sbyte, long>((value) => value);
			RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<sbyte, double>((value) => value);
			RegisterUnsafe<sbyte, float>((value) => value);

			RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
			RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
			RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
			RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<float, byte>((value) => checked((byte)value));
			RegisterUnsafe<float, short>((value) => checked((short)value));
			RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<float, int>((value) => checked((int)value));
			RegisterUnsafe<float, uint>((value) => (uint)value);
			RegisterUnsafe<float, long>((value) => checked((long)value));
			RegisterUnsafe<float, ulong>((value) => (ulong)value);
			RegisterUnsafe<float, double>((value) => value);

			RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
			RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
			RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
			RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<double, byte>((value) => checked((byte)value));
			RegisterUnsafe<double, short>((value) => checked((short)value));
			RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<double, int>((value) => checked((int)value));
			RegisterUnsafe<double, uint>((value) => (uint)value);
			RegisterUnsafe<double, long>((value) => checked((long)value));
			RegisterUnsafe<double, ulong>((value) => (ulong)value);
			RegisterUnsafe<double, float>((value) => checked((float)value));

			RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
			RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
			RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
			RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
			RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
			RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
			RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));

			RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
			RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
			RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
			RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
			RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
			RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
			RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
			RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
			RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
			RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
			RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
			RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
			RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
			RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
			RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
			RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));

			RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
			RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
			RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
			RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));

			RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));

			RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
			RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);

			RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
			RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
			RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
			RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
			RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
			RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);

			RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
			RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
			RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);

			RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
			RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
			RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));

			//REVIEW: this should go in the Tuples layer !
			RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
			RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
			RegisterUnsafe<Slice, bool>((value) => value.ToBool());
			RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
			RegisterUnsafe<Slice, byte>((value) => value.ToByte());
			RegisterUnsafe<Slice, short>((value) => value.ToInt16());
			RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
			RegisterUnsafe<Slice, int>((value) => value.ToInt32());
			RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
			RegisterUnsafe<Slice, long>((value) => value.ToInt64());
			RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
			RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
			RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
			RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
			RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
		}

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public bool cancelOrder(int orderID, MarketType market=MarketType.BTCCNY)
        {
            const string method = "cancelOrder";
            string mParams = orderID.ToString(CultureInfo.InvariantCulture);
            //all is not supported
            if (market == MarketType.ALL)
                throw new BTCChinaException(method, "N/A", "Market:ALL is not supported.");
            //not default market
            if (market != MarketType.BTCCNY)
                mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";

            var response = DoMethod(BuildParams(method, mParams));
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");

	        return success;
        }

19 View Source File : SolarAnalysisManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private bool CreateShadowPlanViews(ModelSetupWizard.TransactionLog log)
        {
            var id = GetViewFamilyId(doc, ViewFamily.FloorPlan);
            var levelId = GetHighestLevel(doc);
            if (id == null || levelId == null) {
                log.AddFailure("Could not gererate shadow plans. FamilyId or LevelId not found");
                return false;
            }

            while (StartTime <= EndTime) {
                using (var t = new Transaction(doc))
                {
                    if (t.Start("Create Shadow Plans") == TransactionStatus.Started) {
                        View view = ViewPlan.Create(doc, id, levelId);
                        view.ViewTemplateId = ElementId.InvalidElementId;
                        var niceMinutes = "00";
                        if (StartTime.Minute > 0) {
                            niceMinutes = StartTime.Minute.ToString(CultureInfo.CurrentCulture);
                        }
                        var vname = "SHADOW PLAN - " + StartTime.ToShortDateString() + "-" + StartTime.Hour + "." +
                                    niceMinutes;
                        view.Name = GetNiceViewName(doc, vname);
                        var sunSettings = view.SunAndShadowSettings;
                        sunSettings.StartDateAndTime = StartTime;
                        sunSettings.SunAndShadowType = SunAndShadowType.StillImage;
                        view.SunlightIntensity = 50;
                        log.AddSuccess("Shadow Plan created: " + vname);
                        t.Commit();
                        StartTime = StartTime.Add(ExportTimeInterval);
                    }
                }
            }
            return true;
        }

19 View Source File : BitstampApi.cs
License : MIT License
Project Creator : aabiryukov

private string Query(string operation, NameValueDictionary args = null)
        {
			if(args == null)
				args = new NameValueDictionary();

			lock (m_nonceLock)
			{
				var nonce = GetNonce();
				var signature = GetSignature(nonce);

				args.Add("key", m_key);
				args.Add("signature", signature);
				args.Add("nonce", nonce.ToString(CultureInfo.InvariantCulture));

				var path = new Uri("https://www.bitstamp.net/api/" + operation + "/");

				var httpContent = new FormUrlEncodedContent(args);
				var response = WebApi.Client.PostAsync(path, httpContent).Result;
				var resultString = response.Content.ReadreplacedtringAsync().Result;
				return resultString;
			}
        }

19 View Source File : StaduimSeatingTier.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

[SuppressMessage("ReSharper", "BitwiseOperatorOnEnumWithoutFlags", Justification = "Revit API...")]
        public void Draw()
        {
            using (var t = new Transaction(doc, "Create sight line view"))
            {
                t.Start();

                string times = DateTime.Now.Ticks.ToString(CultureInfo.CurrentCulture);

                view = CreateLineOfSightDraftingView(
                    "LOS-X" + distanceToFirstRowX + "-Y" + distanceToFirstRowY + "-T" +
                    TreadSize + "-MinN" + MinimumRiserHeight + "-Inc" + RiserIncrement +
                    "-Eye" + EyeHeight + "-MinC" + MinimumCValue + "_" + times);

                view.Scale = 50;
                int i;

                for (i = 0; i < NumberOfRows; i++)
                {
                    if (i == 0)
                    {
                        DrawLine(0, 0, distanceToFirstRowX, 0, "Thin Lines");
                        DrawText(
                            distanceToFirstRowX / 2,
                            0,
                            distanceToFirstRowX.ToString(CultureInfo.InvariantCulture),
                            TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_TOP);
                        DrawText(
                            distanceToFirstRowX,
                            distanceToFirstRowY / 2,
                            distanceToFirstRowY.ToString(CultureInfo.InvariantCulture),
                            TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_BOTTOM);
                    }

                    // Draw the sight line
                    DrawLine(0, 0, rows[i].EyeToFocusX, rows[i].HeightToFocus, "Dash - 0.1 pen");

                    // Draw the head
                    DrawCircle(rows[i].EyeToFocusX, rows[i].HeightToFocus, "Medium Lines");

                    // Draw the body
                    DrawLine(
                        rows[i].EyeToFocusX,
                        rows[i].HeightToFocus,
                        rows[i].EyeToFocusX,
                        rows[i].HeightToFocus - rows[i].EyeHeight,
                        "Thin Lines");

                    // Draw the riser
                    DrawRiser(i);

                    // Draw the going
                    DrawGoing(i);

                    // Draw the c-value text
                    DrawText(
                        rows[i].EyeToFocusX + 125,
                        rows[i].HeightToFocus,
                        "c:" + Math.Round(rows[i].CValue, 2).ToString(CultureInfo.InvariantCulture),
                        TextAlignFlags.TEF_ALIGN_LEFT);

                    //// Draw the going text (treadSize)
                    DrawText(
                        rows[i].EyeToFocusX - (rows[i].Going / 2),
                        rows[i].HeightToFocus - rows[i].EyeHeight,
                        "R" + (i + 1).ToString(CultureInfo.InvariantCulture) + " : " + TreadSize.ToString(CultureInfo.InvariantCulture),
                        TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_TOP);

                    //// Draw the riser text)
                    if (i > 0)
                    {
                        DrawText(
                            rows[i].EyeToFocusX - TreadSize,
                            rows[i].HeightToFocus - rows[i].EyeHeight - (rows[i].RiserHeight / 2),
                            rows[i].RiserHeight.ToString(CultureInfo.InvariantCulture),
                            TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_BOTTOM);
                    }
                }
                t.Commit();

                Autodesk.Revit.UI.UIDoreplacedent uidoc = new Autodesk.Revit.UI.UIDoreplacedent(doc);
                uidoc.ActiveView = view;
            }
        }

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

public bool CancelOrder(int orderId)
        {
	        var args = new NameValueCollection
	        {
		        {"symbol", "btc_usd"},
		        {"order_id", orderId.ToString(CultureInfo.InvariantCulture)}
	        };

	        var response = DoMethod2("cancel_order", args);
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");

	        return success;
        }

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

private DTWebApi.Issue ConvertToIssue(IssueMatch match)
        {
            // Validate the message
            if (string.IsNullOrWhiteSpace(match.Message))
            {
                _executionContext.Debug("Skipping logging an issue for the matched line because the message is empty.");
                return null;
            }

            // Validate the severity
            DTWebApi.IssueType issueType;
            if (string.IsNullOrEmpty(match.Severity) || string.Equals(match.Severity, "error", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Error;
            }
            else if (string.Equals(match.Severity, "warning", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Warning;
            }
            else if (string.Equals(match.Severity, "notice", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Notice;
            }
            else
            {
                _executionContext.Debug($"Skipped logging an issue for the matched line because the severity '{match.Severity}' is not supported.");
                return null;
            }

            var issue = new DTWebApi.Issue
            {
                Message = match.Message,
                Type = issueType,
            };

            // Line
            if (!string.IsNullOrEmpty(match.Line))
            {
                if (int.TryParse(match.Line, NumberStyles.None, CultureInfo.InvariantCulture, out var line))
                {
                    issue.Data["line"] = line.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    _executionContext.Debug($"Unable to parse line number '{match.Line}'");
                }
            }

            // Column
            if (!string.IsNullOrEmpty(match.Column))
            {
                if (int.TryParse(match.Column, NumberStyles.None, CultureInfo.InvariantCulture, out var column))
                {
                    issue.Data["col"] = column.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    _executionContext.Debug($"Unable to parse column number '{match.Column}'");
                }
            }

            // Code
            if (!string.IsNullOrWhiteSpace(match.Code))
            {
                issue.Data["code"] = match.Code.Trim();
            }

            // File
            try
            {
                if (!string.IsNullOrWhiteSpace(match.File))
                {
                    var file = match.File;
                    var translate = _container != null;

                    // Root using fromPath
                    if (!string.IsNullOrWhiteSpace(match.FromPath) && !Path.IsPathFullyQualified(file))
                    {
                        var fromDirectory = Path.GetDirectoryName(match.FromPath);
                        if (!string.IsNullOrWhiteSpace(fromDirectory))
                        {
                            file = Path.Combine(fromDirectory, file);
                        }
                    }

                    // Root using workspace
                    if (!Path.IsPathFullyQualified(file))
                    {
                        var workspace = _executionContext.GetGitHubContext("workspace");
                        ArgUtil.NotNullOrEmpty(workspace, "workspace");

                        file = Path.Combine(workspace, file);
                        translate = false;
                    }

                    // Remove relative pathing and normalize slashes
                    file = Path.GetFullPath(file);

                    // Translate to host
                    if (translate)
                    {
                        file = _container.TranslateToHostPath(file);
                        file = Path.GetFullPath(file);
                    }

                    // Check whether the file exists
                    if (File.Exists(file))
                    {
                        // Check whether the file is under the workflow repository
                        var repositoryPath = GetRepositoryPath(file);
                        if (!string.IsNullOrEmpty(repositoryPath))
                        {
                            // Get the relative file path
                            var relativePath = file.Substring(repositoryPath.Length).TrimStart(Path.DirectorySeparatorChar);

                            // Prefer `/` on all platforms
                            issue.Data["file"] = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                        }
                        else
                        {
                            _executionContext.Debug($"Dropping file value '{file}'. Path is not under the workflow repo.");
                        }
                    }
                    else
                    {
                        _executionContext.Debug($"Dropping file value '{file}'. Path does not exist");
                    }
                }
            }
            catch (Exception ex)
            {
                _executionContext.Debug($"Dropping file value '{match.File}' and fromPath value '{match.FromPath}'. Exception during validation: {ex.ToString()}");
            }

            return issue;
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private string GetMaxLayerSize(InputMode inputMode)
        {
            int width = 0;
            int height = 0;

            switch (inputMode)
            {
                case InputMode.NoInput:
                case InputMode.AllHiddenLayers:
                case InputMode.AllHiddenLayersDescending:
                    break;
                case InputMode.ActiveLayer:
                case InputMode.ActiveAndBelow:
                    // The last layer in the list is always the layer the user has selected in Paint.NET,
                    // so it will be treated as the active layer.
                    // The clipboard layer (if present) will be placed above the active layer.
                    GmicLayer activeLayer = layers[layers.Count - 1];

                    width = activeLayer.Width;
                    height = activeLayer.Height;
                    break;

                case InputMode.AllLayers:
                case InputMode.ActiveAndAbove:
                case InputMode.AllVisibleLayers:
                case InputMode.AllVisibleLayersDescending:
                    foreach (GmicLayer layer in layers)
                    {
                        width = Math.Max(width, layer.Width);
                        height = Math.Max(height, layer.Height);
                    }
                    break;
                default:
                    throw new InvalidOperationException("Unsupported InputMode: " + inputMode.ToString());
            }

            return width.ToString(CultureInfo.InvariantCulture) + "," + height.ToString(CultureInfo.InvariantCulture);
        }

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

[EditorBrowsable(EditorBrowsableState.Never)]
        public virtual async Task RefreshAgentAsync(
            int poolId,
            int agentId,
            object userState = null,
            CancellationToken cancellationToken = default)
        {
            HttpMethod httpMethod = new HttpMethod("POST");
            Guid locationId = new Guid("c3a054f6-7a8a-49c0-944e-3a8e5d7adfd7");
            object routeValues = new { poolId = poolId };

            List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
            queryParams.Add("agentId", agentId.ToString(CultureInfo.InvariantCulture));

            using (HttpResponseMessage response = await SendAsync(
                httpMethod,
                locationId,
                routeValues: routeValues,
                version: new ApiResourceVersion(5.1, 1),
                queryParameters: queryParams,
                userState: userState,
                cancellationToken: cancellationToken).ConfigureAwait(false))
            {
                return;
            }
        }

19 View Source File : SimpleSegment.cs
License : MIT License
Project Creator : Abdesol

public override string ToString()
		{
			return "[Offset=" + Offset.ToString(CultureInfo.InvariantCulture) + ", Length=" + Length.ToString(CultureInfo.InvariantCulture) + "]";
		}

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

public virtual Task<Timeline> GetTimelineAsync(
            Guid scopeIdentifier,
            string hubName,
            Guid planId,
            Guid timelineId,
            int? changeId = null,
            bool? includeRecords = null,
            object userState = null,
            CancellationToken cancellationToken = default)
        {
            HttpMethod httpMethod = new HttpMethod("GET");
            Guid locationId = new Guid("83597576-cc2c-453c-bea6-2882ae6a1653");
            object routeValues = new { scopeIdentifier = scopeIdentifier, hubName = hubName, planId = planId, timelineId = timelineId };

            List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
            if (changeId != null)
            {
                queryParams.Add("changeId", changeId.Value.ToString(CultureInfo.InvariantCulture));
            }
            if (includeRecords != null)
            {
                queryParams.Add("includeRecords", includeRecords.Value.ToString());
            }

            return SendAsync<Timeline>(
                httpMethod,
                locationId,
                routeValues: routeValues,
                version: new ApiResourceVersion(5.1, 1),
                queryParameters: queryParams,
                userState: userState,
                cancellationToken: cancellationToken);
        }

19 View Source File : BitstampApi.cs
License : MIT License
Project Creator : aabiryukov

public bool CancelOrder(int orderId)
        {
            var args = new NameValueDictionary
            {
                { "id", orderId.ToString(CultureInfo.InvariantCulture) }
            };
			var json = Query("cancel_order", args);
			var result = DeserializeBitstampObject<bool>(json);

	        return result;
        }

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

public async Task<ConnectionData> GetConnectionDataAsync(ConnectOptions connectOptions, Int64 lastChangeId, CancellationToken cancellationToken = default(CancellationToken), Object userState = null)
        {
            using (new OperationScope(LocationResourceIds.LocationServiceArea, "GetConnectionData"))
            {
                var uri = new Uri(PathUtility.Combine(BaseAddress.GetLeftPart(UriPartial.Path), connectSubUrl));
                var uriBuilder = new UriBuilder(uri) { Query = BaseAddress.Query };

                var query = new List<KeyValuePair<String, String>>
                {
                    new KeyValuePair<String, String>("connectOptions", ((Int32)connectOptions).ToString(CultureInfo.InvariantCulture)),
                    new KeyValuePair<String, String>("lastChangeId", ((Int32)lastChangeId).ToString(CultureInfo.InvariantCulture)),
                    new KeyValuePair<String, String>("lastChangeId64", lastChangeId.ToString(CultureInfo.InvariantCulture))
                };

                uri = uriBuilder.Uri.AppendQuery(query);

                var message = new HttpRequestMessage(HttpMethod.Get, uri.ToString());
                message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                return await SendAsync<ConnectionData>(message, userState, cancellationToken).ConfigureAwait(false);
            }
        }

19 View Source File : TextLocation.cs
License : MIT License
Project Creator : Abdesol

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (value is TextLocation && destinationType == typeof(string)) {
				var loc = (TextLocation)value;
				return loc.Line.ToString(culture) + ";" + loc.Column.ToString(culture);
			}
			return base.ConvertTo(context, culture, value, destinationType);
		}

19 View Source File : Repository.cs
License : Apache License 2.0
Project Creator : adamralph

public string ToString(int tagWidth, int versionWidth, int heightWidth) =>
                $"{{ {nameof(this.Commit)}: {this.Commit.ShortSha}, {nameof(this.Tag)}: {$"{(this.Tag == null ? "null" : $"'{this.Tag}'")},".PadRight(tagWidth + 3)} {nameof(this.Version)}: {$"{this.Version?.ToString() ?? "null"},".PadRight(versionWidth + 1)} {nameof(this.Height)}: {this.Height.ToString(CultureInfo.CurrentCulture).PadLeft(heightWidth)} }}";

19 View Source File : SequenceLevel.cs
License : MIT License
Project Creator : 0xC0000054

public static SequenceLevel FromPackedByte(byte seqProfileAndSeqLevelIdx0)
        {
            byte value = (byte)(seqProfileAndSeqLevelIdx0 & 0x1f);

            if (SequenceLevelMap.Instance.TryGetValue(value, out SequenceLevel level))
            {
                return level;
            }
            else
            {
                // From AV1 specification, https://aomediacodec.github.io/av1-spec/av1-spec.pdf:
                // "The level uses a X.Y format. X is equal to 2 + (seq_level_idx >> 2). Y is given by (seq_level_idx & 3)."
                int majorVersion = 2 + (value >> 2);
                int minorVersion = value & 3;

                string name = majorVersion.ToString(CultureInfo.InvariantCulture) + "." + minorVersion.ToString(CultureInfo.InvariantCulture);

                return new SequenceLevel(value, name);
            }
        }

19 View Source File : POComment.cs
License : MIT License
Project Creator : adams85

public override string ToString()
        {
            var filePath =
                !string.IsNullOrEmpty(FilePath) ?
                (FilePath.FindIndex(char.IsWhiteSpace) >= 0 ? "\"" + FilePath + "\"" : FilePath) :
                "(unknown)";

            return
                Line > 0 ?
                filePath + ":" + Line.ToString(CultureInfo.InvariantCulture) :
                filePath;
        }

19 View Source File : Rope.cs
License : MIT License
Project Creator : Abdesol

internal void VerifyRange(int startIndex, int length)
		{
			if (startIndex < 0 || startIndex > this.Length) {
				throw new ArgumentOutOfRangeException("startIndex", startIndex, "0 <= startIndex <= " + this.Length.ToString(CultureInfo.InvariantCulture));
			}
			if (length < 0 || startIndex + length > this.Length) {
				throw new ArgumentOutOfRangeException("length", length, "0 <= length, startIndex(" + startIndex + ")+length <= " + this.Length.ToString(CultureInfo.InvariantCulture));
			}
		}

19 View Source File : HuobiAPI.cs
License : MIT License
Project Creator : aabiryukov

public IEnumerable<Order> GetActiveOrders()
		{
			var args = new NameValueCollection
	        {
                {"coin_type", ((int)CoinType.Btc).ToString(CultureInfo.InvariantCulture)},
	        };

			var response = DoMethod2("get_orders", args);
		    var orders = JsonConvert.DeserializeObject<List<Order>>(response);

//			var jsonObject = CheckResult(response);
//			var orders = jsonObject["orders"].ToObject<List<Order>>();

			return orders;
		}

19 View Source File : ExprPlainWriter.cs
License : MIT License
Project Creator : 0x1000000

public void VisitPlainProperty(string name, int? value, int ctx)
        {
            this._buffer.Add(this._factory(ctx, ctx, null, false, name, value?.ToString(CultureInfo.InvariantCulture)));
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private unsafe string PrepareCroppedLayers(InputMode inputMode, RectangleF cropRect)
        {
            if (inputMode == InputMode.NoInput)
            {
                return string.Empty;
            }

            IReadOnlyList<GmicLayer> layers = GetRequestedLayers(inputMode);

            if (layers.Count == 0)
            {
                return string.Empty;
            }

            if (memoryMappedFiles.Capacity < layers.Count)
            {
                memoryMappedFiles.Capacity = layers.Count;
            }

            StringBuilder reply = new StringBuilder();

            foreach (GmicLayer layer in layers)
            {
                Surface surface = layer.Surface;
                bool disposeSurface = false;
                int destinationImageStride = surface.Stride;

                if (cropRect != WholeImageCropRect)
                {
                    int cropX = (int)Math.Floor(cropRect.X * layer.Width);
                    int cropY = (int)Math.Floor(cropRect.Y * layer.Height);
                    int cropWidth = (int)Math.Min(layer.Width - cropX, 1 + Math.Ceiling(cropRect.Width * layer.Width));
                    int cropHeight = (int)Math.Min(layer.Height - cropY, 1 + Math.Ceiling(cropRect.Height * layer.Height));

                    try
                    {
                        surface = layer.Surface.CreateWindow(cropX, cropY, cropWidth, cropHeight);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        throw new InvalidOperationException(string.Format("Surface.CreateWindow bounds invalid, cropRect={0}", cropRect.ToString()), ex);
                    }
                    disposeSurface = true;
                    destinationImageStride = cropWidth * ColorBgra.SizeOf;
                }

                string mapName = "pdn_" + Guid.NewGuid().ToString();

                try
                {
                    MemoryMappedFile file = MemoryMappedFile.CreateNew(mapName, surface.Scan0.Length);
                    memoryMappedFiles.Add(file);

                    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                    {
                        byte* destination = null;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref destination);

                            for (int y = 0; y < surface.Height; y++)
                            {
                                ColorBgra* src = surface.GetRowAddressUnchecked(y);
                                byte* dst = destination + (y * destinationImageStride);

                                Buffer.MemoryCopy(src, dst, destinationImageStride, destinationImageStride);
                            }
                        }
                        finally
                        {
                            if (destination != null)
                            {
                                accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                            }
                        }
                    }
                }
                finally
                {
                    if (disposeSurface)
                    {
                        surface.Dispose();
                    }
                }

                reply.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "{0},{1},{2},{3}\n",
                    mapName,
                    surface.Width.ToString(CultureInfo.InvariantCulture),
                    surface.Height.ToString(CultureInfo.InvariantCulture),
                    destinationImageStride.ToString(CultureInfo.InvariantCulture));
            }

            return reply.ToString();
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public static Dictionary<WexPair, List<TradeInfoV3>> GetTrades(WexPair[] pairlist, int limit = 150)
        {
            var limits = new Dictionary<string, string> { { "limit", limit.ToString(CultureInfo.InvariantCulture) } };

            Func<JContainer, List<TradeInfoV3>> tradeInfoListReader = (x => x.OfType<JObject>().Select(TradeInfoV3.ReadFromJObject).ToList());
			return MakeRequest("trades", pairlist, tradeInfoListReader, limits);
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public CancelOrderAnswer CancelOrder(int orderId)
        {
			var args = new NameValueDictionary
            {
                { "order_id", orderId.ToString(CultureInfo.InvariantCulture) }
            };
            var result = JObject.Parse(Query("CancelOrder", args));

            if (result.Value<int>("success") == 0)
				throw new WexApiException(result.Value<string>("error"));

            return CancelOrderAnswer.ReadFromJObject(result["return"] as JObject);
        }

19 View Source File : SCexportViewModel.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public void KeyPressed(KeyEventArgs keyArgs)
        {
            //// only execute search if in the search text box
            if (keyArgs.OriginalSource.GetType() == typeof(System.Windows.Controls.TextBox))
            {
                if (keyArgs.Key == Key.Enter)
                {
                    ExecuteSearch();
                    NotifyOfPropertyChange(() => Sheets);
                }
                return;
            }

            switch (keyArgs.Key)
            {
                case Key.C:
                    RemoveViewFilter();
                    break;

                case Key.D:
                    exportManager.ToggleExportOption(ExportOptions.DWG);
                    NotifyOfPropertyChange(() => StatusText);
                    break;

                case Key.N:
#if REVIT2022
                    exportManager.ToggleExportOption(ExportOptions.DirectPDF);
                    NotifyOfPropertyChange(() => StatusText);
#endif
                    break;

                case Key.L:
                    ShowLatestRevision();
                    break;

                case Key.O:
                    OpenViewsCommand();
                    break;

                case Key.P:
                    exportManager.ToggleExportOption(ExportOptions.PDF);
                    NotifyOfPropertyChange(() => StatusText);
                    break;

                case Key.S:
                    var activeSheetNumber = Manager.CurrentViewNumber(exportManager.Doc);
                    if (activeSheetNumber == null)
                    {
                        return;
                    }
                    ExportSheet ss = sheets.Where(item => item.SheetNumber.Equals(activeSheetNumber, StringComparison.CurrentCulture)).First();
                    SelectedSheet = ss;
                    NotifyOfPropertyChange(() => SelectedSheet);
                    break;

                case Key.Q:
                    OpenViewSet();
                    break;

                case Key.V:
                    VerifySheets();
                    break;

                case Key.W:
                    SaveViewSet();
                    break;

                case Key.Escape:
                    TryClose();
                    break;

                default:
                    if (keyArgs.Key >= Key.D0 && keyArgs.Key <= Key.D9)
                    {
                        int index = (int)keyArgs.Key - (int)Key.D0;
                        if (keyArgs.KeyboardDevice.IsKeyDown(Key.LeftShift) || keyArgs.KeyboardDevice.IsKeyDown(Key.RightShift))
                        {
                            if (index < recentExportSets.Count)
                            {
                                SelectPrevious(recentExportSets[index]);
                            }
                        }
                        else
                        {
                            FilterByNumber(index.ToString(System.Globalization.CultureInfo.CurrentCulture));
                        }
                    }
                    break;
            }
        }

See More Examples