//checks if a file already exists, uploads it if not private static void CheckOrUploadFile(string localFolder, string cmsDestinationPath, AccessAsset accessAsset, string file) { string cmsPathToCheck = ""; //1 - check if file already exists cmsPathToCheck = file.ToLower().Replace(localFolder, cmsDestinationPath).Replace("\\", "/"); var existsResponse = accessAsset.Exists(new AssetExistsRequest(cmsPathToCheck)); if (existsResponse.exists) { Console.WriteLine("Skipping, asset {0} already exists. (id: {1})", cmsPathToCheck, existsResponse.assetId); } else { //file was not found in the CMS instance, so we will upload it, but first make sure we do have an existing folder structure in the CMS //2 - check if folder exists, create otherwise string path = Path.GetDirectoryName(file); int folderId = -1; if (folderCache.ContainsKey(path)) { folderId = folderCache[path]; } else { //attempt to create folder and cache new assetId as the folderId cmsPathToCheck = path.ToLower().Replace(localFolder, cmsDestinationPath).Replace("\\", "/"); existsResponse = accessAsset.Exists(new AssetExistsRequest(cmsPathToCheck)); if (existsResponse.exists) { folderId = existsResponse.assetId; folderCache.Add(path, folderId); } else { //could not find folder, split and build path folderId = BuildFolderTree(cmsPathToCheck); if (folderId < 0) { //something went wrong, exit app, so we don't upload files to wrong folders, or have excessive # of errors. Console.WriteLine("Error, Unable to create folder {0} ", cmsPathToCheck); Environment.Exit(-1); } folderCache.Add(path, folderId); } } //upload asset here AssetUploadRequest req = new AssetUploadRequest(Path.GetFileName(file), folderId); req.bytes = File.ReadAllBytes(file); var resp = accessAsset.Upload(req); if (resp.IsSuccessful) { Console.WriteLine("upload successful: {0} in {1}", file, path, resp.asset.id); } else { Console.WriteLine("Error uploading file: {0} in {1}: {2}", file, path, resp.ErrorMessage); } } }
private static AccessAsset accessAsset; //for accessability, used in multiple methods static void Main(string[] args) { try { #region handle arguments and validation if (args.Length < 2) { Console.WriteLine("Usage: syncFolder [local folder to synchronize] [destination CMS folder]"); } string localFolder = args[0]; string destFolder = args[1]; if (!Directory.Exists(localFolder)) { Console.WriteLine("Could not find local folder: {0}", localFolder); return; } #endregion #region get password string username = ConfigurationSettings.AppSettings["username"]; Console.Write("Enter pw for {0}: ", username); string pw = getSecuredString(); Console.WriteLine(""); Console.WriteLine("Authenticating: {0} ", username); #endregion Console.WriteLine("Communicating with {0}/{1}", ConfigurationSettings.AppSettings["host"], ConfigurationSettings.AppSettings["instance"]); var session = new AccessSession(ConfigurationSettings.AppSettings["host"], ConfigurationSettings.AppSettings["instance"], username, pw, ConfigurationSettings.AppSettings["apiKey"]); accessAsset = new AccessAsset(session.Client); processFolder(localFolder.ToLower(), destFolder); var accessAuth = new AccessAuth(session.Client); accessAuth.Logout(); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } Console.Write("Press, almost, any key to continue..."); Console.ReadLine(); }
/// <summary> /// Returns a collection of assets residing in the specified CMS path. /// </summary> /// <param name="assetPath">Path relative to the configured image browsing path</param> /// <param name="currentPage"></param> /// <param name="pageSize"></param> /// <param name="searchText"></param> /// <returns></returns> public AssetCollection ListAssets(string assetPath, int currentPage, int pageSize, string searchText) { EnsureAccessApiSession(); var assets = new List<AssetInfo>(); var accessAsset = new AccessAsset(_session.Client); var listPath = (_settings.ImageBrowsePath + assetPath).Replace("\\", "//"); var folderAssetId = GetAssetId(accessAsset, listPath); var hasFilter = !string.IsNullOrEmpty(searchText); // Get assets var totalAssetCount = 0; // Add asset for navigating up a level in folder structure if (!string.IsNullOrEmpty(assetPath) && currentPage == 1) { var parentAssetPath = assetPath.Substring(0, assetPath.LastIndexOf("/")); assets.Add(new AssetInfo() { Id = 0, Label = ". . .", PublishedUrl = parentAssetPath, IsFolder = true }); } if (hasFilter) { // Api doesn't support filtering, so we must fetch all assets and filter/page manually AddAssetsToList(assets, accessAsset, assetPath, folderAssetId, 1, -1); assets = assets.Where(a => a.Label.ToUpperInvariant().Contains(searchText.ToUpperInvariant())).ToList(); totalAssetCount = assets.Count; assets = assets .Skip(pageSize * (currentPage - 1)) .Take(pageSize) .ToList(); } else { totalAssetCount = AddAssetsToList(assets, accessAsset, assetPath, folderAssetId, currentPage, pageSize); } return new AssetCollection(assets, totalAssetCount); }
static void Main(string[] args) { try { #region handle arguments and validation if (args.Length < 2) { Console.WriteLine("Usage: syncFolder [local folder to synchronize] [destination CMS folder]"); } string localFolder = args[0]; string destFolder = args[1]; if (!Directory.Exists(localFolder)) { Console.WriteLine("Could not find local folder: {0}", localFolder); return; } #endregion #region get password string username = ConfigurationSettings.AppSettings["username"]; Console.Write("Enter pw for {0}: ", username); string pw = getSecuredString(); Console.WriteLine(""); Console.WriteLine("Authenticating: {0} ", username); #endregion Console.WriteLine("Communicating with {0}/{1}", ConfigurationSettings.AppSettings["host"], ConfigurationSettings.AppSettings["instance"]); var session = new AccessSession( ConfigurationSettings.AppSettings["host"], ConfigurationSettings.AppSettings["instance"], username, pw, ConfigurationSettings.AppSettings["apiKey"]); accessAsset = new AccessAsset(session.Client); processFolder(localFolder.ToLower(), destFolder); var accessAuth = new AccessAuth(session.Client); accessAuth.Logout(); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } Console.Write("Press, almost, any key to continue..."); Console.ReadLine(); }
public string UploadAsset(string assetPath, string base64StringData) { EnsureAccessApiSession(); var accessAsset = new AccessAsset(_session.Client); var uploadPath = _settings.ImageBrowsePath + assetPath; // Remove existing asset if exists if (!DeleteAsset(accessAsset, uploadPath)) throw new InvalidOperationException("Unable to remove existing asset: " + uploadPath); // Get target folder var folderId = GetAssetId(accessAsset, Path.GetDirectoryName(uploadPath).Replace("\\", "//")); if (folderId <= 0) throw new InvalidOperationException("Specified upload path does not exist: " + uploadPath); // Upload new asset to target folder var fileName = Path.GetFileName(uploadPath); var assetDataParts = base64StringData.Split(",".ToCharArray()); AssetUploadRequest request = new AssetUploadRequest(fileName, folderId); if (!string.IsNullOrEmpty(_settings.ImageUploadWorkflowId)) request.workflowId = int.Parse(_settings.ImageUploadWorkflowId); request.bytes = Convert.FromBase64String(assetDataParts.Length > 1 ? assetDataParts[1] : assetDataParts[0]); var response = accessAsset.Upload(request); if (!response.IsSuccessful) throw new InvalidOperationException("Unable to upload asset: " + uploadPath + " (" + response.ErrorMessage ?? string.Empty + ")"); // Return published relative path of asset var publishedPath = _settings.ImageBrowsePublishServerPath + assetPath; return publishedPath; }
private int GetAssetId(AccessAsset accessAsset, string assetPath) { var existsResponse = accessAsset.Exists(new AssetExistsRequest(assetPath)); return existsResponse.assetId; }
private void EnsureAccessApiSession() { lock (_threadLock) { var sessionMinutes = (DateTime.Now - _sessionRenewDate).TotalMinutes; if (_session == null || (sessionMinutes >= _maxSessionMinutes)) { _session = Authenticator.CreateSession(_settings.ApiHostUrl, _settings.ApiInstanceName, _settings.ApiUserName, _settings.ApiPassword, _settings.ApiKey); _sessionRenewDate = DateTime.Now; return; } } // Make test call to ensure session hasn't timed out try { var accessAsset = new AccessAsset(_session.Client); accessAsset.Exists(new AssetExistsRequest("/")); } catch { _session = null; EnsureAccessApiSession(); } }
private bool DeleteAsset(AccessAsset accessAsset, string assetPath) { var assetId = GetAssetId(accessAsset, assetPath); if (assetId > 0) { var deleteResponse = accessAsset.Delete(assetId); return deleteResponse.IsSuccessful; } return true; }
private int AddAssetsToList(List<AssetInfo> assets, AccessAsset accessAsset, string assetPath, int folderAssetId, int currentPage, int pageSize) { var returnAllPages = pageSize == -1; // Fetch specified page of data var request = new AssetPagedRequest { assetId = folderAssetId, currentPage = currentPage - 1, pageSize = returnAllPages ? _maxSupportedPageSize : pageSize, sortColumn = "", orderType = cpAssetOrderType.Ascending, visibilityType = cpAssetVisibilityType.Normal, ignoreFilter = true, ignoreSort = true }; var response = accessAsset.Paged(request); if (response != null && response.assets != null) { foreach (var worklistAsset in response.assets) { if (worklistAsset.type == (int)AssetType.File || worklistAsset.type == (int)AssetType.Folder) { var publishedUrl = _settings.PublishSiteRootUrl + _settings.ImageBrowsePublishServerPath + assetPath + "/" + worklistAsset.label; assets.Add(new AssetInfo { Id = worklistAsset.id, Label = worklistAsset.label, CmsPath = worklistAsset.FullPath, PublishedUrl = publishedUrl, IsFolder = worklistAsset.type == (int)AssetType.Folder }); } } } // If returning all results, determine if additional pages of data need to be loaded if (returnAllPages && (response.normalCount > (currentPage * _maxSupportedPageSize))) { currentPage++; return AddAssetsToList(assets, accessAsset, assetPath, folderAssetId, currentPage, pageSize); } return response.normalCount; }