Beispiel #1
0
        private void Close()
        {
            if (_client != null)
            {
                if (_client.State == CommunicationState.Faulted)
                {
                    _client.Abort();
                }
                else
                {
                    if (_client.State != CommunicationState.Opened)
                    {
                        return;
                    }

                    try
                    {
                        _client.Close();
                    }
                    catch (CommunicationException ex)
                    {
                        _client.Abort();
                    }
                    catch (TimeoutException ex)
                    {
                        _client.Abort();
                    }
                    catch (Exception ex)
                    {
                        _client.Abort();
                    }
                }
            }
        }
Beispiel #2
0
        public string[] GetExportEndpointAndStreamDownloadAddresses()
        {
            // Export endpoint and stream download endpoint are returned as a two element string array,
            // where the export endpoint is the first entry and the stream download endpoint is the second.
            string[] exportEndpointAndStreamDownloadAddresses = { string.Empty, string.Empty };

            // Create a new, null Core Service Client
            SessionAwareCoreServiceClient client = null;

            // TODO: Use Client, not client (then you don't have to worry about handling abort/dispose/etc.). <- Alchemy version 7.0 or higher
            // With Client, no need to call client.Abort(); can we also remove catch block below if using Client? Fix in other parts of code as well...

            try
            {
                // Creates a new core service client
                client = new SessionAwareCoreServiceClient("netTcp_2013");
                // Gets the current user so we can impersonate them for our client
                string username = GetUserName();
                client.Impersonate(username);

                // App data is set up with the following parameters.
                string exportEndpointId = "exportEndpointAddr";
                string streamDownloadId = "streamDownloadAddr";

                // Pass null for the item ID, since this app data does not correspond to any items in Tridion.
                ApplicationData appData = client.ReadApplicationData(null, exportEndpointId);
                if (appData != null)
                {
                    Byte[] data = appData.Data;
                    // exportEndpointId corresponds to the first element of the array return value.
                    exportEndpointAndStreamDownloadAddresses[0] = Encoding.Unicode.GetString(data);
                }

                appData = client.ReadApplicationData(null, streamDownloadId);
                if (appData != null)
                {
                    Byte[] data = appData.Data;
                    // streamDownloadId corresponds to the second element of the array return value.
                    exportEndpointAndStreamDownloadAddresses[1] = Encoding.Unicode.GetString(data);
                }

                // Explicitly abort to ensure there are no memory leaks.
                client.Abort();
            }
            catch (Exception ex)
            {
                // Proper way of ensuring that the client gets closed.
                if (client != null)
                {
                    client.Abort();
                }

                // We are rethrowing the original exception and just letting webapi handle it.
                throw ex;
            }

            return(exportEndpointAndStreamDownloadAddresses);
        }
Beispiel #3
0
        public string GetPathOfSelectedItem(string tcm)
        {
            string path = string.Empty;

            // Create a new, null Core Service Client
            SessionAwareCoreServiceClient client = null;

            try
            {
                // Creates a new core service client
                client = new SessionAwareCoreServiceClient("netTcp_2013");
                // Gets the current user so we can impersonate them for our client
                string username = GetUserName();
                client.Impersonate(username);

                if (String.Equals(tcm, "tcm:0") || String.Equals(tcm, "0"))
                {
                    // If it's tcm:0, we're dealing with the root element in the CMS's tree. In that case, simply
                    // do nothing to return an empty path, indicating to search through the entire tree.
                }
                else
                {
                    var item = client.Read("tcm:" + tcm, new ReadOptions());

                    if (item is RepositoryLocalObjectData)
                    {
                        path = ((RepositoryLocalObjectData)item).LocationInfo.Path + "\\" + item.Title;
                    }
                    else if (item is PublicationData)
                    {
                        // If the selection is not the root element and not a RepositoryLocalObjectData,
                        // then it's a publication.
                        path = "\\" + ((PublicationData)item).Title;
                    }
                    else
                    {
                        // Do nothing - allow empty path to be return; handle any additional cases here, if they arise.
                    }
                }

                // Explicitly abort to ensure there are no memory leaks.
                client.Abort();
            }
            catch (Exception ex)
            {
                // Proper way of ensuring that the client gets closed.
                if (client != null)
                {
                    client.Abort();
                }

                // We are rethrowing the original exception and just letting webapi handle it.
                throw ex;
            }

            return(path);
        }
 public void Dispose()
 {
     if (_client.State == CommunicationState.Faulted)
     {
         _client.Abort();
     }
     else
     {
         _client.Close();
     }
 }
Beispiel #5
0
        private void SetAppDataAddress(string id, string address)
        {
            // Create a new, null Core Service Client
            SessionAwareCoreServiceClient client = null;

            // TODO: Update to pass internal part of below snippet as a function (to reuse try-catch pattern)

            try
            {
                // Creates a new core service client
                client = new SessionAwareCoreServiceClient("netTcp_2013");
                // Gets the current user so we can impersonate them for our client
                string username = GetUserName();
                client.Impersonate(username);

                Byte[]          byteData = Encoding.Unicode.GetBytes(address);
                ApplicationData appData  = new ApplicationData
                {
                    ApplicationId = id,
                    Data          = byteData
                };

                client.SaveApplicationData(null, new[] { appData });

                // Explicitly abort to ensure there are no memory leaks.
                client.Abort();
            }
            catch (Exception ex)
            {
                // Proper way of ensuring that the client gets closed... we close it in our try block above,
                // then in a catch block if an exception is thrown we abort it.
                if (client != null)
                {
                    client.Abort();
                }

                // We are rethrowing the original exception and just letting webapi handle it.
                throw ex;
            }
        }
        public void Dispose()
        {
            if (_client != null)
            {
                switch (_client.State)
                {
                case CommunicationState.Faulted:
                    _client.Abort();
                    break;

                case CommunicationState.Opened:
                    _client.Close();
                    break;
                }
                var disposable = _client as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
        /// <summary>
        /// This allows efficient use of the CoreServices and automatic disposal and cleanup when
        /// properly used within using {} statements.
        /// </summary>
        public void Dispose()
        {
            if (_client != null)
            {
                switch (_client.State)
                {
                case CommunicationState.Faulted:
                    _client.Abort();
                    break;

                case CommunicationState.Opened:
                    _client.Close();
                    break;
                }

                //Since clientSession is by default an Interface we must polymorphically re-cast back
                //to IDisposable and then ensure it is still valid to safely dispose of the item.
                var disposable = _client as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Beispiel #8
0
 public void Abort()
 {
     _client.Abort();
 }
Beispiel #9
0
        public SocialPageData Execute(string pageUri)
        {
            SessionAwareCoreServiceClient client = null;
            SocialPageData socialPageData        = new SocialPageData();

            try
            {
                client = Client.GetCoreService();

                string liveTargetUri = Configuration.GetConfigString("livetargeturi");
                string liveUrl       = Configuration.GetConfigString("liveurl");

                PageData            pageData = (PageData)client.Read(pageUri, new ReadOptions());
                PublishLocationInfo pubInfo  = (PublishLocationInfo)pageData.LocationInfo;

                socialPageData.Title       = pageData.Title;
                socialPageData.Uri         = pageUri;
                socialPageData.Url         = liveUrl + pubInfo.PublishLocationUrl;
                socialPageData.IsPublished = client.IsPublished(pageUri, liveTargetUri, true);
                socialPageData.UseShortUrl = bool.Parse(Configuration.GetConfigString("shorturl"));

                string shortUrl = string.Empty;

                if (socialPageData.UseShortUrl)
                {
                    ApplicationData appData = client.ReadApplicationData(pageUri, SHORT_URL_APP_ID);

                    if (appData != null)
                    {
                        Byte[] data = appData.Data;
                        shortUrl = Encoding.Unicode.GetString(data);
                    }

                    if (shortUrl.Equals(string.Empty))
                    {
                        Bitly  service = new Bitly(socialPageData.Url);
                        string shorter = service.ShortenUrl(service.UrlToShorten, service.BitlyLogin, service.BitlyAPIKey);
                        shortUrl = Bitly.ParseXmlResponse(shorter, false);

                        Byte[] byteData = Encoding.Unicode.GetBytes(shortUrl);
                        appData = new ApplicationData
                        {
                            ApplicationId = SHORT_URL_APP_ID,
                            Data          = byteData,
                            TypeId        = shortUrl.GetType().ToString()
                        };

                        client.SaveApplicationData(pageUri, new[] { appData });
                    }
                }

                socialPageData.ShortUrl = shortUrl;
            }
            catch (Exception ex)
            {
                socialPageData.HasError  = true;
                socialPageData.ErrorInfo = ex;
            }
            finally
            {
                if (client != null)
                {
                    if (client.State == CommunicationState.Faulted)
                    {
                        client.Abort();
                    }
                    else
                    {
                        client.Close();
                    }
                }
            }

            return(socialPageData);
        }
Beispiel #10
0
        public string GetLatestItems(LatestItemsRequest request)
        {
            // Create a new, null Core Service Client
            SessionAwareCoreServiceClient client = null;

            try
            {
                // Creates a new core service client
                client = new SessionAwareCoreServiceClient("netTcp_2013");
                // Gets the current user so we can impersonate them for our client
                string username = GetUserName();
                client.Impersonate(username);

                // Start building up a string of html to return, including headings for the table that the html will represent.
                string html = "<div class=\"usingItems results\" id=\"latestItemsList\">";
                html += CreateItemsHeading();

                var filter = new SearchQueryData();

                // TODO: Add check for valid start and end times:

                if (String.IsNullOrEmpty(request.startTime))
                {
                    filter.ModifiedAfter = DateTime.Now.AddDays(-1);
                }
                else
                {
                    filter.ModifiedAfter = Convert.ToDateTime(request.startTime);
                }

                if (String.IsNullOrEmpty(request.endTime))
                {
                    filter.ModifiedBefore = DateTime.Now;
                }
                else
                {
                    filter.ModifiedBefore = Convert.ToDateTime(request.endTime);
                }

                filter.IncludeLocationInfoColumns = true;

                if (!string.IsNullOrEmpty(request.pathOfContainer) && !request.pathOfContainer.Equals("(All)"))
                {
                    // Assume publication field is valid publication name
                    // TODO: Validate here
                    string containerId = client.GetTcmUri(ConvertPathToWebdav(request.pathOfContainer), null, null);
                    //string pubTcm = client.GetTcmUri("/webdav/" + request.publication, null, null);
                    filter.SearchIn = new LinkToIdentifiableObjectData {
                        IdRef = containerId
                    };
                }

                if (!string.IsNullOrEmpty(request.user) && !request.user.Equals("(All)"))
                {
                    // TODO: Find a more efficient way of doing this than simply looking at all users.

                    var users = client.GetSystemWideList(new UsersFilterData {
                        BaseColumns = ListBaseColumns.IdAndTitle, IsPredefined = false
                    });

                    string userId = string.Empty;

                    foreach (var ud in users)
                    {
                        if (ud.Title == request.user)
                        {
                            userId = ud.Id;
                        }
                    }

                    // If userId is not found, allow an empty string to be passed, which will trigger and error message.
                    filter.Author = new LinkToUserData()
                    {
                        IdRef = userId
                    };
                }

                filter.ItemTypes = new[] { ItemType.Schema,
                                           ItemType.Component,
                                           ItemType.TemplateBuildingBlock,
                                           ItemType.ComponentTemplate,
                                           ItemType.PageTemplate,
                                           ItemType.Category,
                                           ItemType.Folder,
                                           ItemType.Keyword,
                                           ItemType.Page,
                                           ItemType.StructureGroup,
                                           ItemType.VirtualFolder,
                                           ItemType.Publication };

                filter.BlueprintStatus = SearchBlueprintStatus.Local;

                var searchResults = client.GetSearchResults(filter);

                filter.BlueprintStatus = SearchBlueprintStatus.Localized;

                var searchResults2 = client.GetSearchResults(filter);

                // Merge the two searchResults arrays (local and localized; union goes into searchResults):
                int array1OriginalLength = searchResults.Length;
                Array.Resize <IdentifiableObjectData>(ref searchResults, array1OriginalLength + searchResults2.Length);
                Array.Copy(searchResults2, 0, searchResults, array1OriginalLength, searchResults2.Length);

                int row = 0;

                foreach (IdentifiableObjectData item in searchResults)
                {
                    row++;

                    string path = "";
                    if (item is RepositoryLocalObjectData)
                    {
                        path = ((RepositoryLocalObjectData)item).LocationInfo.Path;
                    }

                    bool outputItem = true;

                    // If user is not empty or set to (All), then run some logic to see if items match selected user within specified time range.
                    // This is necessary to account for scenarios where one user creates an item, but another edits it at a later time, for instance.
                    // If no specific user is specified, DO NOT run these checks as they are expensive and not necessary in that case!
                    // Only perform this check for Versioned Items (i.e. not folders, etc.).
                    ////if (!string.IsNullOrEmpty(request.user) && !request.user.Equals("(All)") && (item is VersionedItemData))
                    ////{
                    ////    // Set flag to false by default and set back to true if we find a match.
                    ////    outputItem = false;

                    ////    VersionsFilterData versionsFilter = new VersionsFilterData();
                    ////    versionsFilter.IncludeRevisorDescriptionColumn = true;
                    ////    IdentifiableObjectData[] versionList = client.GetList(item.Id, versionsFilter);

                    ////    foreach (IdentifiableObjectData objectData in versionList)
                    ////    {
                    ////        var versionInfo = (FullVersionInfo)objectData.VersionInfo;

                    ////        // Check 2 things:
                    ////        // 1) that versionInfo.Revisor.Title == request.user
                    ////        // 2) that versionInfo.RevisionDate.Value is between filter.ModifiedAfter and filter2.ModifiedBefore
                    ////        // If we find a match, set outputItem to true and break the foreach loop.

                    ////        if (versionInfo.Revisor.Title == request.user)
                    ////        {
                    ////            if ((objectData.VersionInfo.RevisionDate >= filter.ModifiedAfter) && (objectData.VersionInfo.RevisionDate <= filter.ModifiedBefore))
                    ////            {
                    ////                outputItem = true;
                    ////                break;
                    ////            }
                    ////        }
                    ////    }
                    ////}

                    if (outputItem)
                    {
                        string currItemHtml = "<div class=\"item\">";

                        // Some JS magic is needed here to retrieve the icon and add it to the url by string replacement.
                        // We need to do this in JS because the core service provides no access to an item's icon.
                        currItemHtml += "<script>var icon = $models.getItem(\"" + item.Id + "\").getInfo().Icon;</script>";
                        currItemHtml += "<div id=\"tempIconId" + row + "\" class=\"icon\" style=\"background-image: url(/WebUI/Editors/CME/Themes/Carbon2/icon_v7.1.0.66.627_.png?name=" + "****" + "&size=16)\">" + "" + "</div>";
                        currItemHtml += "<script>document.getElementById('tempIconId" + row + "').outerHTML = document.getElementById('tempIconId" + row + "').outerHTML.replace(\"****\", icon);</script>";

                        currItemHtml += "<div class=\"name\">" + item.Title + "</div>";
                        currItemHtml += "<div class=\"path\">" + path + "</div>";
                        currItemHtml += "<div class=\"id\">" + item.Id + "</div>";
                        currItemHtml += "</div>";

                        html += currItemHtml;
                    }
                }

                // Close the div we opened above
                html += "</div>";

                // Explicitly abort to ensure there are no memory leaks.
                client.Abort();

                // Return the html we've built.
                return(html);
            }
            catch (Exception ex)
            {
                // Proper way of ensuring that the client gets closed... we close it in our try block above,
                // then in a catch block if an exception is thrown we abort it.
                if (client != null)
                {
                    client.Abort();
                }

                // We are rethrowing the original exception and just letting webapi handle it.
                throw ex;
            }
        }