public override IntegrationProcessResultEnum ProcessInternalTaskAsync(GeneralizedInfo infoObj, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnum dataType, string siteName, out string errorMessage) { try { //Determine if the record exists in Azure Storage // Retrieve the storage account from the connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(SettingsKeyInfoProvider.GetValue("Custom.AzureStorageConnectionString")); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "kenticousers" table. CloudTable table = tableClient.GetTableReference("kenticousers"); // Create a retrieve operation that takes a customer entity. TableOperation retrieveOperation = TableOperation.Retrieve<KenticoUserEntity>(ValidationHelper.GetString(infoObj["UserGUID"], ""), ValidationHelper.GetString(infoObj["LastName"], "")); // Execute the operation. TableResult retrievedResult = table.Execute(retrieveOperation); // Assign the result to a CustomerEntity object. KenticoUserEntity existinguser = (KenticoUserEntity)retrievedResult.Result; //Check if the record already exists if (existinguser == null) { // create a new record KenticoUserEntity newuser = new KenticoUserEntity(ValidationHelper.GetString(infoObj["UserGUID"], ""), ValidationHelper.GetString(infoObj["LastName"], "")); newuser.firstname = ValidationHelper.GetString(infoObj["FirstName"], ""); newuser.lastname = ValidationHelper.GetString(infoObj["LastName"], ""); newuser.email = ValidationHelper.GetString(infoObj["Email"], ""); // Create the Insert TableOperation TableOperation insertOperation = TableOperation.Insert(newuser); // Execute the operation. table.Execute(insertOperation); EventLogProvider.LogEvent("I", "CustomIntegrationConnector", "Information", "Record inserted!"); } else { //update the record existinguser.firstname = ValidationHelper.GetString(infoObj["FirstName"], ""); existinguser.lastname = ValidationHelper.GetString(infoObj["LastName"], ""); existinguser.email = ValidationHelper.GetString(infoObj["Email"], ""); // Create the Update TableOperation TableOperation updateOperation = TableOperation.Replace(existinguser); // Execute the operation. table.Execute(updateOperation); EventLogProvider.LogEvent("I", "CustomIntegrationConnector", "Information", "Record updated!"); } //Set the error message to null and the response to OK errorMessage = null; return IntegrationProcessResultEnum.OK; } catch (Exception ex) { //There was a problem. errorMessage = ex.Message; return IntegrationProcessResultEnum.ErrorAndSkip; } }
/// <summary> /// Reloads the data for the UniGrid control displaying the objects related to the current object. /// </summary> private void gridItems_OnBeforeDataReload() { loaded = true; registeredObjects.Clear(); // Prepare the translations table th = new TranslationHelper(); th.UseDisplayNameAsCodeName = true; }
/// <summary> /// Processes given object according to task type. /// It is expected that you use TranslateColumnsToExternal method before you process the task. /// The TranslateColumnsToExternal needs GetExternalObjectID and GetExternalDocumentID to be implemented. /// It traverses the given object and tries to translate foreign keys to match external (your) application. /// </summary> /// <param name="infoObj">Info object to process</param> /// <param name="translations">Translation helper object containing translations for given object</param> /// <param name="taskType">Type of task</param> /// <param name="dataType">Type of data</param> /// <param name="siteName">Name of site</param> /// <param name="errorMessage">Possible error message</param> /// <returns>Result of processing</returns> public override IntegrationProcessResultEnum ProcessInternalTaskAsync(GeneralizedInfo infoObj, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnum dataType, string siteName, out string errorMessage) { try { // If object is of 'user' type // You can also use following condition: (((BaseInfo)infoObj) is CMS.SiteProvider.UserInfo) if (infoObj.ObjectType == PredefinedObjectType.USER) { bool log = false; // Create simple message string message = "User with username '" + infoObj.ObjectCodeName + "' has been"; switch (taskType) { case TaskTypeEnum.CreateObject: log = true; message += " created."; break; case TaskTypeEnum.UpdateObject: log = true; message += " updated."; break; case TaskTypeEnum.DeleteObject: log = true; message += " deleted."; break; } if (log) { EventLogProvider eventLog = new EventLogProvider(); // Log the message eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, ConnectorName, taskType.ToString(), 0, null, 0, null, null, message, 0, null); } } errorMessage = null; return IntegrationProcessResultEnum.OK; } catch (Exception ex) { errorMessage = ex.Message; return IntegrationProcessResultEnum.Error; } finally { // Clear translations cached during TranslateColumnsToExternal which internally calls GetExternalObjectID, GetExternalDocumentID // This call is optional but recommended in the case where eg. collision of code names can occur ClearInternalTranslations(); } }
/// <summary> /// Processes given document according to task type. /// It is expected that you use TranslateColumnsToExternal method before you process the task. /// The TranslateColumnsToExternal needs GetExternalObjectID and GetExternalDocumentID to be implemented. /// It traverses the given object and tries to translate foreign keys to match external (your) application. /// </summary> /// <param name="node">Document to process</param> /// <param name="translations">Translation helper object containing translations for given document</param> /// <param name="taskType">Type of task</param> /// <param name="dataType">Type of data</param> /// <param name="siteName">Name of site</param> /// <param name="errorMessage">Possible error message</param> /// <returns>Result of processing</returns> public override IntegrationProcessResultEnum ProcessInternalTaskAsync(TreeNode node, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnum dataType, string siteName, out string errorMessage) { try { bool log = false; // Create simple message string message = "Document named '" + node.NodeName + "' located at '" + node.NodeAliasPath + "' has been"; switch (taskType) { case TaskTypeEnum.CreateDocument: log = true; message += " created."; break; case TaskTypeEnum.UpdateDocument: log = true; message += " updated."; break; case TaskTypeEnum.DeleteDocument: log = true; message += " deleted."; break; } if (log) { EventLogProvider eventLog = new EventLogProvider(); // Log the message eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, ConnectorName, taskType.ToString(), 0, null, node.NodeID, node.DocumentName, null, message, node.NodeSiteID, null); } errorMessage = null; return IntegrationProcessResultEnum.OK; } catch (Exception ex) { errorMessage = ex.Message; return IntegrationProcessResultEnum.Error; } finally { // Clear translations cached during TranslateColumnsToExternal which internally calls GetExternalObjectID, GetExternalDocumentID // This call is optional but recommended in the case where eg. collision of code names can occur ClearInternalTranslations(); } }
string ITranslationEngine.MapCultureToSourceLanguageCode(string appID, CultureInfo cultureInfo) { return(TranslationHelper.DoMapCultureToLanguageCode( ((ITranslationEngine)this).GetSourceLanguages(appID), cultureInfo)); }
/// <summary> /// Reloads the data for the UniGrid control displaying the objects related to the current object. /// </summary> private void ReloadData() { loaded = true; registeredObjects.Clear(); gridItems.WhereCondition = GetWhereCondition(drpRelatedObjType.SelectedItem.Value); // Prepare the translations table th = new TranslationHelper(); th.UseDisplayNameAsCodeName = true; gridItems.ReloadData(); }
bool ITranslationEngine.IsDestinationLanguageSupported(string appID, string languageCode) { return(TranslationHelper.IsSupportedLanguage(languageCode, ((ITranslationEngine)this).GetDestinationLanguages(appID))); }
private void AddIndiceDocumento(string descricao, string caminhoFicheiro, string nomeFicheiro, ResourceAccessType tipoAcessoRecurso) { if ((tipoAcessoRecurso == ResourceAccessType.Smb || tipoAcessoRecurso == ResourceAccessType.Web) && !(ImageHelper.isValidImageResource(caminhoFicheiro + nomeFicheiro, tipoAcessoRecurso))) { return; } if ((tipoAcessoRecurso == ResourceAccessType.DICAnexo || tipoAcessoRecurso == ResourceAccessType.DICConteudo) && !(ImageHelper.isValidImageResource(caminhoFicheiro, nomeFicheiro, tipoAcessoRecurso))) { return; } GISADataset.SFRDImagemVolumeRow imgVolRow = getImagemVolume(caminhoFicheiro); long maxOrdem = GetImgMaxOrdem(); GISADataset.SFRDImagemRow imgRow = null; imgRow = GisaDataSetHelper.GetInstance().SFRDImagem.AddSFRDImagemRow(CurrentFRDBase, maxOrdem + 1, TranslationHelper.FormatTipoAcessoEnumToTipoAcessoText(tipoAcessoRecurso), descricao, imgVolRow, nomeFicheiro, new byte[] { }, 0); ListViewItem item = null; item = lstVwIndiceDocumento.Items.Add(descricao); item.SubItems.Add(caminhoFicheiro); item.SubItems.Add(nomeFicheiro); item.Tag = imgRow; }
private void btnEdit_Click(object sender, EventArgs e) { if (lstVwIndiceDocumento.SelectedItems.Count == 1) { GISADataset.SFRDImagemRow imgRow = null; imgRow = (GISADataset.SFRDImagemRow)(lstVwIndiceDocumento.SelectedItems[0].Tag); FormImagem form = new FormImagem(CurrentFRDBase.IDNivel.ToString()); form.Text = "Alterar Imagem / Objeto Digital"; form.Descricao = imgRow.Descricao; form.cbTipoAcessoRecurso.SelectedItem = imgRow.Tipo; if (imgRow.Tipo.Equals(TranslationHelper.FormatTipoAcessoEnumToTipoAcessoText(ResourceAccessType.DICAnexo))) { form.NomeFicheiroDIP = imgRow.Identificador; form.NUDDIP = imgRow.SFRDImagemVolumeRow.Mount; form.ValidLocation = form.NomeFicheiroDIP; form.ValidLocationParams = form.NUDDIP; } else if (imgRow.Tipo.Equals(TranslationHelper.FormatTipoAcessoEnumToTipoAcessoText(ResourceAccessType.DICConteudo))) { form.NUDDIP = imgRow.Identificador; form.ValidLocation = form.NUDDIP; } else { form.Identificador = imgRow.SFRDImagemVolumeRow.Mount + imgRow.Identificador; form.ValidLocation = form.Identificador; } Image currentImage = null; Size currentImageSize = new Size(); Size viewportSize = new Size(); currentImage = ImageViewerControl1.pictImagem.Image; if (currentImage != null) { currentImageSize = currentImage.Size; viewportSize = form.ImageViewerControl1.grpImagem.Size; Size newSize = ImageHelper.getSizeSameAspectRatio(currentImageSize, viewportSize); Image newImg = FormImageViewer.resizeImage(currentImage, newSize); form.ImageViewerControl1.pictImagem.Image = newImg; form.ImageViewerControl1.pictImagem.Size = form.ImageViewerControl1.grpImagem.Size; } if (form.ShowDialog() == DialogResult.OK) { string identificador, descricao, caminho; identificador = form.Identificador; descricao = form.Descricao; caminho = form.Identificador; ListViewItem item = null; item = lstVwIndiceDocumento.SelectedItems[0]; item.SubItems[0].Text = descricao; item.SubItems[1].Text = getPathFromFullPath(caminho, form.TipoAcessoRecurso); item.SubItems[2].Text = getFilenameFromFullPath(identificador, form.TipoAcessoRecurso); ViewToModel(item, TranslationHelper.FormatTipoAcessoEnumToTipoAcessoText(form.TipoAcessoRecurso)); RefreshDetails(); RefreshButtonsState(); } } }
public List <string> Translate(string sourceLanguage, string targetLanguage, List <Paragraph> sourceParagraphs) { var baseUrl = "https://translation.googleapis.com/language/translate/v2"; var format = "text"; var input = new StringBuilder(); var formatList = new List <Formatting>(); for (var index = 0; index < sourceParagraphs.Count; index++) { var p = sourceParagraphs[index]; var f = new Formatting(); formatList.Add(f); if (input.Length > 0) { input.Append("&"); } var text = f.SetTagsAndReturnTrimmed(TranslationHelper.PreTranslate(p.Text, sourceLanguage), sourceLanguage); text = f.UnBreak(text, p.Text); input.Append("q=" + Utilities.UrlEncode(text)); } string uri = $"{baseUrl}/?{input}&target={targetLanguage}&source={sourceLanguage}&format={format}&key={_apiKey}"; string content; try { var request = WebRequest.Create(uri); request.Proxy = Utilities.GetProxy(); request.ContentType = "application/json"; request.ContentLength = 0; request.Method = "POST"; var response = request.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); content = reader.ReadToEnd(); } catch (WebException webException) { var message = string.Empty; if (webException.Message.Contains("(400) Bad Request")) { message = "API key invalid (or perhaps billing is not enabled)?"; } else if (webException.Message.Contains("(403) Forbidden.")) { message = "Perhaps billing is not enabled (or API key is invalid)?"; } throw new TranslationException(message, webException); } var skipCount = 0; var resultList = new List <string>(); var parser = new JsonParser(); var x = (Dictionary <string, object>)parser.Parse(content); foreach (var k in x.Keys) { if (x[k] is Dictionary <string, object> v) { foreach (var innerKey in v.Keys) { if (v[innerKey] is List <object> l) { foreach (var o2 in l) { if (o2 is Dictionary <string, object> v2) { foreach (var innerKey2 in v2.Keys) { if (v2[innerKey2] is string translatedText) { translatedText = Regex.Unescape(translatedText); translatedText = string.Join(Environment.NewLine, translatedText.SplitToLines()); translatedText = TranslationHelper.PostTranslate(translatedText, targetLanguage); if (resultList.Count - skipCount < formatList.Count) { translatedText = formatList[resultList.Count - skipCount].ReAddFormatting(translatedText); translatedText = formatList[resultList.Count - skipCount].ReBreak(translatedText, targetLanguage); } resultList.Add(translatedText); } } } } } } } } return(resultList); }
internal ViewerWindow() { // this object should be initialized before loading UI components, because many of which are binding to it. ContextObject = new ContextObject(); ContextObject.PropertyChanged += ContextObject_PropertyChanged; InitializeComponent(); Icon = (App.IsWin10 ? Properties.Resources.app_white_png : Properties.Resources.app_png).ToBitmapSource(); FontFamily = new FontFamily(TranslationHelper.Get("UI_FontFamily", failsafe: "Segoe UI")); SizeChanged += SaveWindowSizeOnSizeChanged; StateChanged += (sender, e) => _ignoreNextWindowSizeChange = true; // bring the window to top when users click in the client area. // the non-client area is handled by the WndProc inside OnSourceInitialized(). PreviewMouseDown += (sender, e) => this.BringToFront(false); windowFrameContainer.PreviewMouseMove += ShowWindowCaptionContainer; Topmost = SettingHelper.Get("Topmost", false); buttonTop.Tag = Topmost ? "Top" : "Auto"; buttonTop.Click += (sender, e) => { Topmost = !Topmost; SettingHelper.Set("Topmost", Topmost); buttonTop.Tag = Topmost ? "Top" : "Auto"; }; buttonPin.Click += (sender, e) => { if (Pinned) { return; } ViewWindowManager.GetInstance().ForgetCurrentWindow(); }; buttonCloseWindow.Click += (sender, e) => { if (Pinned) { BeginClose(); } else { ViewWindowManager.GetInstance().ClosePreview(); } }; buttonOpen.Click += (sender, e) => { if (Pinned) { RunAndClose(); } else { ViewWindowManager.GetInstance().RunAndClosePreview(); } }; buttonWindowStatus.Click += (sender, e) => WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; buttonShare.Click += (sender, e) => ShareHelper.Share(_path, this); buttonOpenWith.Click += (sender, e) => ShareHelper.Share(_path, this, true); }