コード例 #1
0
        static void Sync(string culture, string input, string output)
        {
            SyncTranslator job = new SyncTranslator(cc, culture);

            Console.WriteLine("Adding files");
            Console.WriteLine("Input: " + input);
            Console.WriteLine("Output: " + output);
            job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
            ClientResult <TranslationItemInfo> cr = job.Translate(input, output);

            cc.ExecuteQuery();
            Console.WriteLine(DateTime.Now);
            Console.WriteLine("OutputSaveBehavior: {0}", job.OutputSaveBehavior.ToString());
            Console.WriteLine("Input: " + cr.Value.InputFile);
            Console.WriteLine("Output: " + cr.Value.OutputFile);
            Console.WriteLine("ErrorMessage: " + cr.Value.ErrorMessage);
            Console.WriteLine("TranslationId: " + cr.Value.TranslationId);
            Console.WriteLine("JobStatus....");
            Console.WriteLine("Succeeded: " + cr.Value.Succeeded);
            Console.WriteLine("Failed: " + cr.Value.Failed);
            Console.WriteLine("Canceled: " + cr.Value.Canceled);
            Console.WriteLine("InProgress: " + cr.Value.InProgress);
            Console.WriteLine("NotStarted: " + cr.Value.NotStarted);
            Console.WriteLine(DateTime.Now);
            Console.WriteLine("Done");
        }
コード例 #2
0
        private void sync_Click(object sender, RoutedEventArgs e)
        {
            CreateClientContext();
            SyncTranslator job    = new SyncTranslator(cc, this.culture.Text);
            string         input  = this.inputFile.Text;
            string         output = this.outputFile.Text;

            job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
            ClientResult <TranslationItemInfo> cr = job.Translate(input, output);

            ThreadPool.QueueUserWorkItem(new WaitCallback(CreateThreadForSync), cr);
        }
コード例 #3
0
    /// <summary>
    /// submit a sync job to translate a file
    /// </summary>
    /// <param name="culture">target langauge</param>
    /// <param name="input">full URL of input file on SharePoint</param>
    /// <param name="output">full URL of output file on SharePoint</param>
    static void AddSyncFile(string culture, string input, string output)
    {
        SyncTranslator job = createSyncTranslationJob(culture);

        Console.WriteLine("Adding files");
        Console.WriteLine("Input: " + input);
        Console.WriteLine("Output: " + output);
        TranslationItemInfo itemInfo = job.Translate(input, output);

        Console.WriteLine("Targetlang: {0}", job.TargetLanguage.Name);
        Console.WriteLine("OutputSaveBehavior: {0}", job.OutputSaveBehavior.ToString());
        PrintItemInfo(itemInfo);
    }
コード例 #4
0
    /// <summary>
    /// submit a sync job to translate stream
    /// the input file will be converted to stream and send to translation
    /// </summary>
    /// <param name="culture">target langauge</param>
    /// <param name="input">input file location (not on SharePoint)</param>
    /// <param name="output">output file location (not on SharePoint)</param>
    /// <param name="fileFormat">file extension of the input file</param>
    static void AddSyncStream(string culture, string input, string output, string fileFormat)
    {
        SyncTranslator      job          = createSyncTranslationJob(culture);
        FileStream          inputStream  = new FileStream(input, FileMode.Open);
        FileStream          outputStream = new FileStream(output, FileMode.Create);
        TranslationItemInfo itemInfo     = job.Translate(inputStream, outputStream, fileFormat);

        Console.WriteLine("Targetlang: {0}", job.TargetLanguage.Name);
        Console.WriteLine("OutputSaveBehavior: {0}", job.OutputSaveBehavior.ToString());
        PrintItemInfo(itemInfo);
        inputStream.Close();
        outputStream.Flush();
        outputStream.Close();
    }
コード例 #5
0
    /// <summary>
    /// submit a sync job to translate array of bytes
    /// the input file will be converted to array of bytes and send to translation
    /// </summary>
    /// <param name="culture">target langauge</param>
    /// <param name="input">input file location (not on SharePoint)</param>
    /// <param name="output">output file location (not on SharePoint)</param>
    /// <param name="fileFormat">file extension of the input file</param>
    static void AddSyncByte(string culture, string input, string output, string fileFormat)
    {
        SyncTranslator job = createSyncTranslationJob(culture);

        Byte[] inputByte;
        Byte[] outputByte;
        inputByte  = File.ReadAllBytes(input);
        outputByte = null;
        TranslationItemInfo itemInfo = job.Translate(inputByte, out outputByte, fileFormat);

        Console.WriteLine("Targetlang: {0}", job.TargetLanguage.Name);
        Console.WriteLine("OutputSaveBehavior: {0}", job.OutputSaveBehavior.ToString());
        PrintItemInfo(itemInfo);
        Console.WriteLine("Writing to output file");
        FileStream   outputStream = File.Open(output, FileMode.Create);
        MemoryStream memoryStream = new MemoryStream(outputByte);

        memoryStream.WriteTo(outputStream);
        outputStream.Flush();
        outputStream.Close();
    }
コード例 #6
0
 static void Sync(string culture, string input, string output)
 {
     SyncTranslator job = new SyncTranslator(cc, culture);
     Console.WriteLine("Adding files");
     Console.WriteLine("Input: " + input);
     Console.WriteLine("Output: " + output);
     job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
     ClientResult<TranslationItemInfo> cr = job.Translate(input, output);
     cc.ExecuteQuery();
     Console.WriteLine(DateTime.Now);
     Console.WriteLine("OutputSaveBehavior: {0}", job.OutputSaveBehavior.ToString());
     Console.WriteLine("Input: " + cr.Value.InputFile);
     Console.WriteLine("Output: " + cr.Value.OutputFile);
     Console.WriteLine("ErrorMessage: " + cr.Value.ErrorMessage);
     Console.WriteLine("TranslationId: " + cr.Value.TranslationId);
     Console.WriteLine("JobStatus....");
     Console.WriteLine("Succeeded: " + cr.Value.Succeeded);
     Console.WriteLine("Failed: " + cr.Value.Failed);
     Console.WriteLine("Canceled: " + cr.Value.Canceled);
     Console.WriteLine("InProgress: " + cr.Value.InProgress);
     Console.WriteLine("NotStarted: " + cr.Value.NotStarted);
     Console.WriteLine(DateTime.Now);
     Console.WriteLine("Done");
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Read the data that has been posted
            connectedSiteUrl = Request.Form["connectedSiteUrl"];
            accessToken = Request.Form["accessToken"];
            refreshToken = Request.Form["refreshToken"];

            // Note that the following form fields were set dynamically by JavaScript
            // to represent the data from the document to be translated and the target language
            string documentContent = string.Empty;
            string targetLanguage = string.Empty;
            documentContent = Request.Form["documentContent"];
            targetLanguage = Request.Form["documentLanguage"];
            try
            {
                using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(connectedSiteUrl, accessToken))
                {
                    // Use standard CSOM and OOXML approaches for creating a file
                    Web thisWeb = context.Web;
                    List docLib = thisWeb.Lists.GetByTitle("Documents");
                    Folder rootFolder = docLib.RootFolder;
                    context.Load(thisWeb);
                    context.Load(docLib);
                    context.Load(rootFolder);
                    context.ExecuteQuery();
                    FileStream fs = null;
                    try
                    {

                        // We'll build a Word Document by using OOXML
                        // Note that we'll first create it in a folder in this Web app.
                        using (WordprocessingDocument wordDocument =
                            WordprocessingDocument.Create(Server.MapPath("~/TempOOXML/SourceDocument.docx"),
                            WordprocessingDocumentType.Document))
                        {

                            // Add a main document part.
                            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                            // Create the document structure.
                            mainPart.Document = new Document();
                            Body body = mainPart.Document.AppendChild(new Body());

                            // Create a paragraph based on the text that was posted
                            // in Request.Form["documentContent"]
                            Paragraph para = body.AppendChild(new Paragraph());
                            Run run = para.AppendChild(new Run());
                            run.AppendChild(new Text(documentContent));

                        }

                        // At this stage, the local file has been created in the folder of this Web project
                        // so we'll now read it and create a new file in SharePoint, based on this local file.
                        byte[] documentBytes;
                        fs = System.IO.File.OpenRead(Server.MapPath("~/TempOOXML/SourceDocument.docx"));
                        documentBytes = new byte[fs.Length];
                        fs.Read(documentBytes, 0, Convert.ToInt32(fs.Length));

                        // At this stage, the file contents of the OOXML document has been read into the byte array
                        // so we can use that as the content of a new file in SharePoint.
                        Microsoft.SharePoint.Client.FileCreationInformation ooxmlFile
                            = new Microsoft.SharePoint.Client.FileCreationInformation();
                        ooxmlFile.Overwrite = true;
                        ooxmlFile.Url = thisWeb.Url
                            + rootFolder.ServerRelativeUrl
                            + "/SharePointSourceDocument.docx";
                        ooxmlFile.Content = documentBytes;
                        Microsoft.SharePoint.Client.File newFile = rootFolder.Files.Add(ooxmlFile);
                        context.Load(newFile);
                        context.ExecuteQuery();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        // Tell the user what went wrong. These variables will be used
                        // to report the error to the user in the TextTranslator.aspx page.
                        success = false;
                        exception = ex;

                    }
                    finally
                    {
                        // Clean up our filestream object
                        fs.Close();
                    }

                    // Do the actual translation work. Note that we use a synchronous translation
                    // approach here, but you could also use the TranslationJob object to
                    // perform an asynchronous translation.
                    if (success)
                    {
                        try
                        {
                            SyncTranslator job = new SyncTranslator(context, targetLanguage);
                            job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
                            job.Translate(
                                thisWeb.Url + rootFolder.ServerRelativeUrl + "/SharePointSourceDocument.docx",
                                thisWeb.Url + rootFolder.ServerRelativeUrl + "/" + targetLanguage + "_Document.docx");
                            context.ExecuteQuery();
                            targetLibrary = thisWeb.Url + rootFolder.ServerRelativeUrl;
                        }
                        catch (Exception ex)
                        {
                            // Tell the user what went wrong. These variables will be used
                            // to report the error to the user in the TextTranslator.aspx page.
                            success = false;
                            exception = ex;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Tell the user what went wrong. These variables will be used
                // to report the error to the user in the TextTranslator.aspx page.
                success = false;
                exception = ex;
            }
        }
コード例 #8
0
        public ActionResult File()
        {
            try
            {
                Uri hostWebUri = new Uri(Request.QueryString["SPHostUrl"]);
                Uri appWebUri  = new Uri(Request.QueryString["SPAppWebUrl"]);

                string listId     = Request.QueryString["SPListId"];
                string listItemId = Request.QueryString["SPListItemId"];

                string culture     = string.Empty;
                string destination = string.Empty;

                //Get the settings
                List <Setting> settings = new List <Setting>();

                using (ClientContext ctx = TokenHelper.GetS2SClientContextWithWindowsIdentity(appWebUri, Request.LogonUserIdentity))
                {
                    List settingsList = ctx.Web.Lists.GetByTitle("Settings");
                    ctx.Load(settingsList);

                    ListItemCollection settingItems = settingsList.GetItems(CamlQuery.CreateAllItemsQuery());
                    ctx.Load(settingItems);

                    ctx.ExecuteQuery();

                    foreach (ListItem settingItem in settingItems)
                    {
                        settings.Add(new Setting()
                        {
                            Title = settingItem["Title"].ToString(),
                            Value = settingItem["Value"].ToString(),
                        });
                    }
                }

                culture     = settings.Where <Setting>(s => s.Title == "Culture").FirstOrDefault().Value;
                destination = settings.Where <Setting>(s => s.Title == "Destination").FirstOrDefault().Value;

                //Translate file synchronously
                using (ClientContext ctx = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWebUri, Request.LogonUserIdentity))
                {
                    //Get the file to translate
                    ListItem listItem = ctx.Web.Lists.GetById(new Guid(listId)).GetItemById(listItemId);
                    ctx.Load(listItem, i => i.File);
                    ctx.ExecuteQuery();

                    //Get the destination library
                    Folder destinationFolder = ctx.Web.Lists.GetByTitle(destination).RootFolder;
                    ctx.Load(destinationFolder, f => f.ServerRelativeUrl);
                    ctx.ExecuteQuery();

                    string ext        = listItem.File.Name.Substring(listItem.File.Name.LastIndexOf("."));
                    string inPath     = hostWebUri.Scheme + "://" + hostWebUri.Authority + ":" + hostWebUri.Port + listItem.File.ServerRelativeUrl;
                    string outPath    = hostWebUri.Scheme + "://" + hostWebUri.Authority + ":" + hostWebUri.Port + destinationFolder.ServerRelativeUrl + "/" + listItem.File.Name;
                    string returnPath = hostWebUri.Scheme + "://" + hostWebUri.Authority + ":" + hostWebUri.Port + destinationFolder.ServerRelativeUrl;
                    ViewBag.ReturnPath = returnPath;

                    //Check if extension is supported
                    ClientResult <bool> isSupported = TranslationJob.IsFileExtensionSupported(ctx, ext.Substring(1));
                    ctx.ExecuteQuery();
                    if (!isSupported.Value)
                    {
                        throw new Exception("File extension is not supported.");
                    }

                    //Translate
                    SyncTranslator job = new SyncTranslator(ctx, culture);
                    job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
                    ClientResult <TranslationItemInfo> cr = job.Translate(inPath, outPath);
                    ctx.ExecuteQuery();

                    if (!cr.Value.Succeeded)
                    {
                        throw new Exception(cr.Value.ErrorMessage);
                    }

                    //Return to library
                    Response.Redirect(returnPath);
                }
            }
            catch (Exception x)
            {
                ViewBag.Message = x.Message;
            }

            return(View());
        }
コード例 #9
0
 private void sync_Click(object sender, RoutedEventArgs e)
 {
     CreateClientContext();
     SyncTranslator job = new SyncTranslator(cc, this.culture.Text);
     string input = this.inputFile.Text;
     string output = this.outputFile.Text;
     job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
     ClientResult<TranslationItemInfo> cr = job.Translate(input, output);
     ThreadPool.QueueUserWorkItem(new WaitCallback(CreateThreadForSync), cr);
 }
コード例 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Read the data that has been posted
            connectedSiteUrl = Request.Form["connectedSiteUrl"];
            accessToken      = Request.Form["accessToken"];
            refreshToken     = Request.Form["refreshToken"];

            // Note that the following form fields were set dynamically by JavaScript
            // to represent the data from the document to be translated and the target language
            string documentContent = string.Empty;
            string targetLanguage  = string.Empty;

            documentContent = Request.Form["documentContent"];
            targetLanguage  = Request.Form["documentLanguage"];
            try
            {
                using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(connectedSiteUrl, accessToken))
                {
                    // Use standard CSOM and OOXML approaches for creating a file
                    Web    thisWeb    = context.Web;
                    List   docLib     = thisWeb.Lists.GetByTitle("Documents");
                    Folder rootFolder = docLib.RootFolder;
                    context.Load(thisWeb);
                    context.Load(docLib);
                    context.Load(rootFolder);
                    context.ExecuteQuery();
                    FileStream fs = null;
                    try
                    {
                        // We'll build a Word Document by using OOXML
                        // Note that we'll first create it in a folder in this Web app.
                        using (WordprocessingDocument wordDocument =
                                   WordprocessingDocument.Create(Server.MapPath("~/TempOOXML/SourceDocument.docx"),
                                                                 WordprocessingDocumentType.Document))
                        {
                            // Add a main document part.
                            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                            // Create the document structure.
                            mainPart.Document = new Document();
                            Body body = mainPart.Document.AppendChild(new Body());

                            // Create a paragraph based on the text that was posted
                            // in Request.Form["documentContent"]
                            Paragraph para = body.AppendChild(new Paragraph());
                            Run       run  = para.AppendChild(new Run());
                            run.AppendChild(new Text(documentContent));
                        }

                        // At this stage, the local file has been created in the folder of this Web project
                        // so we'll now read it and create a new file in SharePoint, based on this local file.
                        byte[] documentBytes;
                        fs            = System.IO.File.OpenRead(Server.MapPath("~/TempOOXML/SourceDocument.docx"));
                        documentBytes = new byte[fs.Length];
                        fs.Read(documentBytes, 0, Convert.ToInt32(fs.Length));


                        // At this stage, the file contents of the OOXML document has been read into the byte array
                        // so we can use that as the content of a new file in SharePoint.
                        Microsoft.SharePoint.Client.FileCreationInformation ooxmlFile
                            = new Microsoft.SharePoint.Client.FileCreationInformation();
                        ooxmlFile.Overwrite = true;
                        ooxmlFile.Url       = thisWeb.Url
                                              + rootFolder.ServerRelativeUrl
                                              + "/SharePointSourceDocument.docx";
                        ooxmlFile.Content = documentBytes;
                        Microsoft.SharePoint.Client.File newFile = rootFolder.Files.Add(ooxmlFile);
                        context.Load(newFile);
                        context.ExecuteQuery();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        // Tell the user what went wrong. These variables will be used
                        // to report the error to the user in the TextTranslator.aspx page.
                        success   = false;
                        exception = ex;
                    }
                    finally
                    {
                        // Clean up our filestream object
                        fs.Close();
                    }


                    // Do the actual translation work. Note that we use a synchronous translation
                    // approach here, but you could also use the TranslationJob object to
                    // perform an asynchronous translation.
                    if (success)
                    {
                        try
                        {
                            SyncTranslator job = new SyncTranslator(context, targetLanguage);
                            job.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
                            job.Translate(
                                thisWeb.Url + rootFolder.ServerRelativeUrl + "/SharePointSourceDocument.docx",
                                thisWeb.Url + rootFolder.ServerRelativeUrl + "/" + targetLanguage + "_Document.docx");
                            context.ExecuteQuery();
                            targetLibrary = thisWeb.Url + rootFolder.ServerRelativeUrl;
                        }
                        catch (Exception ex)
                        {
                            // Tell the user what went wrong. These variables will be used
                            // to report the error to the user in the TextTranslator.aspx page.
                            success   = false;
                            exception = ex;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Tell the user what went wrong. These variables will be used
                // to report the error to the user in the TextTranslator.aspx page.
                success   = false;
                exception = ex;
            }
        }