protected override void Execute() { ActivityInstanceData activityInstance = ActivityInstance; List <String> items = new List <string>(); TridionActivityDefinitionData activitydefinition = (TridionActivityDefinitionData)CoreServiceClient.Read(ActivityInstance.ActivityDefinition.IdRef, readoption); ProcessDefinitionData processdefinition = (ProcessDefinitionData)CoreServiceClient.Read(activitydefinition.ProcessDefinition.IdRef, readoption); Logger.Write(string.Format("ActivityInstance.Title : {0}", ActivityInstance.Title), "Workflow", LoggingCategory.General, TraceEventType.Information); foreach (WorkItemData wid in activityInstance.WorkItems) { items.Add(wid.Subject.Title); } try { SmtpClient client = Utility.SMTPClientConfiguration(); MailMessage mail = Utility.WorkflowMailMessageConfiguration(ActivityInstance.Title.ToString(), items, null); client.Send(mail); Logger.Write(string.Format("Mail : {0}", mail.Body.ToString()), "Workflow", LoggingCategory.General, TraceEventType.Information); Logger.Write(string.Format("ActivityInstance.Title : {0}", "Mail Sent"), "Workflow", LoggingCategory.General, TraceEventType.Information); } catch (Exception ex) { Logger.Write(string.Format("ActivityInstance.Title : {0}", ex.Message.ToString()), "Workflow", LoggingCategory.General, TraceEventType.Information); } finally { CoreServiceClient.FinishActivity(ActivityInstance.Id, new ActivityFinishData { Message = "Mail Sent to Target Audience, Finished Activity" }, null); Logger.Write(string.Format("Message: {0}", "Auto Approved and Send for Next Activity , Finished Activity"), "Workflow", LoggingCategory.General, TraceEventType.Information); } }
protected static void PurgeStructureGroupItems(string startSgUri, ushort versionsToKeep, string pubUri) { using (CoreServiceClient client = new CoreServiceClient(endpointName)) { var credentials = CredentialCache.DefaultNetworkCredentials; if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { credentials = new NetworkCredential(userName, password); } client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; if (versionsToKeep < 0) { return; } PurgeOldVersionsInstructionData purgeIntructions = new PurgeOldVersionsInstructionData(); string structureGroups = startSgUri; if (structureGroups != "") { PurgeStructureGroups(client, structureGroups, purgeIntructions, versionsToKeep, pubUri); } } }
public Simulation(IMessageHandler messageHandler) { _messageHandler = messageHandler; _stations = new List <Station>(); _coreServiceClient = new CoreServiceClient(); _hosts = new List <ServiceHost>(); }
private static string GetAllPublications() { List <string> pubs = new List <string>(); using (CoreServiceClient client = new CoreServiceClient(endpointName)) { var credentials = CredentialCache.DefaultNetworkCredentials; if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { credentials = new NetworkCredential(userName, password); } client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; PublicationsFilterData filter = new PublicationsFilterData(); XElement publications = client.GetSystemWideListXml(filter); XNamespace ns = publications.GetNamespaceOfPrefix("tcm"); foreach (XElement item in publications.DescendantNodes()) { pubs.Add(item.Attribute("ID").Value); } } string allPubs = string.Join(", ", Array.ConvertAll(pubs.ToArray(), i => i.ToString())); return(allPubs); }
public static ICoreService GetClient(Environment environment) { Uri cmUri = new Uri(environment.CMSUrl); if (_clientInstance == null) { var binding = GetBinding(cmUri.Scheme == "https"); var endpoint = _version; CoreServiceClient coreServiceClient = new CoreServiceClient((Binding)binding, new EndpointAddress($"{cmUri.Scheme}://{cmUri.Host}:{cmUri.Port}/webservices/CoreService{_version}.svc/basicHttp")); if (!string.IsNullOrEmpty(environment.Username) && !string.IsNullOrEmpty(environment.Password)) { ((ClientBase <ICoreService>)coreServiceClient).ClientCredentials.Windows.ClientCredential.UserName = environment.Username; ((ClientBase <ICoreService>)coreServiceClient).ClientCredentials.Windows.ClientCredential.Password = environment.Password; } if (!string.IsNullOrEmpty(environment.UserDomain)) { ((ClientBase <ICoreService>)coreServiceClient).ClientCredentials.Windows.ClientCredential.Domain = string.IsNullOrEmpty(environment.UserDomain) ? "." : environment.UserDomain; } _clientInstance = coreServiceClient; } return(_clientInstance); }
public static bool bluePrintInfo(CoreServiceClient client) { client.ClientCredentials.Windows.ClientCredential.Domain = ConfigurationSettings.AppSettings["Domain"]; client.ClientCredentials.Windows.ClientCredential.UserName = ConfigurationSettings.AppSettings["User"]; client.ClientCredentials.Windows.ClientCredential.Password = ConfigurationSettings.AppSettings["PWD"]; UsingItemsFilterData usingItemsFilterData = new UsingItemsFilterData { ItemTypes = new[] { ItemType.PublicationTarget, ItemType.Publication, ItemType.Component, ItemType.Page, ItemType.Keyword } , IncludeLocalCopies = true, BaseColumns = ListBaseColumns.Extended, }; PublicationsFilterData filter = new PublicationsFilterData { BaseColumns = ListBaseColumns.IdAndTitle }; XElement publications = client.GetSystemWideListXml(filter); XElement elist = client.GetListXml("tcm:3-1973", usingItemsFilterData); List <Result> lstRS = new List <Result>(); IEnumerable <XElement> usingXML1 = (from el in elist.Elements() //where (string)el.Attribute("IsPublished").Value == "true" select el); return(true); }
protected override void Execute() { CoreServiceClient.FinishActivity(ActivityInstance.Id, new ActivityFinishData { Message = "Mail Sent to Target Audience, Finished Activity", NextActivityDueDate = System.DateTime.Now.AddMinutes(5) }, null); Logger.Write(string.Format("Message: {0}", "Auto Approved and Send for Next Activity , Finished Activity"), "Workflow", LoggingCategory.General, TraceEventType.Information); }
/// <summary> /// Processes the core service record. /// </summary> /// <remarks>Used for proper error handling of core service fault exception.</remarks> protected override void ProcessCoreServiceRecord() { foreach (string id in TcmApplicationIds) { CoreServiceClient.PurgeApplicationData(id); } }
/// <summary> /// Processes the core service record. /// </summary> /// <remarks>Used for proper error handling of core service fault exception.</remarks> protected override void ProcessCoreServiceRecord() { foreach (var queue in GetQueues()) { CoreServiceClient.PurgeQueue((int)queue); } }
public CoreServiceClient GetNewNetTcpClient() { string username = _Config.AppSettings.Settings["impersonation_user"].Value; string password = _Config.AppSettings.Settings["impersonation_password"].Value; string address = _Config.AppSettings.Settings["nettcpaddress"].Value; var binding = new NetTcpBinding { MaxReceivedMessageSize = 2147483647, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxStringContentLength = 2147483647, MaxArrayLength = 2147483647 } }; var endpoint = new EndpointAddress(address); var client = new CoreServiceClient(binding, endpoint); client.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(username, password); try { client.GetApiVersion(); } catch { return(null); } return(client); }
/// <summary> /// Lấy thông tin chữ ký số táºp trung trên hệ thống /// </summary> /// <param name="token"></param> /// <returns></returns> private static Certificate _getAccoutCert(string token) { var response = CoreServiceClient.Query(new RequestMessage { RequestID = Guid.NewGuid().ToString(), ServiceID = "Certificate", FunctionName = "GetAccountCertificateByEmail", Parameter = new CertParameter { PageIndex = 0, PageSize = 10 } }, token); if (response != null) { if (response.Content == null) { _error = response.ResponseContent; return(null); } var str = JsonConvert.SerializeObject(response.Content); CertResponse acc = JsonConvert.DeserializeObject <CertResponse>(str); if (acc != null && acc.Count > 0) { return(acc.Items[0]); } else { _error = "Tà i khoản chÆ°a đăng ký chữ ký số táºp trung. Không có chứng thÆ° số trên hệ thống"; } } return(null); }
public AddDroneTask() { InitializeComponent(); comboBoxDroneTask.Items.Insert(0, "TakePackage"); comboBoxDroneTask.Items.Insert(1, "GoToStation"); comboBoxDroneTask.Items.Insert(2, "LeavePackage"); comboBoxDroneTask.Items.Insert(3, "ChargeAtStation"); _coreServiceClient = new CoreServiceClient(); _stations = new List <Station>(_coreServiceClient.GetStations()); for (int i = 0; i < _stations.Count; i++) { comboBoxStation.Items.Insert(i, _stations.ElementAt(i).Name); } if (!((MainWindow)Application.Current.MainWindow).isAddedDrone) { _coreServiceClient = new CoreServiceClient(); _drones = ((MainWindow)Application.Current.MainWindow).Simulation._drones; foreach (Drone drone in _drones) { ((MainWindow)Application.Current.MainWindow).DroneList.Add(drone.Model.ModelName); } ((MainWindow)Application.Current.MainWindow).isAddedDrone = true; } foreach (string droneName in ((MainWindow)Application.Current.MainWindow).DroneList) { comboBoxDrone.Items.Add(droneName); } }
public static IEnumerable <string> ItemURIsInOrganizationalItem(this CoreServiceClient client, string organizationalItemId) { var filter = new OrganizationalItemItemsFilterData(); var comps = client.GetListXml(organizationalItemId, filter); return(comps.Descendants().Select(itemElement => itemElement.Attribute("ID").Value)); }
public CustomerSimulation() { _random = new Random(DateTime.Now.GetHashCode()); _coreServiceClient = new CoreServiceClient(); _customers = new List <Customer>(); _stations = new List <Station>(); _sizes = new List <PackageSize>(); }
public bool GetPackageFromCustomer(GeneratedPackage package) { Log($"get package from customer, registering it in core"); CoreServiceClient coreClient = new CoreServiceClient(); coreClient.RegisterPackage(package); return(true); }
public Simulation(IMessageHandlerDrone messageHandler) { _messageHandler = messageHandler; _drones = new List <Drone>(); _coreServiceClient = new CoreServiceClient(); _hosts = new List <ServiceHost>(); _packageSize = new List <PackageSize>(); }
public void Open(string endPoint, NetworkCredential credentials) { _client = new CoreServiceClient(endPoint); if (credentials != null) { _client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; } }
private UserData GetFirstManualActivityPerformer() { ReadOptions readoption = new ReadOptions(); ActivityInstanceData firstManualActivity = GetFirstManualActivity(); Logger.Write(string.Format("FirstManualActivity: {0}", firstManualActivity.Title), "Workflow", LoggingCategory.General, TraceEventType.Information); return((UserData)CoreServiceClient.Read(firstManualActivity.Performers.Last().IdRef, null)); }
/// <summary> /// Processes the core service record. /// </summary> /// <remarks>Used for proper error handling of core service fault exception.</remarks> protected override void ProcessCoreServiceRecord() { foreach (var packageInfo in _packagesToDelete) { CoreServiceClient.DeleteApplicationData(null, packageInfo.PackageId); CoreServiceClient.DeleteApplicationData(null, packageInfo.PackageMetadataId); } }
/// <summary> /// Processes the core service record. /// </summary> /// <remarks>Used for proper error handling of core service fault exception.</remarks> protected override void ProcessCoreServiceRecord() { if (Ids == null || !Ids.Any()) { WriteObject(CoreServiceClient.GetSystemWideList(new RepositoriesFilterData()), true); return; } Ids.ToList().ForEach(id => WriteObject((RepositoryData)CoreServiceClient.Read(id, null))); }
protected override void Execute() { PublishInstructionData publishInstruction = new PublishInstructionData(); publishInstruction.ResolveInstruction = new ResolveInstructionData(); publishInstruction.RenderInstruction = new RenderInstructionData(); //Needed for publishing workflow revision/version publishInstruction.ResolveInstruction.IncludeWorkflow = true; TrusteeData lastPerformer = GetFirstManualActivityPerformer(); ActivityInstanceData activityInstance = ActivityInstance; Logger.Write(string.Format("lastPerformer: {0}", lastPerformer.Title), "Workflow", LoggingCategory.General, TraceEventType.Information); if (Utility.IsMailSendOptionTrue(activityInstance.Title)) { Logger.Write(string.Format("Mail Send Option: {0}", "True"), "Workflow", LoggingCategory.General, TraceEventType.Information); try { SmtpClient client = Utility.SMTPClientConfiguration(); MailMessage mail = Utility.WorkflowMailMessageConfiguration(ActivityInstance.Title.ToString(), null, lastPerformer.Title); client.Send(mail); Logger.Write(string.Format("Mail : {0}", mail.Body.ToString()), "Workflow", LoggingCategory.General, TraceEventType.Information); Logger.Write(string.Format("ActivityInstance.Title : {0}", "Mail Sent"), "Workflow", LoggingCategory.General, TraceEventType.Information); } catch (Exception ex) { Logger.Write(string.Format("ActivityInstance.Title : {0}", ex.Message.ToString()), "Workflow", LoggingCategory.General, TraceEventType.Information); } } if (Utility.IsPublishedToPreviewTrue()) { // Retrieving the Publication Target and Publish Transaction if (ProcessInstance.Variables.ContainsKey("PublishTransaction")) { string publishTransactionId = ProcessInstance.Variables["PublishTransaction"]; // Undo Publish Transaction CoreServiceClient.UndoPublishTransaction(publishTransactionId, QueueMessagePriority.Normal, null); } } // Finish the Activity ActivityFinishData finishData = new ActivityFinishData() { Message = "The Item " + activityInstance.WorkItems.FirstOrDefault().ToString() + " has been rejected and reassigned to " + lastPerformer.Title, NextAssignee = new LinkToTrusteeData() { IdRef = lastPerformer.Id } }; CoreServiceClient.FinishActivity(activityInstance.Id, finishData, null); }
/// <summary> /// This method is used to Publish Item to Preview environment /// </summary> protected override void Execute() { PublishInstructionData publishInstractionData = new PublishInstructionData(); publishInstractionData.RenderInstruction = new RenderInstructionData(); publishInstractionData.ResolveInstruction = new ResolveInstructionData(); publishInstractionData.ResolveInstruction.IncludeWorkflow = true; publishInstractionData.ResolveInstruction.IncludeChildPublications = false; List <string> itemToPublish = new List <string>(); String[] targets = Utility.GetPublishingTarget("Preview Publication Target"); String[] PublishTo = Utility.GetPublishingTo(); int length = PublishTo.Length; Logger.Write(string.Format("length: {0}", length), "Workflow", LoggingCategory.General, TraceEventType.Information); ActivityInstanceData activityInstance = ActivityInstance; foreach (WorkItemData wid in activityInstance.WorkItems) { if (length != 0 && PublishTo[0].ToString() != "All") { for (int counter = 0; counter < length; counter++) { string comp = wid.Subject.IdRef; int index = comp.IndexOf('-'); string sub1 = comp.Substring(index, comp.Length - index); comp = @"tcm:" + PublishTo[counter].ToString() + sub1; Logger.Write(string.Format("component ID : {0}", comp), "Workflow", LoggingCategory.General, TraceEventType.Information); itemToPublish.Add(comp); } } else { publishInstractionData.ResolveInstruction.IncludeChildPublications = true; itemToPublish.Add(wid.Subject.IdRef); } } PublishTransactionData[] publishTransactionData = CoreServiceClient.Publish(itemToPublish.ToArray <String>(), publishInstractionData, targets, PublishPriority.High, null); if (ProcessInstance.Variables.ContainsKey("PublishTransaction")) { ProcessInstance.Variables["PublishTransaction"] = publishTransactionData[0].Id; } else { ProcessInstance.Variables.Add("PublishTransaction", publishTransactionData[0].Id); } CoreServiceClient.FinishActivity(ActivityInstance.Id, new ActivityFinishData { Message = "Publish to Preview Queued: Finished Activity" }, null); Logger.Write(string.Format("Message: {0}", "Publish to Preview Queued: Finished Activity"), "Workflow", LoggingCategory.General, TraceEventType.Information); }
/// <summary> /// Processes the core service record. /// </summary> /// <remarks> /// Used for proper error handling of core service fault exception. /// </remarks> protected override void ProcessCoreServiceRecord() { if (PublicationTargetIds != null && PublicationTargetIds.Any()) { foreach (string publicationTargetId in PublicationTargetIds) { CoreServiceClient.DecommissionPublicationTarget(publicationTargetId); } } }
public AddDrone() { InitializeComponent(); _coreServiceClient = new CoreServiceClient(); _maxCarrySize = ((MainWindow)Application.Current.MainWindow).Simulation._packageSize; for (int i = 0; i < _maxCarrySize.Count; i++) { comboBoxMaxSizeCarry.Items.Insert(i, _maxCarrySize.ElementAt(i).SizeName); } }
private void InitializeClient(string endPoint, NetworkCredential credentials) { try { _client = new CoreServiceClient(endPoint); _client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; if (_client != null) _coreServiceVersion = _client.GetApiVersion(); } catch (EndpointNotFoundException e) { } catch (Exception e) { } }
private void AnalyzeResults() { // analyze the test results Console.WriteLine(""); if (_folders.Count == 0) { // Failed test. Apparently the folder existed before starting the test. Console.WriteLine($"ERROR - unexpected: {_folders.Count} folders were created"); } else if (_folders.Count == 1) { // OK test. The bug did not apprear Console.WriteLine($"OK - {_folders.Count} folders were created"); // one folder was created which is good. The bug is not reproduced } else if (_folders.Count > 1) { // Expected test result Console.WriteLine($"ERROR {_folders.Count} folders were created with the same folder name: '{_folderPath}'"); CoreServiceClient client = new CoreServiceClient(ConfigurationManager.AppSettings["endpointName"], ConfigurationManager.AppSettings["endpointURI"]); client.ClientCredentials.Windows.ClientCredential = new NetworkCredential( ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"]); // Proving that IsExistingObject operation returns an exception when the target folder name is not unique Console.WriteLine(""); try { bool isExistingObject = client.IsExistingObject(_folderPath); Console.WriteLine($"OK IsExistingObject '{_folderPath}' returned '{isExistingObject.ToString()}'"); } catch (Exception e) { Console.WriteLine($"ERROR: IsExistingObject '{_folderPath}' returned exception '{e.Message}'"); } // Proving that Read operation returns an exception when the target folder name is not unique Console.WriteLine(""); try { FolderData folderData = (FolderData)client.Read(_folderPath, new ReadOptions()); Console.WriteLine($"OK Read '{_folderPath}' returned FolderData for '{folderData.Id}'"); } catch (Exception e) { Console.WriteLine($"ERROR: Read '{_folderPath}' returned exception '{e.Message}'"); } } }
/// <summary> /// Processes the core service record. /// </summary> /// <remarks>Used for proper error handling of core service fault exception.</remarks> protected override void ProcessCoreServiceRecord() { if (TcmRepositoryIds != null && TcmRepositoryIds.Any()) { foreach (string id in TcmRepositoryIds) { CoreServiceClient.ReIndex(id); } } else { CoreServiceClient.ReIndex(null); } }
public List<Breed> GetBreedList(int sid, PetfirstCustomer mCustomer) { List<Breed> lstReturn = null; string cacheKey = string.Concat("$BreedList_sid$" ,sid); object CachedList = m_Cache.Get(cacheKey) as List<Breed>; if (CachedList == null)//get from the service { CoreServiceReference.CoreServiceClient cs = new CoreServiceClient(); CoreServiceGetBreedListRequest cRequest = new CoreServiceGetBreedListRequest(); cRequest.SpeciesId = sid; CoreServiceGetBreedListResponse cbResponse = cs.GetBreedList(cRequest); //insert select breed on the top if (string.IsNullOrEmpty(cbResponse.Error.ErrorText))//check error { if (cbResponse.Breeds != null) { lstReturn = ModifyMixedBreed(sid, cbResponse.Breeds); m_Cache.Add(cacheKey, lstReturn); } } else { lstReturn = null; LogException le = new LogException(); try { le.LogError(HttpContext.Current.Request.Url.AbsoluteUri, "Error during getting breed list", cbResponse.Error.ErrorText, mCustomer); ///Test email server //le.SendErrorEmail(string.Concat(Request.Url.AbsoluteUri, "<br/><hr />", msg, "<hr />User Input:", le.BuildUserDataString(mCustomer))); } catch (Exception ex) { ///Test email server //lblError.Text = ex.ToString(); try { le.SendErrorEmail(string.Concat(HttpContext.Current.Request.Url.AbsoluteUri, "<br/><hr />", ex.Message, "<br />StackTrace: ", ex.StackTrace, "<br /><hr />User Input:", le.BuildUserDataString(mCustomer))); } catch { } } } } else { lstReturn = (List<Breed>)CachedList; } return lstReturn; }
public CoreService(string hostname, string username, string password, bool IsSecured) { if (IsSecured) { _client = CreateBasicHttpsClient(hostname); } else { _client = CreateBasicHttpClient(hostname); } _client.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(username, password); }
public static IEnumerable <string> ComponentURIsInFolder(this CoreServiceClient client, string folderId, string schemaId = null) { var filter = new OrganizationalItemItemsFilterData(); filter.ItemTypes = new ItemType[] { ItemType.Component }; if (schemaId != null) { filter.BasedOnSchemas = new[] { new LinkToSchemaData { IdRef = schemaId } } } ; var comps = client.GetListXml(folderId, filter); return(comps.Descendants().Select(itemElement => itemElement.Attribute("ID").Value)); }
/// <summary> /// Initializes a new instance of the <see cref="Client"/> class. /// </summary> /// <param name="targetUri">Target <see cref="T:System.Uri" /></param> /// <param name="domain">Optional domain</param> /// <param name="userName">Optional username</param> /// <param name="password">Optional password</param> public Client(Uri targetUri, String userName, String password) { mTargetUri = targetUri; mClient = new CoreServiceClient(ClientConfiguration.ClientHttpBinding, new EndpointAddress(ClientConfiguration.ClientHttpUri(targetUri))); if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password)) { mClient.ClientCredentials.UserName.UserName = userName; mClient.ClientCredentials.UserName.Password = password; mClient.ChannelFactory.Credentials.UserName.UserName = userName; mClient.ChannelFactory.Credentials.UserName.Password = password; } }
public PetColor[] GetColorList(PetfirstCustomer mCustomer) { PetColor[] lstReturn = null; string cacheKey = "$ColorList$"; object CachedList = m_Cache.Get(cacheKey) as PetColor[]; if (CachedList == null)//get from the service { CoreServiceReference.CoreServiceClient cs = new CoreServiceClient(); CoreServiceGetColorListResponse ccResponse = cs.GetColorList(); //insert select breed on the top if (string.IsNullOrEmpty(ccResponse.Error.ErrorText))//check error { if (ccResponse.Colors !=null) { lstReturn = ccResponse.Colors; m_Cache.Add(cacheKey, lstReturn); } } else { lstReturn = null; LogException le = new LogException(); try { le.LogError(HttpContext.Current.Request.Url.AbsoluteUri, "Error during getting color list", ccResponse.Error.ErrorText, mCustomer); ///Test email server //le.SendErrorEmail(string.Concat(Request.Url.AbsoluteUri, "<br/><hr />", msg, "<hr />User Input:", le.BuildUserDataString(mCustomer))); } catch (Exception ex) { ///Test email server //lblError.Text = ex.ToString(); try { le.SendErrorEmail(string.Concat(HttpContext.Current.Request.Url.AbsoluteUri, "<br/><hr />", ex.Message, "<br />StackTrace: ", ex.StackTrace, "<br /><hr />User Input:", le.BuildUserDataString(mCustomer))); } catch { } } } } else { lstReturn = (PetColor[])CachedList; } return lstReturn; }
/// <summary> /// Processes the core service record. /// </summary> /// <remarks>Used for proper error handling of core service fault exception.</remarks> protected override void ProcessCoreServiceRecord() { BatchesFilterData filter = new BatchesFilterData() { BaseColumns = CoreService.Client.ListBaseColumns.Default }; IEnumerable <BatchData> batchDatas = CoreServiceClient.GetSystemWideList(filter).Cast <BatchData>().ToList(); foreach (var batchData in batchDatas) { if (All || batchData.TotalNumberOfOperations == batchData.NumberOfDoneOperations) { CoreServiceClient.Delete(batchData.Id); WriteObject(batchData); } } }
public TridionItem GetByUri(string uri) { TridionItem tridionItem = new TridionItem(); try { CoreServiceClient client = new CoreServiceClient(); client.ClientCredentials.Windows.ClientCredential.UserName = ConfigurationManager.AppSettings["impersonationUser"].ToString(); // "administrator"; client.ClientCredentials.Windows.ClientCredential.Password = ConfigurationManager.AppSettings["impersonationPassword"].ToString(); client.ClientCredentials.Windows.ClientCredential.Domain = ConfigurationManager.AppSettings["impersonationDomain"].ToString(); IdentifiableObjectData objectData = client.Read(uri, null) as IdentifiableObjectData; FullVersionInfo versionInfo = objectData.VersionInfo as FullVersionInfo; tridionItem.Title = objectData.Title; tridionItem.Uri = uri; tridionItem.LastModifiedBy = versionInfo.Revisor.Title; } catch (Exception ex) { tridionItem.Error = ex.Source + ", " + ex.Message + ", " + ex.ToString(); } return tridionItem; }
protected static void PurgeFolderItems(string startFolder, ushort versionsToKeep, string pubUri) { using (CoreServiceClient client = new CoreServiceClient(endpointName)) { var credentials = CredentialCache.DefaultNetworkCredentials; if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { credentials = new NetworkCredential(userName, password); } client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; if (versionsToKeep < 0) return; PurgeOldVersionsInstructionData purgeIntructions = new PurgeOldVersionsInstructionData(); string folders = startFolder; if (folders != "") { PurgeFolders(client, folders, purgeIntructions, versionsToKeep, pubUri); } } }
/// <summary> /// Initializes the core service client. /// </summary> private void InitializeCoreServiceClient() { _Tcmclient = GetNewNetTcpClient(); }
public CoreServiceClient GetNewNetTcpClient() { string username = _Config.AppSettings.Settings["impersonation_user"].Value; string password = _Config.AppSettings.Settings["impersonation_password"].Value; string address = _Config.AppSettings.Settings["nettcpaddress"].Value; var binding = new NetTcpBinding { MaxReceivedMessageSize = 2147483647, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxStringContentLength = 2147483647, MaxArrayLength = 2147483647 } }; var endpoint = new EndpointAddress(address); var client = new CoreServiceClient(binding, endpoint); client.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(username, password); try { client.GetApiVersion(); } catch { return null; } return client; }
static void Main(string[] args) { coreServiceHandler = new CoreServiceHandler(configFilename); core = coreServiceHandler.GetNewNetTcpClient(); if (core == null) { Console.WriteLine("Could not login, please check config for credentials"); return; } else { Console.WriteLine("Start scan with Tridion for VBScript legacy code"); } //https://code.google.com/p/tridion-practice/wiki/LINQQueries var ppList = GetPublicationAndTheirParents(); StringBuilder sbReport = new StringBuilder(); bool backupVbScriptCodeToFile = coreServiceHandler.GetAppSetting("saveTemplateCode").Equals("true", StringComparison.OrdinalIgnoreCase); int ptAllCount = 0; int ctAllCount = 0; foreach (var publication in ppList) { int ptCount = 0; int ctCount = 0; Console.WriteLine(Environment.NewLine + "Scanning publication " + publication.Title); sbReport.Append(Environment.NewLine + "Scanning publication " + publication.Title + Environment.NewLine); var listOfPt = GetListOfType(publication.TcmId, ItemType.PageTemplate); var pubID = GetPublicationId(publication.TcmId); foreach (var ptitem in listOfPt.Items) { var ptd = core.Read(ptitem.TcmId, readOpts) as PageTemplateData; if (ptd != null && ptd.TemplateType != "CompoundTemplate") { ptCount++; var templateId = GetPublicationId(ptd.Id); // only report local templates if (pubID == templateId) { int pageCount = 0; string pages = GetPagesUsedByAPageTemplate(ptd.Id, out pageCount); if (pageCount > 0) { sbReport.AppendFormat("{0} ({1}) is {2} used in {3} pages:", ptd.LocationInfo.WebDavUrl, ptd.Id, ptd.TemplateType, pageCount).Append(Environment.NewLine); sbReport.AppendLine(pages); sbReport.AppendFormat("----------------------------").Append(Environment.NewLine); }else { sbReport.AppendFormat("{0} ({1}) is {2} is not used in pages", ptd.LocationInfo.WebDavUrl, ptd.Id, ptd.TemplateType).Append(Environment.NewLine); } if (backupVbScriptCodeToFile) { File.WriteAllText(ptd.Title + ".tpts.txt", ptd.Content); } } } Console.Write("."); } var listOfCt = GetListOfType(publication.TcmId, ItemType.ComponentTemplate); foreach (var ctitem in listOfCt.Items) { var ctd = core.Read(ctitem.TcmId, readOpts) as ComponentTemplateData; if (ctd != null && ctd.TemplateType != "CompoundTemplate") { ctCount++; var templateId = GetPublicationId(ctd.Id); int pageCount = 0; string pages = GetPagesUsedByAPageTemplate(ctd.Id, out pageCount); // only report local templates if (pubID == templateId) { if (pageCount > 0) { sbReport.AppendFormat("{0} ({1}) is {2} used in {3} pages:", ctd.LocationInfo.WebDavUrl, ctd.Id, ctd.TemplateType, pageCount).Append(Environment.NewLine); sbReport.AppendLine(pages); sbReport.AppendFormat("----------------------------").Append(Environment.NewLine); } else { sbReport.AppendFormat("{0} ({1}) is {2} is not used in pages", ctd.LocationInfo.WebDavUrl, ctd.Id, ctd.TemplateType).Append(Environment.NewLine); } } if (backupVbScriptCodeToFile) { File.WriteAllText(ctd.Title + ".tcts.txt", ctd.Content); } } Console.Write("."); } ctAllCount += ctCount; ptAllCount += ptCount; sbReport.AppendFormat("Found {0} PT's and {1} CT's with VBScript in publication '{2}'" + Environment.NewLine, ptCount, ctCount, publication.Title); } sbReport.AppendFormat(Environment.NewLine + "Found {0} PT's and {1} CT's with VBScript in all publications" + Environment.NewLine, ptAllCount, ctAllCount); Console.WriteLine(""); Console.WriteLine(sbReport.ToString()); Console.WriteLine("--------------------------"); File.WriteAllText(reportFile, sbReport.ToString()); Console.WriteLine("Saved report to " + reportFile); Console.WriteLine("Done.."); Console.ReadLine(); }
protected void btnContinue_Click(object sender, EventArgs e) { bool bError = false; if (mCustomer == null) { InitiatePetfirstCustomer(); } string url; try { mthisPet.PetName = txtPetName.Text; mthisPet.Birthday = DateTime.Today.AddYears(-(ddlAge.SelectedIndex - 1)); mthisPet.Birthday = mthisPet.Birthday.AddMonths(-6); mthisPet.BreedId = int.Parse(ddlBreed.SelectedValue.ToString()); mthisPet.BreedName = ddlBreed.SelectedItem.Text; mthisPet.ColorId = 146; mthisPet.ColorName = "Any"; mthisPet.SpeciesId = int.Parse(rblSpecies.SelectedValue.ToString()); mthisPet.SpeciesName = rblSpecies.SelectedItem.Text; //Handle Mixed if (ddlBreed.SelectedValue.ToString() == "10000") { mthisPet.WeightId = int.Parse(rbRadioButtonListMixed.SelectedValue); mthisPet.BreedId = 54; } if (bAddPet) { try { mthisPet.DeductibleAmount = 250; mthisPet.LimitAmount = 5000; mthisPet.Reimbursement = .8m; mthisPet.RiderName = ""; mthisPet.Routine = ""; int planId = 0; Int16 typeid = (short)(mCustomer.LifeTimeActive ? 2 : 1); using (PetfirstData pfData = new PetfirstData()) { planId = pfData.GetPlanId(mthisPet.LimitAmount, typeid); mCustomer.Underwriter = pfData.GetUnderwriterID(mCustomer.EnrollmentCode); mthisPet.PlanId = planId; mthisPet.QuoteId = 0; } PetfirstBL pfBl = new PetfirstBL(); if (!pfBl.GetFastQuote(ref mCustomer, ref mthisPet, true)) { List<Pet> lstEnrollPet = new List<Pet>(); lstEnrollPet.Add(mthisPet); pfBl.GetMonthlyQuote(ref mCustomer, lstEnrollPet); if (mCustomer.WebserviceErrorMsg.Equals("")) { pfBl.GetAnnualQuote(ref mCustomer, lstEnrollPet); } else { displayError("getting quote ", mCustomer.WebserviceErrorMsg, true); bError = true; } } } catch (Exception ex) { displayError("getting quote ", ex.ToString(), true); bError = true; } if (!bError) { url = "CustomizePlan.aspx"; Response.Redirect(url, false); Context.ApplicationInstance.CompleteRequest(); } } else if (bSamePet) { CoreServiceClient csc = new CoreServiceClient(); CoreServiceGetStateByZipResponse resp = csc.GetStateByZip(txtZip.Text); if (string.IsNullOrEmpty(resp.Error.ErrorText)) { mCustomer.MembershipInfo.StateId = resp.State.Id; mCustomer.MembershipInfo.City = resp.State.CityName; mCustomer.MembershipInfo.State = resp.State.StateName; mCustomer.MembershipInfo.Zip = txtZip.Text; mCustomer.DiscountMilitaryAvailable = mCustomer.DiscountMilitarySelected = false; mCustomer.DiscountVetAvailable = mCustomer.DiscountVetSelected = false; using (PetfirstData pfData = new PetfirstData()) { mCustomer.Underwriter = pfData.GetUnderwriterID(mCustomer.EnrollmentCode); if (mCustomer.Underwriter == 4) { CoreServiceGetDiscountByStateResponse response = csc.GetDiscountsByState(mCustomer.MembershipInfo.StateId); if (string.IsNullOrEmpty(resp.Error.ErrorText)) { foreach (Discount d in response.Discounts) { switch (d.DiscountID) { case 356: mCustomer.DiscountMilitaryAvailable = true; break; case 333: mCustomer.DiscountVetAvailable = true; break; default: break; } } } } } try { mthisPet.DeductibleAmount = 250; mthisPet.LimitAmount = 5000; mthisPet.Reimbursement = .8m; mthisPet.RiderName = ""; mthisPet.Routine = ""; int planId = 0; Int16 typeid = (short)(mCustomer.LifeTimeActive ? 2 : 1); using (PetfirstData pfData = new PetfirstData()) { planId = pfData.GetPlanId(mthisPet.LimitAmount, typeid); mCustomer.Underwriter = pfData.GetUnderwriterID(mCustomer.EnrollmentCode); mthisPet.PlanId = planId; mthisPet.QuoteId = 0; } PetfirstBL pfBl = new PetfirstBL(); if (!pfBl.GetFastQuote(ref mCustomer, ref mthisPet, true)) { List<Pet> lstEnrollPet = new List<Pet>(); lstEnrollPet.Add(mthisPet); pfBl.GetMonthlyQuote(ref mCustomer, lstEnrollPet); if (mCustomer.WebserviceErrorMsg.Equals("")) { pfBl.GetAnnualQuote(ref mCustomer, lstEnrollPet); } else { displayError("getting quote ", mCustomer.WebserviceErrorMsg, true); bError = true; } } } catch (Exception ex) { displayError("getting quote ", ex.ToString(), true); bError = true; } if (!bError) { url = "YourInformation.aspx?current_customer=true"; Response.Redirect(url, false); Context.ApplicationInstance.CompleteRequest(); } } } else { CoreServiceClient csc = new CoreServiceClient(); CoreServiceGetStateByZipResponse resp = csc.GetStateByZip(txtZip.Text); if (string.IsNullOrEmpty(resp.Error.ErrorText)) { mCustomer.MembershipInfo.StateId = resp.State.Id; mCustomer.MembershipInfo.City = resp.State.CityName; mCustomer.MembershipInfo.State = resp.State.StateName; mCustomer.MembershipInfo.Zip = txtZip.Text; using (PetfirstData pfData = new PetfirstData()) { mCustomer.Underwriter = pfData.GetUnderwriterID(mCustomer.EnrollmentCode); if (mCustomer.Underwriter == 4) { CoreServiceGetDiscountByStateResponse response = csc.GetDiscountsByState(mCustomer.MembershipInfo.StateId); if (string.IsNullOrEmpty(resp.Error.ErrorText)) { foreach (Discount d in response.Discounts) { switch (d.DiscountID) { case 356: mCustomer.DiscountMilitaryAvailable = true; break; case 333: mCustomer.DiscountVetAvailable = true; break; default: break; } } } } } url = "YourInformation.aspx"; Response.Redirect(url, false); Context.ApplicationInstance.CompleteRequest(); } else { lblError.Text = string.Concat("Sorry, we cannot find the zip you entered, please make sure the zip you entered is correct.<br />If you continue to get this message, please call ", mCustomer.CallCenter); } } } catch (Exception ex) { DisplayError("verifying your zip", ex.ToString(), true); } }
public PubTargetCreator(List<PublicationTarget> targets) { _coreServiceHandler = new CoreServiceHandler(configFilename); _core = _coreServiceHandler.GetNewNetTcpClient(); _targets = targets; }
private bool LoadCustomerInfo(ref PetfirstCustomer mCustomer, string scustomerLookup) { bool bReturn = true; SqlConnection con = GetConnection(); SqlDataReader sdr = null; SqlCommand cmd = new SqlCommand("usp_pricecompare_tmpcustomer_get_by_customer_id", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@customer_id", SqlDbType.BigInt)); cmd.Parameters["@customer_id"].Value = Int32.Parse(scustomerLookup); try { con.Open(); sdr = cmd.ExecuteReader(); while (sdr.Read()) { mCustomer.MembershipInfo.FirstName = sdr.GetString(CTFIRSTNAME); mCustomer.MembershipInfo.LastName = sdr.GetString(CTLASTNAME); mCustomer.EnrollmentCode = sdr.GetString(CTENROLLMENTCODE); using (PetfirstData pfData = new PetfirstData()) { mCustomer.CallCenter = pfData.GetPhoneNumber(mCustomer.EnrollmentCode); } mCustomer.MembershipInfo.Email = sdr.GetString(CTEMAIL); mCustomer.MembershipInfo.Zip = sdr.GetString(CTZIP); mCustomer.MembershipInfo.Phone = sdr.GetString(CTPHONE); if ((sdr.GetString(CTPAYFREQUENCY)).ToString().Contains("monthly") == true) { mCustomer.PayFrequency = 1; } else { mCustomer.PayFrequency = 2; } CoreServiceClient csc = new CoreServiceClient(); CoreServiceGetStateByZipResponse resp = csc.GetStateByZip(mCustomer.MembershipInfo.Zip); if (string.IsNullOrEmpty(resp.Error.ErrorText)) { mCustomer.MembershipInfo.StateId = resp.State.Id; mCustomer.MembershipInfo.City = resp.State.CityName; mCustomer.MembershipInfo.State = resp.State.StateName; } Pet myPet = new Pet(); myPet.Birthday = sdr.GetDateTime(CTPETBIRTHDAY); myPet.ColorId = 146; //Any Breed// myPet.ColorName = "Any"; if ((sdr.GetString(CTSPECIESNAME)).ToString().Contains("dog") == true) { myPet.SpeciesId = 1; myPet.SpeciesName = "Dog"; } else { myPet.SpeciesId = 2; myPet.SpeciesName = "Cat"; } myPet.BreedId = sdr.GetInt32(CTBREEDID); myPet.WeightId = sdr.GetByte(CTWEIGHTID); myPet.PetName = sdr.GetString(CTPETNAME); myPet.GenderFull = sdr.GetString(CTPETGENDER); myPet.GenderFull.Trim(); if (myPet.GenderFull.Contains("female")) { myPet.Gender = "F"; } else { myPet.Gender = "M"; } myPet.DeductibleAmount = sdr.GetDecimal(CTDEDUCTIBLE); myPet.Reimbursement = sdr.GetDecimal(CTREIMBURSEMENT); myPet.SpayedOrNeutered = sdr.GetBoolean(CTSPAYORNEUTER); //stored procedure will take care of figuring out if this is true or not. mCustomer.DiscountVetAvailable = true; mCustomer.DiscountMilitaryAvailable = true; mCustomer.DiscountMilitarySelected = sdr.GetBoolean(CTMILITARY); mCustomer.DiscountVetSelected = sdr.GetBoolean(CTVETPROFFESIONAL); mCustomer.MyPets.Add(myPet); try { using (PetfirstData pfData = new PetfirstData()) { pfData.SaveCustomer(mCustomer); } } catch { throw; } } con.Close(); } catch (Exception ex) { bReturn = false; LoggingError(ex.Message, ex.StackTrace); } finally { if (con != null) { con.Close(); con.Dispose(); con = null; } if (cmd != null) { cmd.Dispose(); cmd = null; } } return (bReturn); }
private static string GetAllPublications() { List<string> pubs = new List<string>(); using (CoreServiceClient client = new CoreServiceClient(endpointName)) { var credentials = CredentialCache.DefaultNetworkCredentials; if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { credentials = new NetworkCredential(userName, password); } client.ChannelFactory.Credentials.Windows.ClientCredential = credentials; PublicationsFilterData filter = new PublicationsFilterData(); XElement publications = client.GetSystemWideListXml(filter); XNamespace ns = publications.GetNamespaceOfPrefix("tcm"); foreach(XElement item in publications.DescendantNodes()) { pubs.Add(item.Attribute("ID").Value); } } string allPubs = string.Join(", ", Array.ConvertAll(pubs.ToArray(), i => i.ToString())); return allPubs; }
public List<MilitaryStatus> GetMilitaryStatusList(PetfirstCustomer mCustomer) { List<MilitaryStatus> lstReturn = new List<MilitaryStatus>(); string cacheKey = "$MilitaryStatusList$"; object CachedList = m_Cache.Get(cacheKey) as List<MilitaryBranch>; if (CachedList == null)//get from the service { CoreServiceReference.CoreServiceClient cs = new CoreServiceClient(); CoreServiceGetMilitaryStatusResponse ccResponse = cs.GetMilitaryStatusList(); foreach (MilitaryStatus ms in ccResponse.Status) { lstReturn.Add(ms); } if (lstReturn.Count > 0) { m_Cache.Add(cacheKey, lstReturn); } else { lstReturn = null; LogException le = new LogException(); try { le.LogError(HttpContext.Current.Request.Url.AbsoluteUri, "Error retreiving military status", ccResponse.Error.ErrorText, mCustomer); ///Test email server //le.SendErrorEmail(string.Concat(Request.Url.AbsoluteUri, "<br/><hr />", msg, "<hr />User Input:", le.BuildUserDataString(mCustomer))); } catch (Exception ex) { ///Test email server //lblError.Text = ex.ToString(); try { le.SendErrorEmail(string.Concat(HttpContext.Current.Request.Url.AbsoluteUri, "<br/><hr />", ex.Message, "<br />StackTrace: ", ex.StackTrace, "<br /><hr />User Input:", le.BuildUserDataString(mCustomer))); } catch { } } } } else { lstReturn = (List<MilitaryStatus>)CachedList; } return lstReturn; }
private static void PurgeFolders(CoreServiceClient client, string folders, PurgeOldVersionsInstructionData purgeIntructions, UInt16 versionsToKeep, string pubUri) { int totalCompVersionsRemoved = 0; string[] folderUris = folders.Split(','); List<LinkToIdentifiableObjectData> itemsToPurge = new List<LinkToIdentifiableObjectData>(); for (int i = 0; i < folderUris.Length; i++) { FolderData subFolder = null; // Add sub and subsub-folders to list to prevent timeouts... try { string localUri = GetLocalUri(pubUri.Trim(), folderUris[i]); subFolder = (FolderData)client.Read(localUri, null); } catch(Exception ex) { continue; } LinkToIdentifiableObjectData subfolderLink = new LinkToIdentifiableObjectData(); subfolderLink.IdRef = subFolder.Id; itemsToPurge.Add(subfolderLink); var itemTypes = new List<ItemType>(); //itemTypes.Add(ItemType.Component); itemTypes.Add(ItemType.Folder); var filter = new OrganizationalItemItemsFilterData(); filter.Recursive = true; filter.ItemTypes = itemTypes.ToArray(); purgeIntructions.VersionsToKeep = versionsToKeep; purgeIntructions.Recursive = false; IdentifiableObjectData[] allSubFolders = client.GetList(subFolder.Id, filter); foreach (var aFolder in allSubFolders) { LinkToIdentifiableObjectData folderLink = new LinkToIdentifiableObjectData(); folderLink.IdRef = aFolder.Id; itemsToPurge.Add(folderLink); purgeIntructions.Containers = itemsToPurge.ToArray(); try { int versionsCleaned = client.PurgeOldVersions(purgeIntructions); totalCompVersionsRemoved = totalCompVersionsRemoved + versionsCleaned; WriteOutput("Folder " + folderLink.IdRef + " removed " + versionsCleaned.ToString()); } catch (Exception ex) { throw; } itemsToPurge.Clear(); } } WriteOutput("Total Component versions removed is " + totalCompVersionsRemoved.ToString()); }
private static void PurgeStructureGroups(CoreServiceClient client, string structureGroups, PurgeOldVersionsInstructionData purgeIntructions, UInt16 versionsToKeep, string pubUri) { int totalPageVersionsRemoved = 0; string[] structureGroupUris = structureGroups.Split(','); List<LinkToIdentifiableObjectData> itemsToPurge = new List<LinkToIdentifiableObjectData>(); for (int i = 0; i < structureGroupUris.Length; i++) { StructureGroupData structureGroup = null; try { string localUri = GetLocalUri(pubUri.Trim(), structureGroupUris[i]); // Add sub and subsub-folders to list to prevent timeouts... structureGroup = (StructureGroupData)client.Read(localUri, null); } catch(Exception ex) { continue; } LinkToIdentifiableObjectData subfolderLink = new LinkToIdentifiableObjectData(); subfolderLink.IdRef = structureGroup.Id; itemsToPurge.Add(subfolderLink); var itemTypes = new List<ItemType>(); itemTypes.Add(ItemType.StructureGroup); var filter = new OrganizationalItemItemsFilterData(); filter.Recursive = true; filter.ItemTypes = itemTypes.ToArray(); purgeIntructions.VersionsToKeep = versionsToKeep; purgeIntructions.Recursive = false; IdentifiableObjectData[] subSGs = client.GetList(structureGroup.Id, filter); foreach (var subSubSG in subSGs) { LinkToIdentifiableObjectData structureGroupLink = new LinkToIdentifiableObjectData(); structureGroupLink.IdRef = subSubSG.Id; itemsToPurge.Add(structureGroupLink); purgeIntructions.Containers = itemsToPurge.ToArray(); try { int versionsCleaned = client.PurgeOldVersions(purgeIntructions); totalPageVersionsRemoved = totalPageVersionsRemoved + versionsCleaned; WriteOutput("Removed " + versionsCleaned.ToString() + " Page Versions"); } catch (Exception ex) { throw; } itemsToPurge.Clear(); } } WriteOutput("Total Page versions removed is " + totalPageVersionsRemoved.ToString()); }
public CoreServiceClient GetNewNetTcpClient() { string username = _Config.AppSettings.Settings["impersonation_user"].Value; string password = _Config.AppSettings.Settings["impersonation_password"].Value; var binding = new NetTcpBinding { MaxReceivedMessageSize = 2147483647, ReaderQuotas = new XmlDictionaryReaderQuotas { MaxStringContentLength = 2147483647, MaxArrayLength = 2147483647 } }; var endpoint = new EndpointAddress("net.tcp://localhost:2660/CoreService/2011/netTcp"); var client = new CoreServiceClient(binding, endpoint); client.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(username, password); return client; }