public PreviewWindowModel(
     IEnumerable <PackageAction> actions,
     Installation.InstallationTarget target)
 {
     _previewResults = PreviewResult.CreatePreview(actions, target);
     Title           = Resources.Resources.WindowTitle_Preview;
 }
Ejemplo n.º 2
0
        private async Task SavePreviewStatistics(PreviewResult previewResult)
        {
            var loggedInUserId = HttpContext.GetOwinContext().Authentication.User.Identity.GetUserId <int>();

            var user = DataContext.Users.Find(loggedInUserId);

            Func <string, bool> existing;

            if (user == null)
            {
                existing = url => !DataContext.Previews.Where(x => x.Skin.Id == previewResult.Skin.Id).Any(x => x.PreviewImage == url);
            }
            else
            {
                existing = url => !DataContext.Previews.Where(x => x.Skin.Id == previewResult.Skin.Id).Any(x => x.Requestor.Id == user.Id && x.PreviewImage == url);
            }

            foreach (var url in previewResult.Urls.Where(existing))
            {
                DataContext.Previews.Add(new Preview
                {
                    Skin         = DataContext.Skins.Find(previewResult.Skin.Id),
                    DragonId     = previewResult.Dragon.FRDragonId,
                    ScryerUrl    = previewResult.DragonUrl,
                    PreviewImage = url,
                    DragonData   = previewResult.Dragon.ToString(),
                    PreviewTime  = DateTime.UtcNow,
                    Requestor    = DataContext.Users.Find(loggedInUserId),
                    Version      = previewResult.Skin.Version
                });
            }

            await DataContext.SaveChangesAsync();
        }
Ejemplo n.º 3
0
        private static async Task <PreviewResult> GenerateOrFetchPreview(PreviewResult result, string skinId, int?version, DragonCache dragon, bool isDressingRoom, bool swapSilhouette, bool force)
        {
            var azureImageService = new AzureImageService();

            using (var ctx = new DataContext())
            {
                Skin skin;
                var  skins = ctx.Skins.Where(x => x.GeneratedId == skinId);
                if (version == null)
                {
                    skin    = skins.OrderByDescending(x => x.Version).FirstOrDefault();
                    version = skin.Version;
                }
                else
                {
                    skin = skins.FirstOrDefault(x => x.Version == version);
                }

                if (skin == null)
                {
                    return(result.WithErrorMessage("Skin not found."));
                }

                result.Skin = skin;

                if (dragon == null)
                {
                    dragon = FRHelpers.ParseUrlForDragon(string.Format(FRHelpers.DressingRoomDummyUrl, skin.DragonType, skin.GenderType), skinId, version);
                }

                result.Dragon = dragon;

                if (dragon.Age == Age.Hatchling)
                {
                    return(result.WithErrorMessage("Skins can only be previewed on adult dragons."));
                }

                if (swapSilhouette)
                {
                    var swappedDragon = FRHelpers.ParseUrlForDragon(GeneratedFRHelpers.GenerateDragonImageUrl(dragon, swapSilhouette));
                    swappedDragon.FRDragonId = dragon.FRDragonId;
                    dragon = swappedDragon;
                }

                if (skin.DragonType != (int)dragon.DragonType)
                {
                    return(result.WithErrorMessage("This skin is meant for a {0} {1}, the dragon you provided is a {2} {3}.", (DragonType)skin.DragonType, (Gender)skin.GenderType, dragon.DragonType, dragon.Gender));
                }

                if (skin.GenderType != (int)dragon.Gender)
                {
                    return(result.WithErrorMessage("This skin is meant for a {0}, the dragon you provided is a {1}.", (Gender)skin.GenderType, dragon.Gender));
                }
            }

            Bitmap dragonImage = null;

            var azureImagePreviewPath = $@"previews\{skinId}\{(version == 1 ? "" : $@"{version}\")}{dragon.GetFileName()}.png";
        private IEnumerable <PowerShellPreviewResult> AddToPowerShellPreviewResult(List <PowerShellPreviewResult> list,
                                                                                   PreviewResult result, PowerShellPackageAction action, VsProject proj)
        {
            IEnumerable <PackageIdentity>     identities = null;
            IEnumerable <UpdatePreviewResult> updates    = null;

            switch (action)
            {
            case PowerShellPackageAction.Install:
            {
                identities = result.Added;
                break;
            }

            case PowerShellPackageAction.Uninstall:
            {
                identities = result.Deleted;
                break;
            }

            case PowerShellPackageAction.Update:
            {
                updates = result.Updated;
                break;
            }
            }

            if (identities != null)
            {
                foreach (PackageIdentity identity in identities)
                {
                    PowerShellPreviewResult previewRes = new PowerShellPreviewResult();
                    previewRes.Id     = identity.Id;
                    previewRes.Action = string.Format("{0} ({1})", action.ToString(), identity.Version.ToNormalizedString());
                    list.Add(previewRes);
                    previewRes.ProjectName = proj.Name;
                }
            }

            if (updates != null)
            {
                foreach (UpdatePreviewResult updateResult in updates)
                {
                    PowerShellPreviewResult previewRes = new PowerShellPreviewResult();
                    previewRes.Id     = updateResult.Old.Id;
                    previewRes.Action = string.Format("{0} ({1} => {2})",
                                                      action.ToString(), updateResult.Old.Version.ToNormalizedString(), updateResult.New.Version.ToNormalizedString());
                    list.Add(previewRes);
                    previewRes.ProjectName = proj.Name;
                }
            }

            return(list);
        }
Ejemplo n.º 5
0
        public PreviewResult Preview(string templateBody, string extension, string itemJsonValue)
        {
            TransformCore core = new TransformCore();

            var previewResult = core.Preview(templateBody, extension, itemJsonValue);

            PreviewResult returnValue = new PreviewResult();

            returnValue.PreviewStatus       = (int)ToVo(previewResult.PreviewStatus);
            returnValue.EngineStatus        = (int)ToVo(previewResult.EngineStatus);
            returnValue.EngineCompileErrors = previewResult.EngineCompileErrors;
            returnValue.EngineRunException  = previewResult.EngineRunException;
            returnValue.Output = previewResult.Output;

            return(returnValue);
        }
        private PreviewResult ToPreviewResult(EngineResult engineResult)
        {
            PreviewResult previewResult = new PreviewResult();

            previewResult.PreviewStatus = PreviewStatus.Success;
            previewResult.EngineStatus  = engineResult.EngineStatus;
            previewResult.Output        = engineResult.Output;

            if (engineResult.EngineStatus != EngineStatus.Success)
            {
                previewResult.PreviewStatus       = PreviewStatus.EngineSaysNo;
                previewResult.EngineCompileErrors = engineResult.CompileErrors;
                previewResult.EngineRunException  = engineResult.RunException;
            }

            return(previewResult);
        }
Ejemplo n.º 7
0
        public static async Task <PreviewResult> GenerateOrFetchPreview(string skinId, int dragonId, bool swapSilhouette = false, bool force = false, int?version = null)
        {
            var result = new PreviewResult(PreviewSource.DragonId)
            {
                Forced = force
            };
            var dragonUrl = FRHelpers.GetDragonImageUrlFromDragonId(dragonId);

            if (dragonUrl.StartsWith(".."))
            {
                return(result.WithErrorMessage("{0} appears to be an invalid dragon id", dragonId));
            }

            var dragon = FRHelpers.ParseUrlForDragon(dragonUrl);

            dragon.FRDragonId = dragonId;
            return(await GenerateOrFetchPreview(result, skinId, version, dragon, false, swapSilhouette, force));
        }
Ejemplo n.º 8
0
 private void SaveStatistics(PreviewResult previewResult)
 {
     using (var ctx = new DataContext())
     {
         foreach (var url in previewResult.Urls.Where(url => !ctx.Previews.Where(x => x.Skin.Id == previewResult.Skin.Id).Any(x => x.PreviewImage == url)))
         {
             ctx.Previews.Add(new Preview
             {
                 Skin         = ctx.Skins.Find(previewResult.Skin.Id),
                 DragonId     = previewResult.Dragon.FRDragonId,
                 ScryerUrl    = previewResult.DragonUrl,
                 PreviewImage = url,
                 DragonData   = previewResult.Dragon.ToString(),
                 PreviewTime  = DateTime.UtcNow,
                 Requestor    = null,
                 Version      = previewResult.Skin.Version
             });
         }
     }
 }
Ejemplo n.º 9
0
            private Embed GeneratedPreviewEmbed(PreviewResult previewResult, bool showApparel = false)
            {
                var botAssembly = Assembly.GetAssembly(typeof(BaseModule));
                var modules     = botAssembly.DefinedTypes.Where(x =>
                {
                    try
                    {
                        return(!x.IsNested && x.BaseType == typeof(BaseModule));
                    }
                    catch
                    {
                        return(false);
                    }
                });

                var embed = new EmbedBuilder();

                embed.WithDescription($"Here is your preview on **{previewResult.Skin.Title ?? previewResult.Skin.GeneratedId}**");
                if (!showApparel && previewResult.Urls.Length > 1)
                {
                    embed.Description += "\r\n\nYou can show the apparel version of the preview by adding **-apparel** at the end of the preview command.";
                }

                embed.WithFields(new EmbedFieldBuilder().WithName("Dragon preview").WithValue($"[click here]({CDNBasePath}{previewResult.Urls[0]})"));
                if (previewResult.Urls.Length > 1)
                {
                    embed.WithFields(new EmbedFieldBuilder().WithName("Apparel preview").WithValue($"[click here]({CDNBasePath}{previewResult.Urls[1]})"));
                }
                if (!showApparel || previewResult.Urls.Length == 1)
                {
                    embed.WithImageUrl($"{CDNBasePath}{previewResult.Urls[0]}");
                }
                else
                {
                    embed.WithImageUrl($"{CDNBasePath}{previewResult.Urls[1]}");
                }

                embed.WithAuthor(new EmbedAuthorBuilder().WithName($"{previewResult.Skin.Title ?? previewResult.Skin.GeneratedId} v{previewResult.Skin.Version}"));
                embed.WithThumbnailUrl($"{CDNBasePath}/previews/{previewResult.Skin.GeneratedId}/{(previewResult.Skin.Version == 1 ? "" : $@"{previewResult.Skin.Version}/")}preview.png");
Ejemplo n.º 10
0
        public async Task <ActionResult> Preview(PreviewModelPost model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToRoute("Preview", new { model.SkinId }));
            }

            PreviewResult result = null;

            if (model.DragonId != null)
            {
                result = await SkinTester.GenerateOrFetchPreview(model.SkinId, model.DragonId.Value, model.SwapSilhouette, model.Force);
            }
            else if (!string.IsNullOrWhiteSpace(model.ScryerUrl))
            {
                result = await SkinTester.GenerateOrFetchPreview(model.SkinId, model.ScryerUrl, model.Force);
            }
            else if (!string.IsNullOrWhiteSpace(model.DressingRoomUrl))
            {
                result = await SkinTester.GenerateOrFetchPreview(model.SkinId, model.DressingRoomUrl, model.Force);
            }

            if (result == null || !result.Success)
            {
                AddErrorNotification(result?.GetHtmlErrorMessage);
                return(RedirectToRoute("Preview", new { model.SkinId }));
            }

            await SavePreviewStatistics(result);

            return(View("PreviewResult", new PreviewModelPostViewModel
            {
                SkinId = model.SkinId,
                Result = result,
                Dragon = result.Dragon
            }));
        }
        private IEnumerable <PowerShellPreviewResult> ConvertToPowerShellPreviewResult(PreviewResult result, VsProject proj)
        {
            List <PowerShellPreviewResult> psResults = new List <PowerShellPreviewResult>();

            AddToPowerShellPreviewResult(psResults, result, PowerShellPackageAction.Install, proj);
            AddToPowerShellPreviewResult(psResults, result, PowerShellPackageAction.Uninstall, proj);
            AddToPowerShellPreviewResult(psResults, result, PowerShellPackageAction.Update, proj);
            return(psResults);
        }
        private void LogPreviewResult(PreviewResult result, VsProject proj)
        {
            IEnumerable <PowerShellPreviewResult> psResults = ConvertToPowerShellPreviewResult(result, proj);

            WriteObject(psResults);
        }
        /// <summary>
        /// Resolve and execute actions for a single package for specified package action type.
        /// </summary>
        /// <param name="identity"></param>
        /// <param name="projects"></param>
        /// <param name="actionType"></param>
        protected void ExecuteSinglePackageAction(PackageIdentity identity, IEnumerable <VsProject> projects, PackageActionType actionType)
        {
            if (identity == null)
            {
                return;
            }

            try
            {
                // Resolve Actions
                List <VsProject> targetProjects = projects.ToList();
                Task <IEnumerable <Client.Resolution.PackageAction> > resolverAction =
                    PackageActionResolver.ResolveActionsAsync(identity, actionType, targetProjects, Solution);

                IEnumerable <Client.Resolution.PackageAction> actions = resolverAction.Result;

                if (WhatIf.IsPresent)
                {
                    foreach (VsProject proj in targetProjects)
                    {
                        IEnumerable <PreviewResult> previewResults = PreviewResult.CreatePreview(actions, proj);
                        if (previewResults.Count() == 0)
                        {
                            PowerShellPreviewResult prResult = new PowerShellPreviewResult();
                            prResult.Id          = identity.Id;
                            prResult.Action      = Resources.Log_NoActionsWhatIf;
                            prResult.ProjectName = proj.Name;
                            WriteObject(prResult);
                        }
                        else
                        {
                            foreach (var p in previewResults)
                            {
                                LogPreviewResult(p, proj);
                            }
                        }
                    }

                    return;
                }

                // Execute Actions
                if (actions.Count() == 0 && actionType == PackageActionType.Install)
                {
                    Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, identity.Id);
                }
                else
                {
                    var            userAction = new UserAction(_actionType, identity);
                    ActionExecutor executor   = new ActionExecutor();
                    executor.ExecuteActions(actions, this, userAction);
                }
            }
            // TODO: Consider adding the rollback behavior if exception is thrown.
            catch (Exception ex)
            {
                if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                {
                    WriteError(ex.InnerException.Message);
                }
                else
                {
                    WriteError(ex.Message);
                }
            }
        }
Ejemplo n.º 14
0
 private IEnumerable<PowerShellPreviewResult> ConvertToPowerShellPreviewResult(PreviewResult result, VsProject proj)
 {
     List<PowerShellPreviewResult> psResults = new List<PowerShellPreviewResult>();
     AddToPowerShellPreviewResult(psResults, result, PowerShellPackageAction.Install, proj);
     AddToPowerShellPreviewResult(psResults, result, PowerShellPackageAction.Uninstall, proj);
     AddToPowerShellPreviewResult(psResults, result, PowerShellPackageAction.Update, proj);
     return psResults;
 }
Ejemplo n.º 15
0
        public static async Task <PreviewResult> GenerateOrFetchPreview(string skinId, string dragonUrl, bool force = false, int?version = null)
        {
            PreviewResult result = null;

            if (dragonUrl.Contains("/dgen/dressing-room"))
            {
                // Dressing room link
                result = new PreviewResult(PreviewSource.DressingRoom)
                {
                    Forced = force
                };

                var         apparelDragon = FRHelpers.ParseUrlForDragon(dragonUrl);
                DragonCache dragon;
                if (dragonUrl.Contains("/dgen/dressing-room/dummy"))
                {
                    dragon = FRHelpers.ParseUrlForDragon(dragonUrl);
                }
                else if (dragonUrl.Contains("dgen/dressing-room/scry"))
                {
                    var scryId  = int.Parse(Regex.Match(dragonUrl, @"sdid=([\d]*)").Groups[1].Value);
                    var scryUrl = FRHelpers.GetDragonImageUrlFromScryId(scryId);
                    dragon = FRHelpers.ParseUrlForDragon(scryUrl);
                }
                else
                {
                    var dragonId = int.Parse(Regex.Match(dragonUrl, @"did=([\d]*)").Groups[1].Value);
                    dragon = FRHelpers.GetDragonFromDragonId(dragonId);
                }

                if (dragon.DragonType.IsAncientBreed())
                {
                    return(result.WithErrorMessage("Ancient breeds cannot wear apparal."));
                }

                dragon.Apparel = apparelDragon.Apparel;
                if (dragon.GetApparel().Length == 0)
                {
                    return(result.WithErrorMessage("This dressing room URL contains no apparel."));
                }

                result = await GenerateOrFetchPreview(result, skinId, version, dragon, true, false, force);
            }
            else if (dragonUrl.Contains("dgen/preview/dragon"))
            {
                // Scry image link
                result = new PreviewResult(PreviewSource.ScryImage)
                {
                    Forced = force
                };

                var dragon = FRHelpers.ParseUrlForDragon(dragonUrl);
                result = await GenerateOrFetchPreview(result, skinId, version, dragon, false, false, force);
            }
            else if (dragonUrl.Contains("scrying/predict"))
            {
                result = new PreviewResult(PreviewSource.ScryLink)
                {
                    Forced = force
                };

                DragonCache dragon;
                var         scryId = Regex.Match(dragonUrl, @"morph=(\d*)");
                if (scryId.Success)
                {
                    // Saved morph link
                    var scryUrl = FRHelpers.GetDragonImageUrlFromScryId(int.Parse(scryId.Groups[1].Value));
                    dragon = FRHelpers.ParseUrlForDragon(scryUrl);
                }
                else
                {
                    // Scry predict link
                    dragon = FRHelpers.ParseUrlForDragon(GeneratedFRHelpers.GenerateDragonImageUrl(FRHelpers.ParseUrlForDragon(dragonUrl, forced: true)));
                }

                result = await GenerateOrFetchPreview(result, skinId, version, dragon, false, false, force);
            }
            else
            {
                return(new PreviewResult(PreviewSource.Unknown).WithErrorMessage("The URL provided is not valid."));
            }

            result.DragonUrl = dragonUrl;
            return(result);
        }
Ejemplo n.º 16
0
        private IEnumerable<PowerShellPreviewResult> AddToPowerShellPreviewResult(List<PowerShellPreviewResult> list, 
            PreviewResult result, PowerShellPackageAction action, VsProject proj)
        {
            IEnumerable<PackageIdentity> identities = null;
            IEnumerable<UpdatePreviewResult> updates = null;
            switch (action)
            {
                case PowerShellPackageAction.Install:
                    {
                        identities = result.Added;
                        break;
                    }
                case PowerShellPackageAction.Uninstall:
                    {
                        identities = result.Deleted;
                        break;
                    }
                case PowerShellPackageAction.Update:
                    {
                        updates = result.Updated;
                        break;
                    }
            }

            if (identities != null)
            {
                foreach (PackageIdentity identity in identities)
                {
                    PowerShellPreviewResult previewRes = new PowerShellPreviewResult();
                    previewRes.Id = identity.Id;
                    previewRes.Action = string.Format("{0} ({1})", action.ToString(), identity.Version.ToNormalizedString());
                    list.Add(previewRes);
                    previewRes.ProjectName = proj.Name;
                }
            }

            if (updates != null)
            {
                foreach (UpdatePreviewResult updateResult in updates)
                {
                    PowerShellPreviewResult previewRes = new PowerShellPreviewResult();
                    previewRes.Id = updateResult.Old.Id;
                    previewRes.Action = string.Format("{0} ({1} => {2})", 
                        action.ToString(), updateResult.Old.Version.ToNormalizedString(), updateResult.New.Version.ToNormalizedString());
                    list.Add(previewRes);
                    previewRes.ProjectName = proj.Name;
                }
            }

            return list;
        }
Ejemplo n.º 17
0
        public void PreviewFile()
        {
            string returnMsg = string.Empty;
            int    errorCode = 0;

            // 校验参数
            string[] parametersRequired = { "fileHistoryId" };
            if (!CheckParamsRequired(parametersRequired, out errorCode, out returnMsg))
            {
                JsonResult <string> resultPra = new JsonResult <string> {
                    Code = errorCode, Message = returnMsg, Rows = 0, Result = null
                };
                GenerateJson(resultPra);
                return;
            }

            string actPath                = string.Empty;
            string taskRootFolder         = string.Empty;
            string taskFolderWithoutEmpNo = string.Empty;

            try
            {
                string fileHistoryId = context.Request["fileHistoryId"];
                string previewFolder = ConfigurationManager.AppSettings["filePreviewFolder"].ToString();
                // 根据 ID 获取到 fileHistory 对象
                FileHistory fileHistory        = new FileHistoryBLL().GetModel(fileHistoryId);
                DataTable   dtPrjIdAndCategory = new FileCategoryBLL().GetProjectIdByFileHistoryId(fileHistoryId).Tables[0];
                string      projectId          = Convert.ToString(dtPrjIdAndCategory.Rows[0]["PROJECTID"]);
                string      category           = Convert.ToString(dtPrjIdAndCategory.Rows[0]["category"]);
                string      folderName         = Convert.ToString(dtPrjIdAndCategory.Rows[0]["folderName"]);
                bool        flag             = new FileCategoryBLL().GetFilePathByProjectId(projectId, category, folderName, false, out actPath, out taskRootFolder, out taskFolderWithoutEmpNo, out errorCode);
                string      physicalFileName = Path.Combine(actPath, fileHistory.FILENAME);
                if (File.Exists(physicalFileName))
                {
                    System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
                    string previewHtmlFile = Path.Combine(previewFolder, fileHistory.ID + ".html");
                    LogHelper.WriteLine("previewHtmlFile Path: " + previewHtmlFile);
                    if (!File.Exists(previewHtmlFile))
                    {
                        string extName = Path.GetExtension(physicalFileName);
                        switch (extName)
                        {
                        case ".doc":
                        case ".docx":
                            //case ".rtf":
                            Office2HtmlHelper.Word2Html(physicalFileName, previewFolder, fileHistory.ID);
                            break;

                        case ".xls":
                        case ".xlsx":
                            Office2HtmlHelper.Excel2Html(physicalFileName, previewFolder, fileHistory.ID);
                            break;

                        default:
                            return;
                        }
                    }

                    List <PreviewResult> lstPre = new List <PreviewResult>();
                    if (File.Exists(previewHtmlFile))
                    {
                        string htmlFile = string.Format("/FilePreview/{0}.html", fileHistory.ID);

                        PreviewResult pre = new PreviewResult();
                        pre.previewUrl = htmlFile;
                        lstPre.Add(pre);
                    }
                    else
                    {
                        errorCode = 1;
                        returnMsg = "文件未能成功生成!";
                    }
                    JsonResult <PreviewResult> resultPre = new JsonResult <PreviewResult> {
                        Code = errorCode, Message = returnMsg, Rows = 0, Result = lstPre
                    };
                    GenerateJson(resultPre);
                    return;
                }
                errorCode = 6001;
                returnMsg = ErrorCode.GetCodeMessage(errorCode);
                JsonResult <string> result = new JsonResult <string> {
                    Code = errorCode, Message = returnMsg, Rows = 0, Result = null
                };
                GenerateJson(result);
                return;
            }
            catch (Exception ex)
            {
                errorCode = 1;
                LogHelper.WriteLine("预览生成出错:" + ex.Message + ex.StackTrace);
            }
        }
Ejemplo n.º 18
0
 private void LogPreviewResult(PreviewResult result, VsProject proj)
 {
     IEnumerable<PowerShellPreviewResult> psResults = ConvertToPowerShellPreviewResult(result, proj);
     WriteObject(psResults);
 }