示例#1
0
        public override bool Execute()
        {
            var packageArtifacts = Artifacts.Select(ArtifactInfo.Parse)
                                   .OfType <ArtifactInfo.Package>()
                                   .Where(p => !p.IsSymbolsArtifact)
                                   .ToDictionary(p => p.PackageInfo.Id, p => p, StringComparer.OrdinalIgnoreCase);

            var factory = new SolutionInfoFactory(Log, BuildEngine5);
            var props   = MSBuildListSplitter.GetNamedProperties(Properties);

            if (!props.TryGetValue("Configuration", out var defaultConfig))
            {
                defaultConfig = "Debug";
            }

            var solutions = factory.Create(Solutions, props, defaultConfig, _cts.Token).OrderBy(f => f.Directory).ToList();

            Log.LogMessage($"Found {solutions.Count} and {solutions.Sum(p => p.Projects.Count)} projects");

            if (_cts.IsCancellationRequested)
            {
                return(false);
            }

            var repoGraph           = new AdjacencyMatrix(solutions.Count);
            var packageToProjectMap = new Dictionary <PackageIdentity, ProjectInfo>();

            for (var i = 0; i < solutions.Count; i++)
            {
                var sln = repoGraph[i] = solutions[i];

                foreach (var proj in sln.Projects)
                {
                    if (!proj.IsPackable ||
                        proj.FullPath.Contains("samples") ||
                        proj.FullPath.Contains("tools/Microsoft.VisualStudio.Web.CodeGeneration.Design"))
                    {
                        continue;
                    }

                    var id = new PackageIdentity(proj.PackageId, new NuGetVersion(proj.PackageVersion));

                    if (packageToProjectMap.TryGetValue(id, out var otherProj))
                    {
                        Log.LogError($"Both {proj.FullPath} and {otherProj.FullPath} produce {id}");
                        continue;
                    }

                    packageToProjectMap.Add(id, proj);
                }

                var sharedSrc = Path.Combine(sln.Directory, "shared");
                if (Directory.Exists(sharedSrc))
                {
                    foreach (var dir in Directory.GetDirectories(sharedSrc, "*.Sources"))
                    {
                        var id            = GetDirectoryName(dir);
                        var artifactInfo  = packageArtifacts[id];
                        var sharedSrcProj = new ProjectInfo(dir,
                                                            Array.Empty <ProjectFrameworkInfo>(),
                                                            Array.Empty <DotNetCliReferenceInfo>(),
                                                            true,
                                                            artifactInfo.PackageInfo.Id,
                                                            artifactInfo.PackageInfo.Version.ToNormalizedString());
                        sharedSrcProj.SolutionInfo = sln;
                        var identity = new PackageIdentity(artifactInfo.PackageInfo.Id, artifactInfo.PackageInfo.Version);
                        packageToProjectMap.Add(identity, sharedSrcProj);
                    }
                }
            }

            if (Log.HasLoggedErrors)
            {
                return(false);
            }

            for (var i = 0; i < solutions.Count; i++)
            {
                var src = repoGraph[i];

                foreach (var proj in src.Projects)
                {
                    if (!proj.IsPackable ||
                        proj.FullPath.Contains("samples"))
                    {
                        continue;
                    }

                    foreach (var dep in proj.Frameworks.SelectMany(f => f.Dependencies.Values))
                    {
                        if (packageToProjectMap.TryGetValue(new PackageIdentity(dep.Id, new NuGetVersion(dep.Version)), out var target))
                        {
                            var j = repoGraph.FindIndex(target.SolutionInfo);
                            repoGraph.SetLink(i, j);
                        }
                    }

                    foreach (var toolDep in proj.Tools)
                    {
                        if (packageToProjectMap.TryGetValue(new PackageIdentity(toolDep.Id, new NuGetVersion(toolDep.Version)), out var target))
                        {
                            var j = repoGraph.FindIndex(target.SolutionInfo);
                            repoGraph.SetLink(i, j);
                        }
                    }
                }
            }

            var repos = Repositories.ToDictionary(i => i.ItemSpec, i => i, StringComparer.OrdinalIgnoreCase);

            for (var i = 0; i < repoGraph.Count; i++)
            {
                var src      = repoGraph[i];
                var repoName = GetDirectoryName(src.Directory);
                var repo     = repos[repoName];

                var policy = Enum.Parse <PatchPolicy>(repo.GetMetadata("PatchPolicy"));

                if ((policy & PatchPolicy.AlwaysUpdate) != 0 && !src.IsPatching)
                {
                    Log.LogError($"{repoName} is not currently set to patch, but it should because the policy is set to always include this in servicing updates. Update the configuration in submodule.props.");
                    continue;
                }

                var srcShouldCascade = (policy & PatchPolicy.CascadeVersions) != 0;
                for (var j = 0; j < repoGraph.Count; j++)
                {
                    if (j == i)
                    {
                        continue;
                    }
                    if (repoGraph.HasLink(i, j))
                    {
                        var target         = repoGraph[j];
                        var targetRepoName = GetDirectoryName(target.Directory);
                        var targetRepo     = repos[targetRepoName];

                        if (srcShouldCascade && !src.IsPatching && target.IsPatching)
                        {
                            Log.LogError($"{repoName} should be patching because it depend on {targetRepoName} and its patch policy is to cascade version changes. Update the configuration in submodule.props.");
                        }
                    }
                }
            }

            return(!Log.HasLoggedErrors);
        }
示例#2
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (Class != null)
         {
             hashCode = hashCode * 59 + Class.GetHashCode();
         }
         if (Artifacts != null)
         {
             hashCode = hashCode * 59 + Artifacts.GetHashCode();
         }
         if (DurationInMillis != null)
         {
             hashCode = hashCode * 59 + DurationInMillis.GetHashCode();
         }
         if (EstimatedDurationInMillis != null)
         {
             hashCode = hashCode * 59 + EstimatedDurationInMillis.GetHashCode();
         }
         if (EnQueueTime != null)
         {
             hashCode = hashCode * 59 + EnQueueTime.GetHashCode();
         }
         if (EndTime != null)
         {
             hashCode = hashCode * 59 + EndTime.GetHashCode();
         }
         if (Id != null)
         {
             hashCode = hashCode * 59 + Id.GetHashCode();
         }
         if (Organization != null)
         {
             hashCode = hashCode * 59 + Organization.GetHashCode();
         }
         if (Pipeline != null)
         {
             hashCode = hashCode * 59 + Pipeline.GetHashCode();
         }
         if (Result != null)
         {
             hashCode = hashCode * 59 + Result.GetHashCode();
         }
         if (RunSummary != null)
         {
             hashCode = hashCode * 59 + RunSummary.GetHashCode();
         }
         if (StartTime != null)
         {
             hashCode = hashCode * 59 + StartTime.GetHashCode();
         }
         if (State != null)
         {
             hashCode = hashCode * 59 + State.GetHashCode();
         }
         if (Type != null)
         {
             hashCode = hashCode * 59 + Type.GetHashCode();
         }
         if (CommitId != null)
         {
             hashCode = hashCode * 59 + CommitId.GetHashCode();
         }
         return(hashCode);
     }
 }
        public GetAppInstallFilesBlobDialogViewModel()
        {
            // Show/Hide Blob
            ShowHideBlobSectionCommand.Subscribe(_ =>
            {
                ShowHideBlobSectionButtonLabel.Value = ShowBlobSectionVisibility.Value == Visibility.Collapsed
                    ? ExpandButtonLabel
                    : CollapseButtonLabel;
                ShowBlobSectionVisibility.Value = ShowBlobSectionVisibility.Value == Visibility.Collapsed
                    ? Visibility.Visible
                    : Visibility.Collapsed;
            })
            .AddTo(disposable);

            // Storage Credential Input
            StorageConnectionInput = new ReactiveProperty <string>(blobConnectionUseCase.Read <string>("blob_connection_string"));
            StorageConnectionInput.Subscribe(x => blobConnectionUseCase.Save("blob_connection_string", x)).AddTo(disposable);
            StorageContainerInput = new ReactiveProperty <string>(blobConnectionUseCase.Read <string>("container"));
            StorageContainerInput.Subscribe(x => blobConnectionUseCase.Save("container", x)).AddTo(disposable);

            // Copy Button
            CopyButtonContent  = new ReactiveProperty <string>("Copy SasUrl");
            CopyButtonEnabled  = ArtifactUrl.Select(x => !string.IsNullOrWhiteSpace(x)).ToReactiveProperty();
            OnClickCopyCommand = CopyButtonEnabled.ToReactiveCommand();
            OnClickCopyCommand
            .Do(_ => blobSasUrlUseCase.CopySasUrl(ArtifactUrl.Value, StorageConnectionInput.Value, StorageContainerInput.Value, SelectedArtifact.Value.Name))
            .SelectMany(x => TemporaryDisableCopyButtonAsObservable(TimeSpan.FromMilliseconds(500), "Copy SasUrl"))
            .Subscribe()
            .AddTo(disposable);

            // Download Button
            blobArtifactUsecase.DownloadStatus.Subscribe(x => DownloadStatus.Value = x).AddTo(disposable);
            OnClickDownloadCommand = CopyButtonEnabled.ToAsyncReactiveCommand();
            OnClickDownloadCommand
            .Subscribe(async _ => await blobArtifactUsecase.DownloadHoloLensPackagesAsync(StorageConnectionInput.Value, StorageContainerInput.Value, SelectedArtifact.Value.Name, SelectedArtifact.Value.Size, SelectedArtifact.Value.FileName))
            .AddTo(disposable);

            // OpenFolder Button
            OnClickOpenDownloadFolderCommand.Subscribe(_ => blobArtifactUsecase.OpenFolderAsync()).AddTo(disposable);
            OnClickOpenDownloadBlobFolderCommand.Subscribe(_ => blobArtifactUsecase.OpenDownloadFolderAsync()).AddTo(disposable);

            // Initialize by obtain artifact informations
            blobArtifactUsecase.Artifacts
            .Where(x => x != null)
            .Do(x =>
            {
                Projects.Add(x);
                BlobResult.Value = $"Found {Projects.Count} projects.";
            })
            .Subscribe()
            .AddTo(disposable);
            blobArtifactUsecase.RequestFailedMessage
            .Do(x => BlobResult.Value = x)
            .Subscribe()
            .AddTo(disposable);

            // Blob Download
            ComboBoxEnabled         = Projects.CollectionChangedAsObservable().Any().ToReactiveProperty();
            IsEnableCheckBlobButton = StorageConnectionInput
                                      .CombineLatest(StorageContainerInput, (r, l) => !string.IsNullOrWhiteSpace(r) && !string.IsNullOrWhiteSpace(l))
                                      .ToReadOnlyReactiveProperty();
            OnClickCheckBlobCommand = IsEnableCheckBlobButton.ToAsyncReactiveCommand();
            OnClickCheckBlobCommand.Subscribe(async _ =>
            {
                var task             = blobArtifactUsecase.RequestHoloLensPackagesAsync(StorageConnectionInput.Value, StorageContainerInput.Value);
                IsBlobChecking.Value = true;
                Projects.Clear();
                Branches?.Clear();
                Artifacts?.Clear();
                BlobResult.Value = "Trying obtain project infomations.";
                await task;
                IsBlobChecking.Value = false;
            })
            .AddTo(disposable);
            OnClickCancelBlobCommand = IsBlobChecking.Select(x => x).ToReactiveCommand();
            OnClickCancelBlobCommand
            .Do(_ => Projects.Clear())
            .Subscribe(_ => blobArtifactUsecase.CancelRequest())
            .AddTo(disposable);

            // Update Collection with Clear existing collection when selected.
            Branches = SelectedProject.Where(x => x != null)
                       .Do(_ => Branches?.Clear())
                       .Do(_ => Artifacts?.Clear())
                       .SelectMany(x => blobArtifactUsecase.GetArtifactCache(x.Project))
                       .ToReactiveCollection();
            Artifacts = SelectedBranch.Where(x => x != null)
                        .Do(x => Artifacts?.Clear())
                        .SelectMany(x => blobArtifactUsecase.GetArtifactCache(SelectedProject.Value?.Project, x.Branch))
                        .ToReactiveCollection();
            SelectedArtifact
            .Where(x => x != null)
            .Do(x =>
            {
                ArtifactName.Value    = x.Name;
                ArtifactCaption.Value = $"(Size: {x.Size}, MD5: {x.MD5}, LeaseState: {x.LeaseState})";
                ArtifactUrl.Value     = x.Uri.AbsoluteUri;
            })
            .ToReactiveProperty();
        }
示例#4
0
        protected void AddVersionInformation(TextWriter writer, AbstractWrapper wrapper)
        {
            AddSectionHeader(writer, "Version Information");

            var docs35           = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("net35"), wrapper);
            var docs45           = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("net45"), wrapper);
            var docsCore13       = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("netstandard1.3"), wrapper);
            var docsCore20       = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("netstandard2.0"), wrapper);
            var docsNetCoreApp31 = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("netcoreapp3.1"), wrapper);

            // If there is no documentation then assume it is available for all platforms.
            var boolNoDocs = docs35 == null && docs45 == null &&
                             docsCore13 == null && docsCore20 == null &&
                             docsNetCoreApp31 == null;

            // .NET Core App
            var netCoreAppVersions = new List <string>();

            if (boolNoDocs || (wrapper != null && docsNetCoreApp31 != null))
            {
                netCoreAppVersions.Add("3.1");
            }

            if (netCoreAppVersions.Count > 0)
            {
                writer.WriteLine("<p><strong>.NET Core App: </strong><br/>Supported in: {0}<br/>", string.Join(", ", netCoreAppVersions));
            }

            // .NET Standard
            var netstandardVersions = new List <string>();

            if (boolNoDocs || (wrapper != null && docsCore20 != null))
            {
                netstandardVersions.Add("2.0");
            }
            if (boolNoDocs || (wrapper != null && docsCore13 != null))
            {
                netstandardVersions.Add("1.3");
            }


            if (netstandardVersions.Count > 0)
            {
                writer.WriteLine("<p><strong>.NET Standard: </strong><br/>Supported in: {0}<br/>", string.Join(", ", netstandardVersions));
            }


            // .NET Framework
            var netframeworkVersions = new List <string>();

            if (boolNoDocs || (wrapper != null && docs45 != null))
            {
                netframeworkVersions.Add("4.5");
            }
            if (boolNoDocs || (wrapper != null && docs35 != null))
            {
                netframeworkVersions.Add("4.0");
                netframeworkVersions.Add("3.5");
            }

            if (netframeworkVersions.Count > 0)
            {
                writer.WriteLine("<p><strong>.NET Framework: </strong><br/>Supported in: {0}<br/>", string.Join(", ", netframeworkVersions));
            }

            AddSectionClosing(writer);
        }
示例#5
0
        /// <summary>
        /// Returns true if PipelineRun instances are equal
        /// </summary>
        /// <param name="other">Instance of PipelineRun to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(PipelineRun other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Class == other.Class ||
                     Class != null &&
                     Class.Equals(other.Class)
                     ) &&
                 (
                     Artifacts == other.Artifacts ||
                     Artifacts != null &&
                     Artifacts.SequenceEqual(other.Artifacts)
                 ) &&
                 (
                     DurationInMillis == other.DurationInMillis ||
                     DurationInMillis != null &&
                     DurationInMillis.Equals(other.DurationInMillis)
                 ) &&
                 (
                     EstimatedDurationInMillis == other.EstimatedDurationInMillis ||
                     EstimatedDurationInMillis != null &&
                     EstimatedDurationInMillis.Equals(other.EstimatedDurationInMillis)
                 ) &&
                 (
                     EnQueueTime == other.EnQueueTime ||
                     EnQueueTime != null &&
                     EnQueueTime.Equals(other.EnQueueTime)
                 ) &&
                 (
                     EndTime == other.EndTime ||
                     EndTime != null &&
                     EndTime.Equals(other.EndTime)
                 ) &&
                 (
                     Id == other.Id ||
                     Id != null &&
                     Id.Equals(other.Id)
                 ) &&
                 (
                     Organization == other.Organization ||
                     Organization != null &&
                     Organization.Equals(other.Organization)
                 ) &&
                 (
                     Pipeline == other.Pipeline ||
                     Pipeline != null &&
                     Pipeline.Equals(other.Pipeline)
                 ) &&
                 (
                     Result == other.Result ||
                     Result != null &&
                     Result.Equals(other.Result)
                 ) &&
                 (
                     RunSummary == other.RunSummary ||
                     RunSummary != null &&
                     RunSummary.Equals(other.RunSummary)
                 ) &&
                 (
                     StartTime == other.StartTime ||
                     StartTime != null &&
                     StartTime.Equals(other.StartTime)
                 ) &&
                 (
                     State == other.State ||
                     State != null &&
                     State.Equals(other.State)
                 ) &&
                 (
                     Type == other.Type ||
                     Type != null &&
                     Type.Equals(other.Type)
                 ) &&
                 (
                     CommitId == other.CommitId ||
                     CommitId != null &&
                     CommitId.Equals(other.CommitId)
                 ));
        }
示例#6
0
        public void Load(RefreshType refreshType, HashSet <Severity> severities)
        {
            DataService dataService = DataService.Instance;

            RaisePropertyChanged("SelectedKey");
            try
            {
                String solutionDir = GetSolutionDir();
                if (String.IsNullOrWhiteSpace(solutionDir))
                {
                    return;
                }

                XrayVersion xrayVersion = HttpUtils.GetVersion();
                if (!XrayUtil.IsXrayVersionCompatible(xrayVersion.xray_version))
                {
                    String errorMessage = "ERROR: Unsupported Xray version: " + xrayVersion.xray_version + ", version "
                                          + XrayUtil.MIN_XRAY_VERSION + " or above required.";
                    OutputLog.ShowMessage(errorMessage);
                    return;
                }
                // Steps to run:
                // Trigger CLI to collect json info to a file
                // Read the info
                // Send dependencies to Xray
                // Get response and build the dependencies tree

                // Running CLI - this is the returned output.
                String returnedText = Util.GetCLIOutput(solutionDir);
                // Load projects from output
                Projects projects = Util.LosdNugetProjects(returnedText);

                if (projects.projects == null || projects.projects.Length == 0)
                {
                    OutputLog.ShowMessage("No projects were found.");
                    return;
                }
                List <Components> components = new List <Components>();
                Artifacts         artifacts  = null;
                switch (refreshType)
                {
                case RefreshType.Hard:
                {
                    // Get information for all dependencies. Ignore the cache
                    artifacts = dataService.RefreshArtifacts(true, projects);
                    break;
                }

                case RefreshType.Soft:
                {
                    // Get information only for the delta. Means only new dependencies will be added.
                    artifacts = dataService.RefreshArtifacts(false, projects);
                    break;
                }
                }
                dataService.Severities = severities;
                dataService.populateRootElements(projects);

                this.Artifacts = new ObservableCollection <ArtifactViewModel>();

                foreach (string key in dataService.RootElements)
                {
                    Artifacts.Add(new ArtifactViewModel(key));
                }
            }
            catch (IOException ioe)
            {
                dataService.ClearAllComponents();
                OutputLog.ShowMessage(ioe.Message);
                OutputLog.ShowMessage(ioe.StackTrace);
            }
            catch (HttpRequestException he)
            {
                dataService.ClearAllComponents();
                OutputLog.ShowMessage(he.Message);
                OutputLog.ShowMessage(he.StackTrace);
            }
        }
示例#7
0
 public MethodWriter(GenerationManifest artifacts, FrameworkVersion version, MethodInfoWrapper methodInfo)
     : base(artifacts, version, methodInfo)
 {
     this._methodInfo = methodInfo;
     // true when this is an Async method and the unity version is present
     this._unityVersionOfAsyncExists = NDocUtilities.FindDocumentationUnityAsync(Artifacts.NDocForPlatform("unity"), methodInfo) != null;
     // refer to asynchronous versions if the synchronous version doesn't exist but the async version does
     this._referAsyncAlternativeUnity = (NDocUtilities.FindDocumentationUnityAsyncAlternative(Artifacts.NDocForPlatform("unity"), methodInfo) != null) &&
                                        (Artifacts.NDocForPlatform("unity") != null) &&
                                        (NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("unity"), methodInfo) == null);
     this._referAsyncAlternativePCL = (NDocUtilities.FindDocumentationPCLAsyncAlternative(Artifacts.NDocForPlatform("pcl"), methodInfo) != null) &&
                                      (Artifacts.NDocForPlatform("pcl") != null) &&
                                      (NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("pcl"), methodInfo) == null);
 }
示例#8
0
        public override void Write(CustomFileWriter writer)
        {
            using (writer.WriteBlock("image:"))
            {
                Images.ForEach(x => writer.WriteLine($"- {x.GetValue()}"));
                writer.WriteLine();
            }

            if (Services.Length > 0)
            {
                using (writer.WriteBlock("services:"))
                {
                    Services.ForEach(x => writer.WriteLine($"- {x.GetValue().ToLowerInvariant()}"));
                    writer.WriteLine();
                }
            }

            if (Branches != null)
            {
                using (writer.WriteBlock("branches:"))
                {
                    Branches.Write(writer);
                    writer.WriteLine();
                }
            }

            if (SkipTags ||
                SkipBranchesWithPullRequest ||
                OnlyCommitsMessage != null ||
                OnlyCommitsAuthor != null ||
                SkipCommitsMessage != null ||
                SkipCommitsAuthor != null)
            {
                if (SkipTags)
                {
                    writer.WriteLine("skip_tags: true");
                }
                if (SkipBranchesWithPullRequest)
                {
                    writer.WriteLine("skip_branch_with_pr: true");
                }

                if (OnlyCommitsMessage != null || OnlyCommitsAuthor != null)
                {
                    using (writer.WriteBlock("only_commits:"))
                    {
                        if (OnlyCommitsMessage != null)
                        {
                            writer.WriteLine($"message: {OnlyCommitsMessage}");
                        }
                        if (OnlyCommitsAuthor != null)
                        {
                            writer.WriteLine($"author: {OnlyCommitsAuthor}");
                        }
                    }
                }

                if (SkipCommitsMessage != null || SkipCommitsAuthor != null)
                {
                    using (writer.WriteBlock("skip_commits:"))
                    {
                        if (SkipCommitsMessage != null)
                        {
                            writer.WriteLine($"message: {SkipCommitsMessage}");
                        }
                        if (SkipCommitsAuthor != null)
                        {
                            writer.WriteLine($"author: {SkipCommitsAuthor}");
                        }
                    }
                }

                writer.WriteLine();
            }

            if (Init.Length > 0)
            {
                using (writer.WriteBlock("init:"))
                {
                    Init.ForEach(x => writer.WriteLine($"- {x}"));
                    writer.WriteLine();
                }
            }

            using (writer.WriteBlock("build_script:"))
            {
                writer.WriteLine($@"- cmd: .\{BuildCmdPath} {InvokedTargets.JoinSpace()}");
                writer.WriteLine($@"- sh: ./{BuildCmdPath} {InvokedTargets.JoinSpace()}");
                writer.WriteLine();
            }

            if (Cache.Length > 0)
            {
                using (writer.WriteBlock("cache:"))
                {
                    Cache.ForEach(x => writer.WriteLine($"- {x}"));
                }
            }

            if (Artifacts.Length > 0)
            {
                using (writer.WriteBlock("artifacts:"))
                {
                    Artifacts.ForEach(x => writer.WriteLine($"- path: {x}"));
                }
            }
        }
示例#9
0
        public static IEnumerable <object[]> GetTestArgumentProcessingTestCases()
        {
            // Current method return 'test case' information that contains two arguments for TestArgumentProcessing method:
            // literal to parse and factory method that will return an argument.
            // This factory can't return Argument instance because to create an instance FrontEndContextCore is required.
            // But front end context is test-specific and belong to the current instance.

            //
            // Scalar + primitive value test cases
            //
            yield return(TestCase(
                             @"export const x = {name: ""foo"", value: 42};",
                             (context) => Cmd.Option("foo", 42)));

            yield return(TestCase(
                             @"export const x = {name: ""foo"", value: ""42""};",
                             (context) => Cmd.Option("foo", "42")));

            yield return(TestCase(
                             @"export const x = {name: undefined, value: ""42""};",
                             (context) => Cmd.Option(null, "42")));

            yield return(TestCase(
                             @"export const x = {value: ""42""};",
                             (context) => Cmd.Argument("42")));

            //
            // Scalar + FileArtifact test cases
            //
            yield return(TestCase(
                             WrapWithArtifactKind(String.Format(@"export const x = {{name: ""scalar1"", value: {{kind: ArtifactKind.output, path: p`{0}foo.cs`}}}};", m_testAbsolutePath)),
                             (context) => Cmd.Option("scalar1", Artifacts.Output(CreateAbsolutePath(context, String.Format("{0}foo.cs", m_testAbsolutePath))))));

            yield return(TestCase(
                             WrapWithArtifactKind(String.Format(@"export const x = {{name: ""scalar2"", value: {{kind: ArtifactKind.input, path: p`{0}foo`}}}};", m_testAbsolutePath)),
                             (context) => Cmd.Option("scalar2", Artifacts.Input(CreateAbsolutePath(context, String.Format("{0}foo", m_testAbsolutePath))))));

            //
            // PrimitiveArgument test cases
            //
            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: ""prim1"", value: {kind: ArgumentKind.rawText, value: ""text""}};"),
                             (context) => Cmd.RawText("prim1", "text")));

            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: ""prim2"", value: {kind: ArgumentKind.regular, value: 42}};"),
                             (context) => Cmd.RegularOption("prim2", 42)));

            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: undefined, value: {kind: ArgumentKind.startUsingResponseFile, value: undefined}};"),
                             (context) => Cmd.StartUsingResponseFile()));

            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: ""@"", value: {kind: ArgumentKind.startUsingResponseFile, value: ""true""}};"),
                             (context) => Cmd.StartUsingResponseFile("@", true)));

            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: ""prim4"", value: {kind: ArgumentKind.flag, value: undefined}};"),
                             (context) => Cmd.Flag("prim4")));

            //
            // ScalarArgument[] test cases
            //
            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: ""array1"", value: [42, ""42"", {kind: ArgumentKind.regular, value: 42}]};"),
                             (context) => Cmd.Options(
                                 "array1",
                                 ArgumentValue.FromNumber(42),
                                 ArgumentValue.FromString("42"),
                                 ArgumentValue.FromPrimitive(ArgumentKind.Regular, new PrimitiveValue(42)))));

            yield return(TestCase(
                             WrapWithArtifactKind(String.Format(@"export const x = {{name: ""array2"", value: [{{kind: ArtifactKind.output, path: p`{0}foo.cs`}}]}};", m_testAbsolutePath)),
                             (context) => Cmd.Options(
                                 "array2",
                                 Artifacts.Output(CreateAbsolutePath(context, String.Format("{0}foo.cs", m_testAbsolutePath))))));

            //
            // ListArgument test cases
            //

            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: ""list2"", value: {separator: "","", values: []}};"),
                             (context) => Cmd.Option("list2", Cmd.Join(",", new ArgumentValue[0]))));

            yield return(TestCase(
                             WrapWithArgumentKind(@"export const x = {name: ""list3"", value: {separator: "","", values: [1, 2, ""42""]}};"),
                             (context) => Cmd.Option(
                                 "list3",
                                 Cmd.Join(
                                     ",",
                                     new[]
            {
                ArgumentValue.FromNumber(1),
                ArgumentValue.FromNumber(2),
                ArgumentValue.FromString("42")
            }))));

            yield return(TestCase(
                             WrapWithArtifactKindAndArgumentKind(
                                 String.Format(@"export const x = {{name: ""list4"", value: {{separator: "","", values: [1, {{kind: ArtifactKind.output, path: p`{0}foo.cs`}}]}}}};", m_testAbsolutePath)),
                             (context) => Cmd.Option(
                                 "list4",
                                 Cmd.Join(
                                     ",",
                                     new[]
            {
                ArgumentValue.FromNumber(1),
                ArgumentValue.FromAbsolutePath(ArtifactKind.Output, CreateAbsolutePath(context, String.Format("{0}foo.cs", m_testAbsolutePath)))
            }))));
        }
 public override void Compute()
 {
     Workspace.Store("Artifacts", Artifacts.ImportDirectory(_config.Directory.Absolute, _config.Filter));
 }
示例#11
0
        public static IEnumerable <object[]> GetTestApiArgumentTestCases()
        {
            //
            // Cmd.flag + Cmd.sign
            //
            yield return(TestCase(
                             @"export const x = Cmd.flag(""/nologo"", true);",
                             (context) => Cmd.Flag("/nologo")));

            yield return(TestCase(
                             @"export const x = Cmd.option(""/timeout"", 42);",
                             (context) => Cmd.Option("/timeout", 42)));

            yield return(TestCase(
                             @"export const x = Cmd.sign(""/unsafe"", true);",
                             (context) => Cmd.Option("/unsafe", "+")));

            yield return(TestCase(
                             @"export const x = Cmd.sign(""/unsafe"", false);",
                             (context) => Cmd.Option("/unsafe", "-")));

            yield return(TestCase(
                             @"export const x = Cmd.sign(""/unsafe"", undefined);",
                             (context) => Cmd.Undefined()));

            yield return(TestCase(
                             @"export const x = Cmd.sign(""/enableNoPlus"", true, true);",
                             (context) => Cmd.Flag("/enableNoPlus")));

            yield return(TestCase(
                             @"export const x = Cmd.sign(""/enableNoPlus"", false, true);",
                             (context) => Cmd.Option("/enableNoPlus", "-")));

            //
            // Cmd.option with files
            //
            yield return(TestCase(
                             String.Format(@"export const x = Cmd.option(""/out"", Artifact.output(p`{0}foo.txt`));", m_testAbsolutePath),
                             (context) => Cmd.Option("/out", Artifacts.Output(CreateAbsolutePath(context, String.Format("{0}foo.txt", m_testAbsolutePath))))));

            yield return(TestCase(
                             String.Format(@"export const x = Cmd.option(""/input"", Artifact.input(p`{0}foo.txt`));", m_testAbsolutePath),
                             (context) => Cmd.Option("/input", Artifacts.Input(CreateAbsolutePath(context, String.Format("{0}foo.txt", m_testAbsolutePath))))));

            yield return(TestCase(
                             String.Format(@"export const x = Cmd.option(""/outFolder"", Artifact.output(p`{0}foo`));", m_testAbsolutePath),
                             (context) => Cmd.Option("/outFolder", Artifacts.Output(CreateAbsolutePath(context, String.Format("{0}foo", m_testAbsolutePath))))));

            yield return(TestCase(
                             String.Format(@"export const x = Cmd.option(""/rewrite"", Artifact.rewritten(f`{0}foo.txt`, p`{0}boo.txt`));", m_testAbsolutePath),
                             (context) =>
                             Cmd.Option("/rewrite", Artifacts.Rewritten(
                                            CreateFile(context, String.Format("{0}foo.txt", m_testAbsolutePath)),
                                            CreateAbsolutePath(context, String.Format("{0}boo.txt", m_testAbsolutePath))))));

            yield return(TestCase(
                             String.Format(@"export const x = Cmd.option(""/rewrite"", Artifact.rewritten(f`{0}foo.txt`));", m_testAbsolutePath),
                             (context) =>
                             Cmd.Option("/rewrite", Artifacts.InPlaceRewritten(CreateFile(context, String.Format("{0}foo.txt", m_testAbsolutePath))))));

            //
            // Cmd.options
            //
            yield return(TestCase(
                             String.Format(@"export const x = Cmd.options(""/crazy"", [Artifact.output(p`{0}foo.txt`), Artifact.input(p`{0}boo.txt`)]);", m_testAbsolutePath),
                             (context) =>
                             Cmd.Options("/crazy",
                                         Artifacts.Output(CreateAbsolutePath(context, String.Format("{0}foo.txt", m_testAbsolutePath))),
                                         Artifacts.Input(CreateAbsolutePath(context, String.Format("{0}boo.txt", m_testAbsolutePath))))));
        }
示例#12
0
 public XElement ToXml() => new XElement(
     "Build",
     Identity.ToXmlAttributes(),
     Artifacts.ToXml(),
     SigningInformation?.ToXml());
示例#13
0
        public static void Fill(LockableContainer cont, int level)
        {
            cont.Movable = false;
            cont.Locked  = true;
            int numberItems;

            if (level == 0)
            {
                cont.LockLevel = 0; // Can't be unlocked

                cont.DropItem(new Gold(Utility.RandomMinMax(50, 100)));

                if (Utility.RandomDouble() < 0.75)
                {
                    cont.DropItem(new TreasureMap(0, Map.Trammel));
                }
            }
            else
            {
                cont.TrapType  = TrapType.ExplosionTrap;
                cont.TrapPower = level * 25;
                cont.TrapLevel = level;

                cont.RequiredSkill = level switch
                {
                    1 => 36,
                    2 => 76,
                    3 => 84,
                    4 => 92,
                    5 => 100,
                    6 => 100,
                    _ => cont.RequiredSkill
                };

                cont.LockLevel    = cont.RequiredSkill - 10;
                cont.MaxLockLevel = cont.RequiredSkill + 40;

                // Publish 67 gold change
                // if (Core.SA)
                // cont.DropItem( new Gold( level * 5000 ) );
                // else
                cont.DropItem(new Gold(level * 1000));

                for (var i = 0; i < level * 5; ++i)
                {
                    cont.DropItem(Loot.RandomScroll(0, 63, SpellbookType.Regular));
                }

                if (Core.SE)
                {
                    numberItems = level switch
                    {
                        1 => 5,
                        2 => 10,
                        3 => 15,
                        4 => 38,
                        5 => 50,
                        6 => 60,
                        _ => 0
                    };
                }
                else
                {
                    numberItems = level * 6;
                }

                for (var i = 0; i < numberItems; ++i)
                {
                    Item item;

                    if (Core.AOS)
                    {
                        item = Loot.RandomArmorOrShieldOrWeaponOrJewelry();
                    }
                    else
                    {
                        item = Loot.RandomArmorOrShieldOrWeapon();
                    }

                    if (item is BaseWeapon weapon)
                    {
                        if (Core.AOS)
                        {
                            GetRandomAOSStats(out var attributeCount, out var min, out var max);
                            BaseRunicTool.ApplyAttributesTo(weapon, attributeCount, min, max);
                        }
                        else
                        {
                            weapon.DamageLevel     = (WeaponDamageLevel)Utility.Random(6);
                            weapon.AccuracyLevel   = (WeaponAccuracyLevel)Utility.Random(6);
                            weapon.DurabilityLevel = (WeaponDurabilityLevel)Utility.Random(6);
                        }

                        cont.DropItem(weapon);
                    }
                    else if (item is BaseArmor armor)
                    {
                        if (Core.AOS)
                        {
                            GetRandomAOSStats(out var attributeCount, out var min, out var max);
                            BaseRunicTool.ApplyAttributesTo(armor, attributeCount, min, max);
                        }
                        else
                        {
                            armor.ProtectionLevel = (ArmorProtectionLevel)Utility.Random(6);
                            armor.Durability      = (ArmorDurabilityLevel)Utility.Random(6);
                        }

                        cont.DropItem(armor);
                    }
                    else if (item is BaseHat hat)
                    {
                        if (Core.AOS)
                        {
                            GetRandomAOSStats(out var attributeCount, out var min, out var max);
                            BaseRunicTool.ApplyAttributesTo(hat, attributeCount, min, max);
                        }

                        cont.DropItem(hat);
                    }
                    else if (item is BaseJewel jewel)
                    {
                        GetRandomAOSStats(out var attributeCount, out var min, out var max);
                        BaseRunicTool.ApplyAttributesTo(jewel, attributeCount, min, max);

                        cont.DropItem(jewel);
                    }
                }
            }

            int reagents;

            if (level == 0)
            {
                reagents = 12;
            }
            else
            {
                reagents = level * 3;
            }

            for (var i = 0; i < reagents; i++)
            {
                var item = Loot.RandomPossibleReagent();
                item.Amount = Utility.RandomMinMax(40, 60);
                cont.DropItem(item);
            }

            int gems;

            if (level == 0)
            {
                gems = 2;
            }
            else
            {
                gems = level * 3;
            }

            for (var i = 0; i < gems; i++)
            {
                var item = Loot.RandomGem();
                cont.DropItem(item);
            }

            if (level == 6 && Core.AOS)
            {
                cont.DropItem(Artifacts.RandomElement().CreateInstance <Item>());
            }
        }
示例#14
0
        public void RandomParty()
        {
            Party.Clear();
            Artifacts.Clear();

            for (var i = 0; i < 8; i++)
            {
                switch (Dice.Roll(1, 6))
                {
                case 1:
                    Party.Add(SlayerRecruit.Wizard());
                    break;

                case 2:
                    Party.Add(SlayerRecruit.Warrior());
                    break;

                case 3:
                    Party.Add(SlayerRecruit.Archer());
                    break;

                case 4:
                    Party.Add(SlayerRecruit.MenAtArms());
                    Party.Add(SlayerRecruit.MenAtArms());
                    break;

                case 5:
                    Artifacts.Add(SlayerArtifact.RandomArtifact());
                    break;

                case 6:
                    if (!Party.Any(_ => _.Type == ERecruitType.MenAtArms))
                    {
                        Party.Add(SlayerRecruit.MenAtArms());
                        Party.Add(SlayerRecruit.MenAtArms());
                    }
                    else if (!Party.Any(_ => _.Type == ERecruitType.Warrior))
                    {
                        Party.Add(SlayerRecruit.Warrior());
                    }
                    else
                    {
                        switch (Dice.Roll(1, 3))
                        {
                        case 1:
                            Party.Add(SlayerRecruit.Wizard());
                            break;

                        case 2:
                            Party.Add(SlayerRecruit.Archer());
                            break;

                        default:
                            Artifacts.Add(SlayerArtifact.RandomArtifact());
                            break;
                        }
                    }
                    break;
                }
            }
        }
        public IActionResult HiPaySuccess(string code)
        {
            try
            {
                HttpResponseMessage resultHttp;
                using (var http = new HttpClient())
                {
                    var formContent = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("site_id", "338486"),
                        new KeyValuePair <string, string>("product_id", "1486845"),
                        new KeyValuePair <string, string>("code[]", code)
                    });
                    resultHttp = http.PostAsync(@"https://payment.allopass.com/api/onetime/validate-codes.apu", formContent).Result;
                }

                // Read XML
                ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
                HIPAYRETURN           dataAPI    = serializer.Deserialize <HIPAYRETURN>(resultHttp.Content.ReadAsStringAsync().Result);

                if (dataAPI.status == "0" && dataAPI.status_description == "success")
                {
                    using (var context = new SiteDbContext())
                    {
                        double doublePrice = -1.0;
                        double.TryParse(dataAPI.price, out doublePrice);
                        if (doublePrice == -1.0)
                        {
                            doublePrice = 0.0;
                        }


                        // Add Deal
                        Deals_statistics stats = new Deals_statistics()
                        {
                            UserId       = User.FindFirstValue(ClaimTypes.NameIdentifier),
                            Code         = code + "(" + dataAPI.transaction_id + ")",
                            Date         = DateTime.Now,
                            Price        = doublePrice,
                            Nb_Artifacts = 16,
                            PaymentType  = "HiPay Mobile"
                        };
                        context.Deals_statistics.Add(stats);

                        //Add Artifact
                        Artifacts artifact = context.Artifacts
                                             .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier))
                                             .Select(r => r).FirstOrDefault();

                        artifact.Number += (int)16;
                        context.Update(artifact);

                        context.SaveChanges();
                    }

                    TempData["success"] = "Your payment has been successfully completed! You have received your artefacts.";
                }
                else
                {
                    TempData["error"] = "Code can already be used or invalid. If the problem contact the support.";
                }

                return(RedirectToAction(nameof(ShopController.Finished), "Shop"));
            }
            catch
            {
                TempData["error"] = "Error during payment, code can already be used. If the problem  contact the support.";
                return(RedirectToAction(nameof(ShopController.Finished), "Shop"));
            }
        }
示例#16
0
        protected void AddVersionInformation(TextWriter writer, AbstractWrapper wrapper)
        {
            AddSectionHeader(writer, "Version Information");

            var docs35     = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("net35"), wrapper);
            var docs45     = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("net45"), wrapper);
            var docsCore13 = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("netstandard1.3"), wrapper);
            var docsCore20 = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("netstandard2.0"), wrapper);
            var docsPCL    = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("pcl"), wrapper);
            var docsUnity  = NDocUtilities.FindDocumentation(Artifacts.NDocForPlatform("unity"), wrapper);

            // If there is no documentation then assume it is available for all platforms, excluding Unity.
            var boolNoDocs = docs35 == null && docs45 == null && docsCore13 == null && docsCore20 == null && docsPCL == null && docsUnity == null;

            // .NET core Framework

            StringBuilder sbNETStandard = new StringBuilder();

            if (boolNoDocs || (wrapper != null && docsCore20 != null))
            {
                sbNETStandard.Append("2.0");
            }
            if (boolNoDocs || (wrapper != null && docsCore13 != null))
            {
                if (sbNETStandard.Length > 0)
                {
                    sbNETStandard.Append(", ");
                }

                sbNETStandard.Append("1.3");
            }

            if (sbNETStandard.Length > 0)
            {
                writer.WriteLine("<p><strong>.NET Standard: </strong><br/>Supported in: {0}<br/>", sbNETStandard.ToString());
            }


            // .NET Framework
            StringBuilder sbFramework = new StringBuilder();

            if (boolNoDocs || (wrapper != null && docs45 != null))
            {
                sbFramework.Append("4.5");
            }
            if (boolNoDocs || (wrapper != null && docs35 != null))
            {
                if (sbFramework.Length > 0)
                {
                    sbFramework.Append(", ");
                }
                sbFramework.Append("4.0, 3.5");
            }

            if (sbFramework.Length > 0)
            {
                writer.WriteLine("<p><strong>.NET Framework: </strong><br/>Supported in: {0}<br/>", sbFramework.ToString());
            }

            if (boolNoDocs || docsPCL != null || _referAsyncAlternativePCL)
            {
                writer.WriteLine("<p><strong>Portable Class Library: </strong><br/>");
                writer.WriteLine("Supported in: Windows Store Apps<br/>");
                writer.WriteLine("Supported in: Xamarin Android<br/>");
                writer.WriteLine("Supported in: Xamarin iOS (Unified)<br/>");
                writer.WriteLine("Supported in: Xamarin.Forms<br/>");
            }

            if (docsUnity != null || _unityVersionOfAsyncExists || _referAsyncAlternativeUnity)
            {
                writer.WriteLine("<p><strong>Unity: </strong><br/>");
                writer.WriteLine("Supported Versions: 4.6 and above<br/>");
                writer.WriteLine("Supported Platforms: Android, iOS, Standalone<br/>");
            }

            AddSectionClosing(writer);
        }
        public async Task <IActionResult> PaidWithCard(StripeChargeForm model)
        {
            try
            {
                var             userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                ApplicationUser user   = await _userManager.FindByIdAsync(userId);

                // Get Price
                ArtifactsPrices price;
                using (var context = new SiteDbContext())
                {
                    price = context.ArtifactsPrices
                            .Where(r => r.Id == model.DealsId)
                            .Select(r => r).FirstOrDefault();
                }
                if (price == null)
                {
                    throw new ArgumentNullException("Price error");
                }

                // Create or Get Customers
                string stripeId = user.StripeId;
                if (stripeId == null)
                {
                    var newCustomer = new StripeCustomerCreateOptions();
                    newCustomer.Email       = user.Email;
                    newCustomer.Description = $"{model.Name} ({user.UserName})";
                    newCustomer.SourceToken = model.Token;

                    var            customerService = new StripeCustomerService();
                    StripeCustomer stripeCustomer  = customerService.Create(newCustomer);
                    stripeId = stripeCustomer.Id;

                    // Update User
                    user.StripeId = stripeId;
                    await _userManager.UpdateAsync(user);
                }

                // Charge
                var myCharge = new StripeChargeCreateOptions();

                myCharge.Amount      = (int)(price.Price * 100);
                myCharge.Currency    = "eur";
                myCharge.Description = "Le mythe des montagnes - Shop(Id: " + price.Id + ")";
                myCharge.CustomerId  = stripeId;

                var          chargeService = new StripeChargeService();
                StripeCharge stripeCharge  = chargeService.Create(myCharge);

                // Verify
                if (stripeCharge.Status == "succeeded")
                {
                    using (var context = new SiteDbContext())
                    {
                        // Add Deal
                        Deals_statistics stats = new Deals_statistics()
                        {
                            UserId       = User.FindFirstValue(ClaimTypes.NameIdentifier),
                            Date         = DateTime.Now,
                            Price        = (double)price.Price,
                            Nb_Artifacts = price.Artifacts,
                            PaymentType  = "Stripe",
                        };
                        context.Deals_statistics.Add(stats);

                        //Add Artifact
                        Artifacts artifact = context.Artifacts
                                             .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier))
                                             .Select(r => r).FirstOrDefault();

                        artifact.Number += (int)price.Artifacts;
                        context.Update(artifact);

                        context.SaveChanges();
                    }

                    // Set message
                    TempData["success"] = "Your payment has been successfully completed! You have received your artefacts.";
                }
                else
                {
                    TempData["error"] = "Error during payment, check your card code. If the problem persists contact the support.";
                }

                return(RedirectToAction(nameof(ShopController.Finished), "Shop"));
            }
            catch
            {
                TempData["error"] = "Error during payment, check your card code. If the problem persists contact the support.";
                return(RedirectToAction(nameof(ShopController.Finished), "Shop"));
            }
        }
示例#18
0
 void Start()
 {
     displayItem  = GetComponent <DisplayItem>();
     artifacts    = GameObject.Find("PlayerShip").GetComponent <Artifacts>();
     playerScript = GameObject.Find("PlayerShip").GetComponent <PlayerScript>();
 }
        // POST: AjaxRedeemGift
        public IActionResult AjaxRedeemGift(string id)
        {
            try
            {
                string jsonString = "[";
                using (var context = new SiteDbContext())
                {
                    var now = DateTime.Now;

                    Gifts gift = context.Gifts
                                 .Where(r => r.Code.Replace("-", "") == id && r.Active == true)
                                 .Select(r => r).SingleOrDefault();

                    if (gift == null)
                    {
                        throw new InvalidCastException("Your code is incorrect or has already been used.");
                    }
                    if (!(now >= gift.Start && now <= gift.End))
                    {
                        throw new InvalidCastException("Your code has expired or is not active yet.");
                    }

                    if (!gift.SinglePerAccount)
                    {
                        gift.Active = false;
                    }

                    // SinglePerAccount
                    if (gift.SinglePerAccount)
                    {
                        var AccountAlreadyUseIt = context.Deals_statistics
                                                  .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier) && r.Code.Replace("-", "") == id)
                                                  .Count();
                        if (AccountAlreadyUseIt > 0)
                        {
                            throw new InvalidCastException("The code already used by your account.");
                        }
                    }

                    Deals_statistics stats = new Deals_statistics()
                    {
                        UserId       = User.FindFirstValue(ClaimTypes.NameIdentifier),
                        Date         = DateTime.Now,
                        Code         = gift.Code,
                        Price        = 0,
                        Nb_Artifacts = (int)gift.Artifacts,
                        PaymentType  = "Gift Code",
                    };
                    context.Deals_statistics.Add(stats);

                    if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                    {
                        jsonString += "{ \"Success\" : \"true\",\"Title\" : \"Bravo\",\"Msg\" : \"Vous venez de valider votre code cadeau, les bonus ont été ajoutés à votre compte !\" }";
                    }
                    else
                    {
                        jsonString += "{ \"Success\" : \"true\",\"Title\" : \"Bravo\",\"Msg\" : \"You just validate your gift code, the bonuses have been added to your account !\" }";
                    }

                    // Artifacts
                    if (gift.Artifacts != null)
                    {
                        if (gift.Artifacts > 0)
                        {
                            Artifacts artifact = context.Artifacts
                                                 .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier))
                                                 .Select(r => r).FirstOrDefault();

                            artifact.Number += (int)gift.Artifacts;
                            context.Update(artifact);

                            if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                            {
                                jsonString += ",{\"Title\":\"Artefacts\", \"Text\":\"Vous obtenez " + gift.Artifacts + " artefats.\", \"Img\":\"/images/Game/artifact.svg\"}";
                            }
                            else
                            {
                                jsonString += ",{\"Title\":\"Artifacts\", \"Text\":\"You obtain " + gift.Artifacts + " artifacts.\", \"Img\":\"/images/Game/artifact.svg\"}";
                            }
                        }
                    }

                    // Xp
                    if (gift.Experiences != null)
                    {
                        if (gift.Experiences > 0)
                        {
                            Characters player = context.Characters
                                                .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier))
                                                .Select(r => r).FirstOrDefault();

                            player.Xp += (int)gift.Experiences;
                            context.Update(player);

                            if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                            {
                                jsonString += ",{\"Title\":\"Expérience\", \"Text\":\"Vous obtenez " + gift.Experiences + " d'expériences\", \"Img\":\"/images/Game/gold.svg\"}";
                            }
                            else
                            {
                                jsonString += ",{\"Title\":\"Experience\", \"Text\":\"You obtain " + gift.Experiences + " experiences.\", \"Img\":\"/images/Game/gold.svg\"}";
                            }
                        }
                    }

                    // Items
                    if (gift.Items != null)
                    {
                        IList <string> items = gift.Items.Split(',').ToList();
                        foreach (string item in items)
                        {
                            var itemExist = context.Items
                                            .Where(r => r.Id == Int32.Parse(item))
                                            .Select(r => r).FirstOrDefault();

                            if (itemExist != null)
                            {
                                Inventory inventory = new Inventory()
                                {
                                    UserId = User.FindFirstValue(ClaimTypes.NameIdentifier),
                                    ItemId = Int32.Parse(item)
                                };

                                if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                                {
                                    jsonString += ",{\"Title\":\"" + itemExist.TitleFr + "\", \"Text\":\"Vous trouverez l'objet dans votre inventaire.\", \"Img\":\"/uploads/game/cards/items/" + itemExist.Id + ".fr.svg\"}";
                                }
                                else
                                {
                                    jsonString += ",{\"Title\":\"" + itemExist.TitleEn + "\", \"Text\":\"You will find the item in your inventory.\", \"Img\":\"/uploads/game/cards/items/" + itemExist.Id + ".en.svg\"}";
                                }

                                context.Add(inventory);
                            }
                        }
                    }

                    context.Update(gift);
                    context.SaveChanges();
                }

                jsonString += "]";
                return(Json(JsonConvert.DeserializeObject(jsonString)));
            }
            catch (InvalidCastException e)
            {
                string jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Error\",\"Msg\" : \"" + e.Message + "\" }]";
                if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                {
                    if (e.Message == "Your code has expired or is not active yet.")
                    {
                        jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Erreur\",\"Msg\" : \"Votre code a expiré ou n'est pas encore actif.\" }]";
                    }
                    else if (e.Message == "Your code is incorrect or has already been used.")
                    {
                        jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Erreur\",\"Msg\" : \"Votre code est incorrect ou a déjà été utilisé.\" }]";
                    }
                    else if (e.Message == "The code already used by your account.")
                    {
                        jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Erreur\",\"Msg\" : \"Le code à déjà utilisé par votre compte.\" }]";
                    }
                }

                return(Json(JsonConvert.DeserializeObject(jsonString)));
            }
        }
 private void AssertFileDownloadedToCorrectPath(List<string> downloadedFiles, string destinationFolder, Artifacts artifacts)
 {
     downloadedFiles.Count.Should().Be(artifacts.Files.Count, "unexpected number of files downloadeded");
     downloadedFiles[0].Should().Be(Path.Combine(destinationFolder, _artifactFileName));
 }
示例#21
0
 /// <summary>Concatenates the results.</summary>
 /// <returns>The result.</returns>
 public string Concatenate()
 {
     return(ConversionUtilities.TrimWhiteSpaces(string.Join("\n\n", Artifacts.Select(p => p.Code))));
 }