Beispiel #1
0
        protected void EmulateUserButton_Click(object sender, EventArgs e)
        {
            int userId = WebUtils.GetIntRequestParam("UserId", 0);

            User currentUser  = CurrentUser;
            User emulatedUser = Data.User.Get(userId);

            if (emulatedUser.IsNull)
            {
                MessageLabel1.SetErrorMessage("User not found");
                return;
            }

            //renew session api token if user not currently active
            if (!UserManager.APISessionIsValid(emulatedUser))
            {
                UserManager.RenewSessionAPIToken(emulatedUser);
            }

            m_Logger.DebugFormat("User: {0} emulating: {1}, user id: {2}", CurrentUser.FullName, emulatedUser.FullName, emulatedUser.UserId);

            AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.UserLogin, string.Format("Emulating: {0}", emulatedUser.FullName));

            SessionInfo.Current.User = emulatedUser;
            SessionInfo.Current.UserSessionInfo.Reset();
            SessionInfo.Current.AdminSessionInfo.Reset();

            Login.SetupSessionForCurrentSessionUser();

            AuditLogManager.LogUserAction(emulatedUser, AuditUserAction.UserLogin, string.Format("User being emulated by {0}", currentUser.FullName));

            Response.Redirect("~/Default.aspx");
        }
        protected override void Grid_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "add")
            {
                TextBox           NameTextBox        = (TextBox)e.Item.FindControl("NewNameTextBox");
                BrandCheckBoxList BrandsCheckBoxList = (BrandCheckBoxList)e.Item.FindControl("NewBrandsCheckBoxList");
                TextBox           DomainTextBox      = (TextBox)e.Item.FindControl("NewDomainTextBox");
                CheckBox          InternalCheckBox   = (CheckBox)e.Item.FindControl("NewInternalCheckBox");

                try
                {
                    Company company = Company.New();

                    company.Name            = NameTextBox.Text;
                    company.Domain          = DomainTextBox.Text;
                    company.IsInternal      = InternalCheckBox.Checked;
                    company.CreateDate      = DateTime.Now;
                    company.CreatedByUserId = CurrentUser.UserId.GetValueOrDefault();

                    AddBrandsToCompany(company, BrandsCheckBoxList);

                    CompanyManager.SaveCompany(company);

                    AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.AddCompany, string.Format("Added Approved Company: {0}, CompanyId: {1}", company.Name, company.CompanyId));

                    ResetGridState();
                    MessageLabel1.SetSuccessMessage("Company added successfully");
                }
                catch (InvalidCompanyException iacex)
                {
                    MessageLabel1.SetErrorMessage("Unable to add company", iacex.Errors);
                }
            }
        }
        protected override void Grid_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            int               id                 = Convert.ToInt32(e.CommandArgument);
            TextBox           NameTextBox        = (TextBox)e.Item.FindControl("NameTextBox");
            BrandCheckBoxList BrandsCheckBoxList = (BrandCheckBoxList)e.Item.FindControl("BrandsCheckBoxList");
            TextBox           DomainTextBox      = (TextBox)e.Item.FindControl("DomainTextBox");
            CheckBox          InternalCheckBox   = (CheckBox)e.Item.FindControl("InternalCheckBox");

            try
            {
                Company company = Company.Get(id);

                company.Name       = NameTextBox.Text;
                company.Domain     = DomainTextBox.Text;
                company.IsInternal = InternalCheckBox.Checked;

                AddBrandsToCompany(company, BrandsCheckBoxList);

                CompanyManager.SaveCompany(company);

                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ModifyCompany, string.Format("Modified Approved Company: {0}, CompanyId: {1}", company.Name, company.CompanyId));

                ResetGridState();
                MessageLabel1.SetSuccessMessage("Company updated successfully");
            }
            catch (InvalidCompanyException iacex)
            {
                MessageLabel1.SetErrorMessage("Unable to save company", iacex.Message);
            }
        }
Beispiel #4
0
        protected void UpdateAccountExpiryDateLinkButton_Click(object sender, EventArgs e)
        {
            // Get the user
            int  userId = GetRequiredQueryStringParameter("UserId", "UserList.aspx");
            User user   = Data.User.Get(userId);

            // Get the expiry date
            DateTime expiryDate = user.GetAccountExpiryDate();

            // Update it, if the user has an expiry date (ie. is non expiring)
            if (expiryDate < DateTime.MaxValue)
            {
                DateTime dt            = (expiryDate < DateTime.Now) ? DateTime.Now : expiryDate;
                DateTime newExpiryDate = dt.AddDays(UserManager.AccountExpiryDays);

                // Also approve user
                user.UserStatus = UserStatus.Approved;

                // Update user
                user.AccountExpiryDate = newExpiryDate;
                Data.User.Update(user);

                // Update UI
                DisplayUserAccountExpiryDate(user);
                MessageLabel1.SetSuccessMessage(string.Format("account expiry date updated to: {0}", newExpiryDate.ToString(Global.DateTimeFormat)));

                // Update audit log
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ModifyUser, string.Format("Updated {0}'s (Userid: {1}) account expiry date to: {2}", user.FullName, user.UserId, newExpiryDate.ToString("dd MMM yyyy HH:mm")));
            }
            else
            {
                MessageLabel1.SetErrorMessage("account never expires, expiry date not updated");
            }
        }
        protected override void Grid_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "add")
            {
                TextBox  NewNameTextBox       = (TextBox)e.Item.FindControl("NewNameTextBox");
                CheckBox NewIsVisibleCheckBox = (CheckBox)e.Item.FindControl("NewIsVisibleCheckBox");

                try
                {
                    AssetType assetType = AssetType.New();
                    assetType.Name      = NewNameTextBox.Text.Trim();
                    assetType.IsVisible = NewIsVisibleCheckBox.Checked;
                    AssetTypeManager.SaveAssetType(assetType);

                    AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.AddAssetType, string.Format("Added Asset Type: {0}, AssetTypeId: {1}", assetType.Name, assetType.AssetTypeId));

                    ResetGridState();
                    MessageLabel1.SetSuccessMessage("Asset type added successfully");
                }
                catch (InvalidAssetTypeException imtex)
                {
                    MessageLabel1.SetErrorMessage("Unable to add asset type", imtex.Errors);
                    BindGrid(CurrentPage);
                }
            }
        }
Beispiel #6
0
        protected void ReassignButton_Click(object sender, EventArgs e)
        {
            AssetFinder finder = new AssetFinder();

            finder.AssetIdList.Add(0);
            finder.AssetIdList.AddRange(AssetIdList);
            List <Asset> assetList = Asset.FindMany(finder);

            foreach (Asset asset in assetList)
            {
                // Update internal permissions
                asset.InternalUsers_HideFromUsers            = (InternalUsersRestrictionsRadioButtonList.SelectedValue == "NotVisible");
                asset.InternalUsers_DownloadApprovalRequired = (InternalUsersRestrictionsRadioButtonList.SelectedValue == "ApprovalRequired");

                // Update external permissions
                asset.ExternalUsers_HideFromUsers            = (ExternalUsersRestrictionsRadioButtonList.SelectedValue == "NotVisible");
                asset.ExternalUsers_DownloadApprovalRequired = (ExternalUsersRestrictionsRadioButtonList.SelectedValue == "ApprovalRequired");

                // Save changes back to DB
                Asset.Update(asset);

                // Update log
                AuditLogManager.LogAssetAction(asset, CurrentUser, AuditAssetAction.SavedAsset, "Permissions changed via bulk permissions change tool");
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.EditAsset, "Permissions changed via bulk permissions change tool");
            }

            const string returnUrl = "AssetList.aspx?PostAction=BulkAssetPermissionChangeSuccessful";

            Response.Redirect(returnUrl);
        }
Beispiel #7
0
        protected void UpdateDefaultButton_Click(object sender, EventArgs e)
        {
            foreach (DataGridItem dgi in AssetFilePathsDataGrid.Items)
            {
                HiddenField AssetFilePathIdHiddenField = (HiddenField)dgi.FindControl("AssetFilePathIdHiddenField");
                RadioButton IsDefaultRadioButton       = (RadioButton)dgi.FindControl("IsDefaultRadioButton");

                if (IsDefaultRadioButton.Checked)
                {
                    int assetFilePathId = NumericUtils.ParseInt32(AssetFilePathIdHiddenField.Value, 0);

                    try
                    {
                        AssetFilePathManager.SetDefault(assetFilePathId);
                        AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ChangeDefaultFilepath, string.Format("Changed default file path to AssetFilePathId: {0}", assetFilePathId));

                        MessageLabel1.SetSuccessMessage("Default asset file path updated successfully");
                    }
                    catch (InvalidAssetFilePathException ifpx)
                    {
                        MessageLabel1.SetErrorMessage("Unable to change default path", ifpx.Errors);
                    }

                    break;
                }
            }
        }
Beispiel #8
0
        protected void AssetFilePathsDataGrid_OnItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "add")
            {
                try
                {
                    TextBox NewFilePathTextBox = (TextBox)e.Item.FindControl("NewFilePathTextBox");
                    string  path = NewFilePathTextBox.Text;

                    AssetFilePathManager.CreateNew(path);
                    AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.AddFilepath, string.Format("Added file path: {0}", path));

                    MessageLabel1.SetSuccessMessage("Asset file path added successfully");

                    BindList();
                }
                catch (InvalidAssetFilePathException iafpex)
                {
                    ErrorList errors = iafpex.Errors;

                    if (errors.Count == 1)
                    {
                        MessageLabel1.SetErrorMessage(errors[0].ToString());
                    }
                    else
                    {
                        MessageLabel1.SetErrorMessage("Unable to add new file path", errors);
                    }
                }
            }
        }
Beispiel #9
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            AssetTypeFileExtension atfe = SaveATFE();

            if (!atfe.IsNull)
            {
                AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.ModifyFileExtension, string.Format("File Extension: {0}, ID: {1}", atfe.Extension, atfe.AssetTypeFileExtensionId));
            }
        }
        protected override void Grid_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);

            IpAddress.Delete(id);
            AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteIpAddress, string.Format("Deleted Ip Address with IpAddressId: {0}", id));

            BindGrid(CurrentPage);
            MessageLabel1.SetSuccessMessage("IP Address deleted successfully");
        }
Beispiel #11
0
        protected void DuplicateButton_Click(object sender, EventArgs e)
        {
            AssetTypeFileExtension atfe = SaveATFE();

            if (!atfe.IsNull)
            {
                string ext = atfe.Extension;
                AssetTypeFileExtensionManager.Duplicate(atfe);
                AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DuplicateFileExtension, string.Format("File Extension: {0} (temp ext: {1}), ID: {2}", ext, atfe.Extension, atfe.AssetTypeFileExtensionId));
                Response.Redirect("ManageFileExtensionsForm.aspx?Action=Duplicate&AssetTypeFileExtensionId=" + atfe.AssetTypeFileExtensionId);
            }
        }
        protected override void Grid_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);

            try
            {
                CompanyManager.DeleteCompany(id);

                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteCompany, string.Format("Deleted Company with CompanyId: {0}", id));
                MessageLabel1.SetSuccessMessage("Company deleted successfully");

                BindGrid(CurrentPage);
            }
            catch (Exception ex)
            {
                MessageLabel1.SetErrorMessage("Error deleting company: " + ex.Message);
            }
        }
        protected void SaveChangesButton_Click(object sender, EventArgs e)
        {
            // Get the user data from the database
            // This is to ensure it is up-to-date, rather than just using the current user in
            // session in case the user has been updated by an admin since the user logged in.
            User user = Data.User.Get(CurrentUser.UserId);

            // Initialise user from posted values
            user.FirstName = UserDetailsForm1.FirstName;
            user.LastName  = UserDetailsForm1.LastName;
            user.Email     = UserDetailsForm1.Email;
            user.SetConfirmPassword(UserDetailsForm1.ConfirmPassword);
            user.IsEmployee     = UserDetailsForm1.IsStaffUser;
            user.CompanyName    = UserDetailsForm1.CompanyName;
            user.PrimaryBrandId = UserDetailsForm1.BrandId;
            user.CountryId      = UserDetailsForm1.CountryId;
            user.PhoneNumber    = UserDetailsForm1.PhoneNumber;
            user.MobileNumber   = UserDetailsForm1.MobileNumber;

            if (!StringUtils.IsBlank(UserDetailsForm1.Password))
            {
                user.SetPassword(UserDetailsForm1.Password);

                if (user.PasswordChanged)
                {
                    user.PasswordExpiryDate = DateTime.Now.AddDays(UserManager.PasswordExpiryDays);
                }
            }

            try
            {
                UserManager.Update(user);
                SessionInfo.Current.User = user;

                AuditLogManager.LogUserAction(user, AuditUserAction.AccountUpdate, "Profile updated successfully.");

                FeedbackLabel1.SetSuccessMessage("Your profile has been updated");
            }
            catch (InvalidUserException iuex)
            {
                FeedbackLabel1.SetErrorMessage("the following errors occured:", iuex.Errors);
            }
        }
Beispiel #14
0
        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            // Get the ID of the extension to be deleted
            int id = WebUtils.GetIntRequestParam("AssetTypeFileExtensionId", 0);

            // Get the file extension to be deleted
            AssetTypeFileExtension atfe = AssetTypeFileExtension.Get(id);

            // Now actually delete it
            AssetTypeFileExtensionManager.Delete(atfe);

            // Update audit log
            AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DeleteFileExtension, string.Format("File Extension: {0}, ID: {1}", atfe.Extension, atfe.AssetTypeFileExtensionId));

            // Update UI
            FormPanel.Visible    = false;
            SuccessPanel.Visible = true;
            MessageLabel2.SetSuccessMessage("File extension deleted successfully");
        }
        protected override void Grid_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                int       assetTypeId = Convert.ToInt32(e.CommandArgument);
                AssetType assetType   = AssetTypeCache.Instance.GetById(assetTypeId);

                AssetTypeManager.DeleteAssetType(assetTypeId);
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteAssetType, string.Format("Deleted Asset Type: {0}, AssetTypeId: {1}", assetType.Name, assetTypeId));

                MessageLabel1.SetSuccessMessage("Asset type deleted successfully");
            }
            catch (SystemException sysex)
            {
                MessageLabel1.SetErrorMessage(sysex.Message);
            }

            BindGrid(CurrentPage);
        }
Beispiel #16
0
        public override void ProcessRequest()
        {
            int assetFileId = GetIdFromFilename();
            int assetId     = WebUtils.GetIntRequestParam("AssetId", 0);

            if (assetFileId <= 0)
            {
                throw new SystemException("Invalid attached file id: " + assetFileId);
            }

            if (assetId <= 0)
            {
                throw new SystemException("Invalid asset id: " + assetId);
            }

            // Get the asset file
            AssetFile assetFile = AssetFile.Get(assetFileId);

            if (assetFile.AssetId != assetId)
            {
                throw new SystemException("Asset mismatch");
            }

            if (assetFile.IsNull)
            {
                throw new SystemException("Asset file not found");
            }

            if (assetFile.Asset.RestrictAttachedFiles && !EntitySecurityManager.CanUserDownloadAsset(SessionInfo.Current.User, assetFile.Asset))
            {
                throw new SystemException("Access denied");
            }

            // Log the download
            string notes = string.Format("Downloaded file: {0}", assetFile.Filename);

            AuditLogManager.LogAssetAction(assetFile.AssetId, SessionInfo.Current.User, AuditAssetAction.DownloadedAttachedFile, notes);
            AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DownloadAttachedFile, notes);

            // Send the file
            SiteUtils.SendAttachedFile(assetFile);
        }
        protected override void Grid_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            TextBox EntityTextBox = (TextBox)e.Item.FindControl("EntityTextBox");
            int     id            = Convert.ToInt32(e.CommandArgument);

            try
            {
                string ipAddress = EntityTextBox.Text;

                IpAddressManager.Update(id, ipAddress);
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ModifyIpAddress, string.Format("Modified Ip Address: {0}, IpAddressId: {1}", id, ipAddress));

                ResetGridState();
                MessageLabel1.SetSuccessMessage("IP Address updated successfully");
            }
            catch (InvalidIpAddressException ex)
            {
                MessageLabel1.SetErrorMessage(ex.Message);
            }
        }
        protected override void Grid_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "add")
            {
                TextBox NewEntityTextBox = (TextBox)e.Item.FindControl("NewEntityTextBox");
                string  ipAddress        = NewEntityTextBox.Text.Trim();

                try
                {
                    IpAddress ipa = IpAddressManager.Add(ipAddress);
                    AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.AddIpAddress, string.Format("Added Ip Address: {0}, IpAddressId: {1}", ipa.IpAddressValue, ipa.IpAddressId));

                    ResetGridState();
                    MessageLabel1.SetSuccessMessage("IP Address added successfully");
                }
                catch (InvalidIpAddressException ex)
                {
                    MessageLabel1.SetErrorMessage(ex.Message);
                }
            }
        }
        protected void RenewButton_Click(object sender, EventArgs e)
        {
            CheckAssetList();

            int months = Convert.ToInt32(ExtendByMonthsDropDownList.SelectedValue);

            AssetFinder finder = new AssetFinder();

            finder.AssetIdList.Add(0);
            finder.AssetIdList.AddRange(AssetIdList);
            List <Asset> assetList = Asset.FindMany(finder);

            foreach (Asset asset in assetList)
            {
                asset.ExpiryDate = asset.ExpiryDate.AddMonths(months);
                Asset.Update(asset);
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.EditAsset, "Updated expiry date to " + asset.ExpiryDate.ToString(Global.DateFormat));
            }

            Response.Redirect("AssetList.aspx?PostAction=BulkAssetRenewalSuccessful");
        }
Beispiel #20
0
        protected void DeleteButton_Command(object sender, CommandEventArgs e)
        {
            try
            {
                // Get brand Id
                int brandId = NumericUtils.ParseInt32(e.CommandArgument.ToString(), 0);

                // Get the brand
                Brand brand = BrandCache.Instance.GetById(brandId);

                // Delete brand from database
                BrandManager.Delete(brandId);

                // Update log
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteBrand, string.Format("Deleted brand: {0}. Brand ID: {1}", brand.Name, brand.BrandId));

                // Delete brand folder.
                string brandFolderPath = Server.MapPath(string.Format("~/Brands/Brand_{0}/", brandId));

                if (Directory.Exists(brandFolderPath))
                {
                    Directory.Delete(brandFolderPath, true);
                    m_Logger.InfoFormat("Deleted brand folder: {0}", brandFolderPath);
                }
                else
                {
                    m_Logger.InfoFormat("Brand folder not deleted, does not exist: {0}", brandFolderPath);
                }

                // Redirect back to brand list
                Response.Redirect("ManageBrands.aspx?message=BrandDeletedSuccessfully");
            }
            catch (Exception ex)
            {
                MessageLabel1.SetErrorMessage("Error deleting brand", ex.Message);
            }
        }
        protected void DelegateButton_Click(object sender, EventArgs e)
        {
            CheckAssetList();

            string email = EmailTextBox.Text;

            if (StringUtils.IsBlank(email))
            {
                MessageLabel1.SetErrorMessage("Email address is required");
                return;
            }

            User user = Data.User.GetByEmail(email);

            if (user.IsNull)
            {
                MessageLabel1.SetErrorMessage("Email address does not belong to a registered user");
                return;
            }

            AssetFinder finder = new AssetFinder();

            finder.AssetIdList.Add(0);
            finder.AssetIdList.AddRange(AssetIdList);
            List <Asset> assetList = Asset.FindMany(finder);

            foreach (Asset asset in assetList)
            {
                asset.UploadedByUserId = user.UserId.GetValueOrDefault();
                asset.ContactEmail     = user.Email;
                Asset.Update(asset);
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.EditAsset, "Delegated asset to " + asset.ContactEmail);
            }

            Response.Redirect("AssetList.aspx?PostAction=BulkAssetDelegationSuccessful");
        }
        protected override void Grid_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            int      assetTypeId       = Convert.ToInt32(e.CommandArgument);
            TextBox  NameTextBox       = (TextBox)e.Item.FindControl("NameTextBox");
            CheckBox IsVisibleCheckBox = (CheckBox)e.Item.FindControl("IsVisibleCheckBox");

            try
            {
                AssetType assetType = AssetType.Get(assetTypeId);
                assetType.Name      = NameTextBox.Text.Trim();
                assetType.IsVisible = IsVisibleCheckBox.Checked;
                AssetTypeManager.SaveAssetType(assetType);

                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ModifyAssetType, string.Format("Modified Asset Type: {0}, AssetTypeId: {1}", assetType.Name, assetType.AssetTypeId));

                ResetGridState();
                MessageLabel1.SetSuccessMessage("Asset type updated successfully");
            }
            catch (InvalidAssetTypeException imtex)
            {
                MessageLabel1.SetErrorMessage("Unable to update asset type", imtex.Message);
                BindGrid(CurrentPage);
            }
        }
        private void ZipSelectedAssetsAndSend()
        {
            int?currentOrderId = CurrentOrder.OrderId;

            m_Logger.DebugFormat("User: {0} has selected assets to zip from order: {1}", CurrentUser.FullName, currentOrderId);

            // The folder where the zip file should be stored
            string sessionFolder = SessionHelper.GetForCurrentSession().CreateSessionTempFolder();

            // Unique filename strings
            string dateString = DateTime.Now.ToString("yyyyMMddHHmmss");
            string guid       = GeneralUtils.GetGuid();

            // The actual filename of the zip file on disk
            string outputFilename = string.Format("assets_from_order_{0}_{1}_{2}.zip", currentOrderId, dateString, guid);

            // The full path to the zip file on disk
            string outputPath = Path.Combine(sessionFolder, outputFilename);

            m_Logger.DebugFormat("Zip file will be stored in: {0}", outputPath);

            using (ZipOutputStream zos = new ZipOutputStream(File.Create(outputPath)))
            {
                try
                {
                    zos.SetLevel(9);
                    zos.SetComment(string.Format("Selected assets from order {0} on {1}", CurrentOrder.OrderId, CurrentOrder.OrderDate.ToString(Global.DateFormat)));

                    foreach (OrderItem orderItem in CurrentOrder.OrderItemList)
                    {
                        if (Response.IsClientConnected && ShouldDownload(orderItem))
                        {
                            // Get the asset
                            Asset asset = orderItem.Asset;

                            // Get the path to the asset file
                            AssetFileInfo info = new AssetFileInfo(asset);

                            // Get actual path
                            string path = info.FilePath;

                            // Check if a different image format is being requested
                            if (AssetTypeChecker.IsImage(asset.FileExtension))
                            {
                                SelectedOrderItem soi = SelectedOrderItems.Get(orderItem.OrderItemId.GetValueOrDefault());
                                path = AssetImageManager.GetResizedAssetImage(asset, soi.AssetImageSizeId, soi.DownloadFormat, true);
                            }

                            // Filename
                            string filename = string.Concat(Path.GetFileNameWithoutExtension(asset.Filename), "_", asset.FileReference, (Path.GetExtension(path) ?? ".unknown").ToLower());

                            // Add the file to the generated zip
                            AddFileToZipOutputStream(filename, path, zos);

                            // Log this download for reporting
                            AuditLogManager.LogAssetAction(asset, CurrentUser, AuditAssetAction.DownloadedAssetFile);
                            AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DownloadAsset, string.Format("Downloaded AssetId: {0} as part of zipped download for OrderId: {1}", asset.AssetId, CurrentOrder.OrderId));
                        }
                    }
                }
                finally
                {
                    zos.Finish();
                    zos.Close();
                }
            }

            string downloadUrl = string.Format("~/GetZipDownload.ashx?OrderId={0}&d={1}&guid={2}", currentOrderId, dateString, guid);

            Response.Redirect(downloadUrl);
        }
        public override void ProcessRequest()
        {
            // Get querystring values
            int            assetId          = GetIdFromFilename();
            int            assetImageSizeId = WebUtils.GetIntRequestParam("assetImageSizeId", 0);
            DownloadFormat downloadFormat   = GeneralUtils.ParseEnum(WebUtils.GetRequestParam("AssetImageFormat"), DownloadFormat.Original);
            bool           logDownload      = (WebUtils.GetIntRequestParam("logDownload", 1) == 1);
            bool           original         = (WebUtils.GetIntRequestParam("original", 0) == 1);

            // Downloads should ALWAYS be logged from normal users, regardless of the querystring
            if (SessionInfo.Current.User.UserRole == UserRole.Normal)
            {
                logDownload = true;
            }

            // Ensure asset id is specified
            if (assetId == 0)
            {
                throw new HttpException(500, "Invalid asset id");
            }

            // Get asset
            Asset asset = Asset.Get(assetId);

            // Make sure asset is valid
            if (asset.IsNull)
            {
                Context.Response.Redirect("~/Errors/AssetMissing.htm");
                return;
            }

            // Check if user can download asset
            bool isAuthorised = EntitySecurityManager.CanUserDownloadAsset(SessionInfo.Current.User, asset);

            if (!isAuthorised)
            {
                throw new SecurityException("Access denied");
            }

            // Get the asset file info
            AssetFileInfo info = new AssetFileInfo(asset);

            // Ensure file exists
            if (!info.FileExists)
            {
                Context.Response.Redirect("~/Errors/AssetFileMissing.htm");
                return;
            }

            // Asset file path
            string path = info.FilePath;

            // Update the audit history
            if (logDownload)
            {
                AuditLogManager.LogAssetAction(assetId, SessionInfo.Current.User, AuditAssetAction.DownloadedAssetFile);
                AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DownloadAsset, string.Format("Downloaded asset with AssetId: {0}", assetId));
            }

            DownloadAsset(asset, path, original, downloadFormat, assetImageSizeId);
        }
        public override void ProcessRequest()
        {
            if (!SessionInfo.Current.User.IsNull)
            {
                //if valid user then process request
                //using normal AssetFileHandler
                base.ProcessRequest();
            }
            else
            {
                // Get querystring values
                int            assetId          = GetIdFromFilename();
                int            assetImageSizeId = WebUtils.GetIntRequestParam("assetImageSizeId", 0);
                DownloadFormat downloadFormat   = GeneralUtils.ParseEnum(WebUtils.GetRequestParam("AssetImageFormat"), DownloadFormat.Original);
                bool           original         = (WebUtils.GetIntRequestParam("original", 0) == 1);
                int            lightboxSentId   = WebUtils.GetIntRequestParam("lsid", 0);
                int            senderId         = WebUtils.GetIntRequestParam("suid", 0);
                string         ticks            = WebUtils.GetRequestParam("dst", string.Empty);

                // Ensure asset id is specified
                if (assetId == 0 || lightboxSentId == 0)
                {
                    InvalidRequest();
                    return;
                }


                // Get the lightbox
                LightboxSent lightboxSent = LightboxSent.Get(lightboxSentId);

                //check that it's a valid lightboxsent object
                if (lightboxSent.IsNull)
                {
                    InvalidRequest();
                    return;
                }


                // Check posted data - ensure that the sender id and ticks match (ie. to ensure user is not messing with the querystring)
                if (!lightboxSent.SenderId.Equals(senderId) || ticks.Length < 6 || !lightboxSent.DateSent.Ticks.ToString().Substring(0, 6).Equals(ticks.Substring(0, 6)))
                {
                    InvalidRequest();
                    return;
                }


                // Make sure sender is a super user
                if (lightboxSent.Sender.UserRole != UserRole.SuperAdministrator)
                {
                    InvalidRequest();
                    return;
                }


                //verify that lightbox has download links enabled
                if (!lightboxSent.DownloadLinks.GetValueOrDefault(false))
                {
                    InvalidRequest();
                    return;
                }


                //check that asset exists in the lightbox being sent
                LightboxAssetFinder finder = new LightboxAssetFinder {
                    LightboxId = lightboxSent.LightboxId, AssetId = assetId
                };
                LightboxAsset lightboxAsset = LightboxAsset.FindOne(finder);

                if (lightboxAsset.IsNull)
                {
                    InvalidRequest();
                    return;
                }


                // Get the asset file info
                AssetFileInfo info = new AssetFileInfo(lightboxAsset.Asset);

                // Ensure file exists
                if (!info.FileExists)
                {
                    InvalidRequest();
                    return;
                }

                // Asset file path
                string path = info.FilePath;

                // Always update the audit history for external downloads
                AuditLogManager.LogAssetAction(assetId, lightboxSent.Sender, AuditAssetAction.DownloadedAssetFile);
                AuditLogManager.LogUserAction(lightboxSent.Sender, AuditUserAction.DownloadAssetFromContactSheet, string.Format("Downloaded asset {0} via contact sheet, sent by: {1} download by: {2}", assetId, lightboxSent.Sender.FullName, lightboxSent.RecipientEmail));

                DownloadAsset(lightboxAsset.Asset, path, original, downloadFormat, assetImageSizeId);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (CurrentAsset.IsNull)
                {
                    Page.ClientScript.RegisterClientScriptBlock(GetType(), "close", "self.close();", true);
                    return;
                }

                // Get the asset ID
                int assetId = CurrentAsset.AssetId.GetValueOrDefault();

                // Get the asset type info
                AssetTypeInfo assetType = AssetTypeInfo.Get(CurrentAsset.FileExtension);


                //-----------------------------------------------------------------------------------------------------
                // Set up UI elements based on asset type
                //-----------------------------------------------------------------------------------------------------
                OrientationRow.Visible = assetType.HasOrientation;
                DurationRow.Visible    = assetType.HasDuration;
                DimensionsRow.Visible  = assetType.HasDimensions;

                //-----------------------------------------------------------------------------------------------------
                // Set up asset breadcrumbs based on category
                //-----------------------------------------------------------------------------------------------------
                AssetBreadcrumb.CategoryId = CurrentAsset.PrimaryCategoryId;

                //-----------------------------------------------------------------------------------------------------
                // Update the audit log
                //-----------------------------------------------------------------------------------------------------
                AuditLogManager.LogAssetAction(assetId, CurrentUser, AuditAssetAction.ViewedAssetDetail);
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ViewedAssetDetail, string.Format("Viewed asset detail for AssetId: {0}", assetId));

                //-----------------------------------------------------------------------------------------------------
                // Initialise the asset preview and buttons
                //-----------------------------------------------------------------------------------------------------
                AssetPreview1.Asset = CurrentAsset;
                AssetButtons1.Initialise(CurrentAsset);

                //-----------------------------------------------------------------------------------------------------
                // Bind categories list
                //-----------------------------------------------------------------------------------------------------
                AssetCategoriesContainer.Visible = (CurrentAsset.CategoryList.Count > 0);
                CategoriesRepeater.DataSource    = CurrentAsset.CategoryList;
                CategoriesRepeater.DataBind();

                //-----------------------------------------------------------------------------------------------------
                // Bind attached files
                //-----------------------------------------------------------------------------------------------------
                List <AssetFile> attachedFiles = CurrentAsset.GetAttachedFiles();
                AttachedFilesRow.Visible         = (attachedFiles.Count > 0);
                AttachedFilesDataList.DataSource = attachedFiles;
                AttachedFilesDataList.DataBind();

                //-----------------------------------------------------------------------------------------------------
                // Bind linked assets
                //-----------------------------------------------------------------------------------------------------
                LinkedAssetsRow.Visible         = (CurrentAsset.ReciprocalLinkedAssetList.Count > 0);
                LinkedAssetsRepeater.DataSource = CurrentAsset.ReciprocalLinkedAssetList;
                LinkedAssetsRepeater.DataBind();

                //-----------------------------------------------------------------------------------------------------
                // Set up the file type icon
                //-----------------------------------------------------------------------------------------------------
                FileTypeIconImage.ImageUrl = SiteUtils.GetFileTypeImageUrl(CurrentAsset.FileExtension);
                FileTypeIconImage.ToolTip  = CurrentAsset.Filename;

                //-----------------------------------------------------------------------------------------------------
                // Brand controlled metadata
                //-----------------------------------------------------------------------------------------------------
                AssetIdCell.InnerText      = CurrentAsset.AssetId.ToString();
                DateUploadedLabel.Text     = CurrentAsset.UploadDate.ToString(Global.DateFormat);
                FilenameCell.InnerText     = FileUtils.GetTruncatedFilename(CurrentAsset.Filename, 25);
                FileHashLabel.Text         = StringUtils.IsBlank(CurrentAsset.FileHash) ? "[Not Available]" : CurrentAsset.FileHash.Substring(0, 15) + " ...";
                FileHashLabel.ToolTip      = CurrentAsset.FileHash;
                FilesizeCell.InnerText     = FileUtils.FriendlyFileSize(CurrentAsset.FileSize);
                AssetTypeCell.InnerText    = CurrentAsset.AssetType.Name;
                DateProducedCell.InnerText = CurrentAsset.GetProductionDate();
                OriginatorCell.InnerText   = CurrentAsset.Originator;
                TitleCell.InnerText        = CurrentAsset.Title;
                ProjectCodeCell.InnerText  = CurrentAsset.ProjectCode;
                BrandCell.InnerText        = CurrentAsset.Brand.Name;

                AssetDescriptionContainer.InnerHtml = SiteUtils.ConvertTextToHtml(CurrentAsset.Description);
                AdditionalKeywordsCell.InnerText    = CurrentAsset.Keywords;
                CopyrightOwnerCell.InnerHtml        = StringUtils.IgnoreCaseCompare(CurrentAsset.CopyrightOwner, WebsiteBrandManager.GetBrand().OrganisationName) ? "(c) " + CurrentAsset.CopyrightOwner : CurrentAsset.CopyrightOwner;
                UsageRestrictionsCell.InnerHtml     = CurrentAsset.UsageRestrictions;
                ContactEmailHyperLink.EmailAddress  = CurrentAsset.ContactEmail;
                PublicationDateCell.InnerText       = CurrentAsset.PublishDate.ToString(Global.DateFormat);
                ExpiryDateCell.InnerText            = CurrentAsset.ExpiryDate.ToString(Global.DateFormat);

                // order metas according to their meta settings asset detail order numbers
                TrBrand.Attributes["class"]              = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.BRAND).AssetDetailOrderNum.ToString();
                TrAssetType.Attributes["class"]          = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.ASSET_TYPE).AssetDetailOrderNum.ToString();
                TrFilename.Attributes["class"]           = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.FILENAME).AssetDetailOrderNum.ToString();
                TrFileSize.Attributes["class"]           = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.FILESIZE).AssetDetailOrderNum.ToString();
                TrFileHash.Attributes["class"]           = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.FILEHASH).AssetDetailOrderNum.ToString();
                TrDateUploaded.Attributes["class"]       = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.DATE_UPLOADED).AssetDetailOrderNum.ToString();
                TrTitle.Attributes["class"]              = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.TITLE).AssetDetailOrderNum.ToString();
                TrProjectCode.Attributes["class"]        = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.PROJECT_CODE).AssetDetailOrderNum.ToString();
                TrOriginator.Attributes["class"]         = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.ORIGINATOR).AssetDetailOrderNum.ToString();
                TrDateProduced.Attributes["class"]       = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.DATE_PRODUCED).AssetDetailOrderNum.ToString();
                TrContactEmail.Attributes["class"]       = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.CONTACT_EMAIL).AssetDetailOrderNum.ToString();
                TrCopyrightOwner.Attributes["class"]     = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.COPYRIGHT_OWNER).AssetDetailOrderNum.ToString();
                TrRestrictedDownload.Attributes["class"] = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.DOWNLOAD_RESTRICTIONS).AssetDetailOrderNum.ToString();
                TrUsageRestrictions.Attributes["class"]  = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.USAGE_RESTRICTIONS).AssetDetailOrderNum.ToString();
                TrAdditionalKeywords.Attributes["class"] = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.ADDITIONAL_KEYWORDS).AssetDetailOrderNum.ToString();
                TrPublicationDate.Attributes["class"]    = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.PUBLICATION_DATE).AssetDetailOrderNum.ToString();
                TrExpiryDate.Attributes["class"]         = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.EXPIRY_DATE).AssetDetailOrderNum.ToString();
                LinkedAssetsRow.Attributes["class"]      = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.LINKED_ASSETS).AssetDetailOrderNum.ToString();
                AttachedFilesRow.Attributes["class"]     = CurrentAsset.Brand.GetMetadataSetting(BrandMetadataSettings.ATTACHED_FILES).AssetDetailOrderNum.ToString();

                var allSettings = BrandMetadataSettingManager.GetCustomMetadataSettings(CurrentAsset.Brand.BrandId.GetValueOrDefault());
                var lastNum     = allSettings.OrderBy(s => s.AssetDetailOrderNum).LastOrDefault().AssetDetailOrderNum;

                DimensionsRow.Attributes["class"]  = (lastNum++).ToString();
                DurationRow.Attributes["class"]    = (lastNum++).ToString();
                OrientationRow.Attributes["class"] = (lastNum++).ToString();

                //-----------------------------------------------------------------------------------------------------
                // Other stuff
                //-----------------------------------------------------------------------------------------------------
                OrientationCell.InnerText        = CurrentAsset.GetOrientation();
                DurationCell.InnerText           = SiteUtils.FriendlyDuration(CurrentAsset.Duration.GetValueOrDefault(), "Unknown");
                DimensionsCell.InnerText         = CurrentAsset.GetDimensions();
                RestrictedDownloadCell.InnerText = EntitySecurityManager.IsAssetRestricted(CurrentUser, CurrentAsset) ? "Yes" : "No";

                // Only show file metadata link if we have some available
                // ShowFileMeta data returns true if there is File metadata to display.
                FileMetadataLinkButton.Visible  = ShowFileMetadata();
                FileMetadataLinkDivider.Visible = FileMetadataLinkButton.Visible;

                //-----------------------------------------------------------------------------------------------------
                // Setup security in UI: Only display the edit and status links of the user has access
                //-----------------------------------------------------------------------------------------------------
                if (EntitySecurityManager.CanManageAsset(CurrentUser, CurrentAsset))
                {
                    string editUrl = "~/Admin/Assets/AssetForm.aspx?assetId=" + CurrentAsset.AssetId;
                    EditHyperLink.NavigateUrl = editUrl;
                    EditHyperLink.Attributes.Add("onClick", string.Format("GetParentWindow().location.href='{0}';self.close();return false;", ResolveUrl(editUrl)));

                    string statsUrl = "~/Admin/Reports/AssetStats.aspx?assetId=" + assetId;
                    StatsHyperLink.NavigateUrl = statsUrl;
                    StatsHyperLink.Attributes.Add("onClick", string.Format("GetParentWindow().location.href='{0}';self.close();return false;", ResolveUrl(statsUrl)));

                    string logHyperlink = "~/Admin/Reports/AssetAuditTrail.aspx?AssetId=" + CurrentAsset.AssetId;
                    LogHyperLink.NavigateUrl = logHyperlink;
                    LogHyperLink.Attributes.Add("onClick", string.Format("GetParentWindow().location.href='{0}';self.close();return false;", ResolveUrl(logHyperlink)));
                }
                else
                {
                    AssetLinksContainer.Visible = false;
                }

                //-----------------------------------------------------------------------------------------------------
                // Control access or AssetOrderHistory links.
                //-----------------------------------------------------------------------------------------------------
                if (!EntitySecurityManager.CanViewAssetOrderHistory(CurrentUser, CurrentAsset))
                {
                    // Get the asset order history, if there isn't any order history
                    // then hide the link.
                    // Set visiblity of order history link
                    OrderHistoryDivider.Visible    = false;
                    OrderHistoryLinkButton.Visible = false;
                }
                else
                {
                    // Get the asset order history, if there isn't any order history
                    // then hide the link.
                    if (!ShowOrderHistory())
                    {
                        // Set visiblity of order history link
                        OrderHistoryDivider.Visible    = false;
                        OrderHistoryLinkButton.Visible = false;
                    }
                }

                //-----------------------------------------------------------------------------------------------------
                // Populate blank cells
                //-----------------------------------------------------------------------------------------------------
                SiteUtils.PopulateBlankControl(AssetDescriptionContainer);
                SiteUtils.PopulateBlankControl(FilenameCell);
                SiteUtils.PopulateBlankControl(FilesizeCell);
                SiteUtils.PopulateBlankControl(TitleCell);
                SiteUtils.PopulateBlankControl(DurationCell);
                SiteUtils.PopulateBlankControl(ProjectCodeCell);
                SiteUtils.PopulateBlankControl(OriginatorCell);
                SiteUtils.PopulateBlankControl(DateProducedCell);
                SiteUtils.PopulateBlankControl(CopyrightOwnerCell);
                SiteUtils.PopulateBlankControl(OrientationCell);
                SiteUtils.PopulateBlankControl(UsageRestrictionsCell);
            }

            //sort metas on every request
            ClientScript.RegisterStartupScript(GetType(), "SortMetas2", "SortMetas();", true);

            //bind repeater on every request as otherwise labels stuff is lost
            MetadataRepeater.DataSource = BrandMetadataSettingManager.GetCustomMetadataSettings(CurrentAsset.BrandId);
            MetadataRepeater.DataBind();
        }
        protected void NextButton_Click(object sender, EventArgs e)
        {
            ErrorList errors = new ErrorList();

            if (StringUtils.IsBlank(FtpHostTextBox.Text))
            {
                errors.Add("Ftp host is required");
            }

            if (NumericUtils.ParseInt32(FtpPortTextBox.Text, 0) == 0)
            {
                errors.Add("Ftp host port must be a number");
            }

            if (StringUtils.IsBlank(FtpUsernameTextBox.Text))
            {
                errors.Add("Username is required");
            }

            if (errors.Count > 0)
            {
                FeedbackLabel1.SetErrorMessage("Please check the following and try again:", errors);
                return;
            }

            // List of files to upload
            List <FtpFile> assetFilePaths = new List <FtpFile>();

            // Get all of the order items in the current order
            foreach (OrderItem orderItem in SelectedOrder.OrderItemList)
            {
                // Get the order item id
                int orderItemId = orderItem.OrderItemId.GetValueOrDefault();

                // Check if the order item can be downloaded and is in the list of selected order items
                if (ViewOrders.CanDownload(orderItem) && SelectedOrderItems.Contains(orderItemId))
                {
                    // Get the asset
                    Asset asset = orderItem.Asset;

                    // Get the selected order item
                    SelectedOrderItem soi = SelectedOrderItems.Get(orderItemId);

                    // Initialise path and filename to FTP
                    string path, filename;

                    // Check if zip asset files is enabled and we're not doing any kind of transcoding.
                    // If so, we want to FTP the zipped asset file instead, so set the path and filename accordingly.
                    // However, if the zip file doesn't exist, then we want to FTP the original asset instead.

                    if (AssetFileManager.ZipAssetFiles && soi.AssetImageSizeId == 0)
                    {
                        // First get the path to the zipped asset file
                        ZippedAssetFileInfo zippedFileInfo = new ZippedAssetFileInfo(asset);

                        if (zippedFileInfo.FileExists)
                        {
                            // Ensure that a path was returned, and if so, set the filename accordingly
                            path     = zippedFileInfo.FilePath;
                            filename = Path.GetFileNameWithoutExtension(asset.Filename) + ".zip";
                        }
                        else
                        {
                            // Otherwise, the zip file doesn't exist, so get the path to the original
                            // asset file, and set the filename to the asset filename

                            AssetFileInfo info = new AssetFileInfo(asset);

                            path     = info.FilePath;
                            filename = asset.Filename;
                        }
                    }
                    else
                    {
                        // Get the file path to the asset
                        AssetFileInfo info = new AssetFileInfo(asset);
                        path = info.FilePath;

                        // For images, get the filepath to the resized image
                        if (AssetTypeChecker.IsImage(asset.FileExtension))
                        {
                            path = AssetImageManager.GetResizedAssetImage(asset, soi.AssetImageSizeId, soi.DownloadFormat, true);
                        }

                        // Construct the asset filename
                        filename = Path.GetFileNameWithoutExtension(asset.Filename) + Path.GetExtension(path);
                    }

                    // Add the file path to the list
                    FtpFile file = new FtpFile(path, filename);
                    assetFilePaths.Add(file);
                }
            }

            try
            {
                // Instantiate FTP downloader
                FtpDownloader ftpDownloader = new FtpDownloader
                {
                    BackgroundTransfer = true,
                    Host         = FtpHostTextBox.Text.Trim(),
                    Port         = NumericUtils.ParseInt32(FtpPortTextBox.Text, 0),
                    PassiveMode  = FtpPassiveModeCheckBox.Checked,
                    Username     = FtpUsernameTextBox.Text.Trim(),
                    Password     = FtpPasswordTextBox.Text.Trim(),
                    RemoteFolder = FtpRemoteFolderTextBox.Text.Trim(),
                    User         = CurrentUser
                };

                // Specify files to send to FTP server
                foreach (FtpFile file in assetFilePaths)
                {
                    ftpDownloader.Files.Add(file);
                }

                // Wire up events
                ftpDownloader.UploadComplete += new FtpDownloadCompleteEventHandler(NotifyEngine.FtpDownloadComplete);

                // Go do it!
                ftpDownloader.Go();

                // Log the assets as downloaded
                foreach (SelectedOrderItem soi in SelectedOrderItems)
                {
                    OrderItem orderItem = OrderItem.Get(soi.OrderItemId);
                    Asset     asset     = orderItem.Asset;

                    AuditLogManager.LogAssetAction(asset, CurrentUser, AuditAssetAction.DownloadedAssetFile);
                    AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DownloadAsset, string.Format("Downloaded AssetId: {0} as part of FTP download to: {1} for OrderId: {2}", asset.AssetId, ftpDownloader.Host, orderItem.OrderId));
                }

                // Lets cookie the settings as well, so we can pre-populate
                // the form when the user returns to download more assets
                CookieManager.SetValue("FtpHost", ftpDownloader.Host);
                CookieManager.SetValue("FtpPort", ftpDownloader.Port);
                CookieManager.SetValue("FtpPassiveMode", FtpPassiveModeCheckBox.Checked ? "1" : "0");
                CookieManager.SetValue("FtpUsername", ftpDownloader.Username);

                // Update UI
                FormPanel.Visible    = false;
                SuccessPanel.Visible = true;
            }
            catch (FtpDownloadException fdex)
            {
                // Remove the error code from the start of the error message
                string message = Regex.Replace(fdex.Message, @"(\d+\s-\s)", string.Empty);

                // Display the error to the user
                FeedbackLabel1.SetErrorMessage("Error downloading assets", message);

                // Log the error
                m_Logger.Warn(string.Format("Error downloading files to FTP. User: {0}, Host: {1}. Error: {2}", CurrentUser.FullName, FtpHostTextBox.Text, message), fdex);
            }
        }
Beispiel #28
0
        protected void ReassignButton_Click(object sender, EventArgs e)
        {
            CheckAssetList();

            int sourceId = SourceCategoryDropDownList.SelectedId;
            int targetId = TargetCategoryDropDownList.SelectedId;

            Category sourceCategory = CategoryCache.Instance.GetById(sourceId);
            Category targetCategory = CategoryCache.Instance.GetById(targetId);

            ErrorList errors = new ErrorList();

            if (sourceId <= 0)
            {
                errors.Add("Source category must be selected");
            }

            if (targetId <= 0)
            {
                errors.Add("Target category must be selected");
            }

            if (sourceId > 0 && sourceId == targetId)
            {
                errors.Add("Source and target categories cannot be the same");
            }

            if (errors.Count > 0)
            {
                MessageLabel1.SetErrorMessage("Error reassigning assets", errors);
                return;
            }

            if (targetCategory.IsNull)
            {
                MessageLabel1.SetErrorMessage("Invalid target category selected");
                return;
            }

            if (DeleteSourceCategoryCheckBox.Checked)
            {
                if (sourceCategory.IsRootCategory)
                {
                    MessageLabel1.SetErrorMessage("The source category cannot be deleted after reassignment as it is a root category");
                    return;
                }

                if (sourceCategory.SubCategories.Count > 0)
                {
                    MessageLabel1.SetErrorMessage("The source category cannot be deleted after reassignment as it contains subcategories");
                    return;
                }
            }

            AssetFinder finder = new AssetFinder();

            finder.AssetIdList.Add(0);
            finder.AssetIdList.AddRange(AssetIdList);
            List <Asset> assetList = Asset.FindMany(finder);

            foreach (Asset asset in assetList)
            {
                if (ClearExistingCategoriesCheckBox.Checked)
                {
                    asset.CategoryList.Clear();
                }

                asset.CategoryList.RemoveAll(c => c.CategoryId == sourceId);
                asset.CategoryList.Add(targetCategory);

                if (asset.CategoryList.Count == 1)
                {
                    asset.PrimaryCategoryId = asset.CategoryList[0].CategoryId.GetValueOrDefault();
                }

                Asset.Update(asset);
                Asset.SaveAssetMetadata(asset);

                AuditLogManager.LogAssetAction(asset, CurrentUser, AuditAssetAction.SavedAsset, string.Format("Assigned category '{0}' to asset to using bulk reassignment tool", targetCategory.Name));
                AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.EditAsset, string.Format("Bulk edited asset categories, assigned asset ID {0} to category '{1}'", asset.AssetId, targetCategory.Name));
            }

            string returnUrl = "AssetList.aspx?PostAction=BulkAssetCategoryUpdateSuccessful";

            if (DeleteSourceCategoryCheckBox.Checked)
            {
                try
                {
                    CategoryManager.DeleteCategory(sourceId, SessionInfo.Current.User);
                    returnUrl = ResolveUrl("~/Admin/Content/ManageCategories.aspx?BrandId=" + sourceCategory.BrandId + "&message=TransferComplete");
                }
                catch (Exception ex)
                {
                    m_Logger.Warn("Error deleting category: " + ex.Message, ex);
                }
            }
            else
            {
                CategoryManager.UpdateCategoryFullAssetCount(sourceId);
            }

            CategoryManager.UpdateCategoryFullAssetCount(targetId);

            Response.Redirect(returnUrl);
        }
Beispiel #29
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            // Get the user id
            int userId = WebUtils.GetIntRequestParam("UserId", 0);

            // Get the user
            User user = Data.User.Get(userId);

            if (user.IsNull)
            {
                // Get new user with default values set
                user = UserManager.GetNewUser();

                if (GeneratedPasswordPanel.Visible || (!NoWelcomeEmailCheckBox.Checked && StringUtils.IsBlank(PasswordTextBox.Text)))
                {
                    // Set password
                    string password = PasswordGenerator.GeneratePassword();
                    user.SetPassword(password);
                    user.SetConfirmPassword(password);
                }

                // Conditional settings for brand admins
                // (As they cannot set these values from the user interface)
                if (CurrentUser.UserRole == UserRole.BrandAdministrator)
                {
                    user.IsEmployee              = CurrentUser.IsEmployee;
                    user.PrimaryBrandId          = CurrentUser.PrimaryBrandId;
                    user.IsAccountNonExpiring    = false;
                    user.IsPasswordNonExpiring   = false;
                    user.IsAllowedExternalAccess = false;
                    user.EnableFilePathIngestion = false;
                }
            }

            user.FirstName    = FirstNameTextBox.Text.Trim();
            user.LastName     = LastNameTextBox.Text.Trim();
            user.Email        = EmailAddressTextBox.Text;
            user.CompanyName  = CompanyNameTextBox.Text.Trim();
            user.CountryId    = CountryDropDownList1.SelectedId;
            user.PhoneNumber  = PhoneNumberTextBox.Text.Trim();
            user.MobileNumber = MobileNumberTextBox.Text.Trim();
            user.IsSuspended  = AccountSuspendedCheckbox.Checked;
            user.UserRoleId   = Convert.ToInt32(UserRoleDropDownList.SelectedValue);

            if (user.CountryId == 0)
            {
                user.CountryId = null;
            }

            user.ApproverUserId = null;

            if (ApproverUserDropDownList.SelectedId > 0)
            {
                user.ApproverUserId = ApproverUserDropDownList.SelectedId;
            }

            user.UseWorkflow = (user.UserRole == UserRole.UploadUser && UseWorkflowCheckbox.Checked);
            user.WorkflowId  = null;

            if (user.UseWorkflow && WorkflowDropDownList.GetSelectedId() != 0)
            {
                user.WorkflowId = WorkflowDropDownList.GetSelectedId();
            }

            if (PasswordTextBox.Text.Trim() != string.Empty)
            {
                user.SetPassword(PasswordTextBox.Text);
                user.SetConfirmPassword(ConfirmPasswordTextBox.Text);
            }

            if (IsStaffUserRow.Visible)
            {
                user.IsEmployee = (IsStaffUserRadioButtonList.SelectedValue == "1");
            }

            SaveSelectedBrandsToUser(user);

            if (AdvancedOptionsPanel.Visible)
            {
                user.IsAccountNonExpiring    = AccountNonExpiringCheckbox.Checked;
                user.IsPasswordNonExpiring   = PasswordNonExpiringCheckBox.Checked;
                user.IsAllowedExternalAccess = AccountExternalAccessAllowedCheckbox.Checked;
                user.EnableFilePathIngestion = EnableFilePathIngestionCheckbox.Checked;
            }

            try
            {
                if (user.IsNew)
                {
                    bool notify = true;

                    if (WelcomeEmailCheckBoxRow.Visible && NoWelcomeEmailCheckBox.Checked)
                    {
                        notify = false;
                    }

                    UserManager.Create(user, CurrentUser, notify);
                }
                else
                {
                    UserManager.Update(user);
                    AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ModifyUser, string.Format("Modified user: {0}, with UserId: {1}", user.FullName, user.UserId));
                }

                UserId               = user.UserId.GetValueOrDefault();
                FormPanel.Visible    = false;
                SuccessPanel.Visible = true;
            }
            catch (InvalidUserException iuex)
            {
                MessageLabel1.SetErrorMessage("the following errors occured:", iuex.Errors);
            }
        }
        public override void ProcessRequest()
        {
            try{
                //log the request in the general log file
                m_Logger.InfoFormat("API Call to {0}.", Context.Request.Path);

                //pass the request to the script engine for processing
                ScriptResult result = ScriptEngine.Instance.Process(Context.Request.Path);

                User user = User.Get(result.Response.UserId);
                //if response was successful then update the user's last operation date
                if (result.Response.Error.Code == 0)
                {
                    UserManager.UpdateLastAPIOperation(user);

                    //update sessioninfo user to synchonise the SessionAPITokens etc.
                    if (!SessionInfo.Current.User.IsNull && !user.IsNull && SessionInfo.Current.User.UserId == user.UserId)
                    {
                        SessionInfo.Current.User = user;
                    }

                    m_Logger.InfoFormat("Successful call to {0}. Request: {1}, Response: {2}", Context.Request.Path, result.Request.RequestId, result.Response.ResponseId);
                }
                else
                {
                    m_Logger.InfoFormat("Unsuccessful call to {0}. Request: {1}, Response: {2}", Context.Request.Path, result.Request.RequestId, result.Response.ResponseId);
                }

                if (!user.IsNull)
                {
                    //log the request made in the audit trail
                    AuditLogManager.LogUserAction(user, AuditUserAction.APICall, String.Format("API Call to {0}", Context.Request.Path));
                }

                //save the response and request to the file system if API log folder
                //setting has been configured correctly
                if (!String.IsNullOrEmpty(ScriptEngine.APILogFolder) && Directory.Exists(ScriptEngine.APILogFolder))
                {
                    string requestFile = Path.Combine(ScriptEngine.APILogFolder, String.Format("{0}_request_{1}.xml", result.Request.CallName, result.Request.RequestId));
                    FileUtils.SaveToXmlFile(requestFile, result.Request);
                    string responseFile = Path.Combine(ScriptEngine.APILogFolder, String.Format("{0}_response_{1}.xml", result.Response.CallName, result.Response.ResponseId));
                    FileUtils.SaveToXmlFile(responseFile, result.Response);
                }
                else
                {
                    m_Logger.Warn("The API Log Folder has not been configured correctly. API Request-Response could not be saved.");
                }

                //Write the response according to the response format
                if (result.Response.Format == ResponseFormat.XML)
                {
                    //Xml response
                    m_Logger.Debug("Xml Response");
                    Context.Response.ContentType     = "application/xml";
                    Context.Response.ContentEncoding = Encoding.UTF8;
                    XmlSerializer xserialize = new XmlSerializer(typeof(ScriptResponse));
                    xserialize.Serialize(Context.Response.OutputStream, result.Response);
                }
                else
                {
                    //Json response (Default)
                    m_Logger.Debug("Json Response");
                    Context.Response.ContentType     = "application/json";
                    Context.Response.ContentEncoding = Encoding.UTF8;
                    DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ScriptResponse));
                    json.WriteObject(Context.Response.OutputStream, result.Response);
                }
            }
            catch (Exception exp)
            {
                m_Logger.ErrorFormat("An exception occurred processing a script request {0} - {1}", Context.Request.Path, exp.Message);
                throw new HttpException(500, "An unexpected error occurred");
            }
        }