コード例 #1
0
    public async Task <IActionResult> ExportDownload(ExportType type, CancellationToken cancellationToken)
    {
        var exportResult = type switch
        {
            ExportType.Tags => await _mediator.Send(new ExportTagsDataCommand(), cancellationToken),
            ExportType.Categories => await _mediator.Send(new ExportCategoryDataCommand(), cancellationToken),
            ExportType.FriendLinks => await _mediator.Send(new ExportLinkDataCommand(), cancellationToken),
            ExportType.Pages => await _mediator.Send(new ExportPageDataCommand(), cancellationToken),
            ExportType.Posts => await _mediator.Send(new ExportPostDataCommand(), cancellationToken),
            _ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
        };

        switch (exportResult.ExportFormat)
        {
        case ExportFormat.SingleJsonFile:
            return(new FileContentResult(exportResult.Content, exportResult.ContentType)
            {
                FileDownloadName = $"moonglade-{type.ToString().ToLowerInvariant()}-{DateTime.UtcNow:yyyy-MM-dd-HH-mm-ss}.json"
            });

        case ExportFormat.SingleCSVFile:
            Response.Headers.Add("Content-Disposition", $"attachment;filename={Path.GetFileName(exportResult.FilePath)}");
            return(PhysicalFile(exportResult.FilePath, exportResult.ContentType, Path.GetFileName(exportResult.FilePath)));

        case ExportFormat.ZippedJsonFiles:
            return(PhysicalFile(exportResult.FilePath, exportResult.ContentType, Path.GetFileName(exportResult.FilePath)));

        default:
            return(BadRequest(ModelState.CombineErrorMessages()));
        }
    }
}
コード例 #2
0
        /// <summary>
        /// Exporta o relatório no formato informado.
        /// </summary>
        /// <param name="exportType">Formato que será usado na exportação.</param>
        /// <param name="fileNameExtension"></param>
        /// <param name="mimeType">MIME Type.</param>
        /// <param name="encoding">Encoding.</param>
        /// <param name="warnings">Warnings.</param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public virtual System.IO.Stream Export(ExportType exportType, out string mimeType, out string encoding, out string fileNameExtension, out Warning[] warnings, System.Globalization.CultureInfo culture)
        {
            var localReport = CreateLocalReport();

            PrepareLocalReport(localReport, culture);
            Dictionary <string, object> obj = new Dictionary <string, object>();

            Microsoft.Reporting.WebForms.Warning[] warnings2 = null;
            string[] streamids = null;
            fileNameExtension = string.Empty;
            byte[] byteViewer = null;
            byteViewer = localReport.Render(exportType.ToString(), null, out mimeType, out encoding, out fileNameExtension, out streamids, out warnings2);
            if (warnings2 != null)
            {
                warnings = warnings2.Select(f => new Warning {
                    Code       = f.Code,
                    Message    = f.Message,
                    ObjectName = f.ObjectName,
                    ObjectType = f.ObjectType,
                    Severity   = f.Severity == Microsoft.Reporting.WebForms.Severity.Error ? Severity.Error : Severity.Warning
                }).ToArray();
            }
            else
            {
                warnings = null;
            }
            return(new System.IO.MemoryStream(byteViewer));
        }
コード例 #3
0
        /// <summary>
        /// Receives data from a stored procedure and returns a string.
        /// It is expected that the ExportType corresponds to a stored procedure name,
        /// and that the stored proc returns the selected data in JSON format.
        /// This procedure will append together multiple rows, as the "FOR JSON"
        /// command in SQL SERVER may split the data across multiple rows!
        /// </summary>
        /// <param name="selectedDate">The day's data we are pulling</param>
        /// <param name="DataType">Enum ExportType - stored proc name</param>
        /// <returns></returns>
        public string GetJSONData(DateTime selectedDate, ExportType DataType)
        {
            var jsonResult = new StringBuilder();

            var selectedDateParameter = new SqlParameter("@SELECT_DATE", SqlDbType.Date);

            selectedDateParameter.Value = selectedDate.Date;
            using (var command = Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = "Exec " + DataType.ToString() + " @SELECT_DATE";
                command.Parameters.Add(selectedDateParameter);

                Database.OpenConnection();
                using (var reader = command.ExecuteReader())
                {
                    if (!reader.HasRows)
                    {
                        jsonResult.Append("[]");
                    }
                    else
                    {
                        while (reader.Read())
                        {
                            jsonResult.Append(reader.GetValue(0).ToString());
                        }
                    }
                }
            }
            return(jsonResult.ToString());
        }
コード例 #4
0
        public static IExportHolidaysFormat LocateByType(ExportType type)
        {
            string strategyName = NAMESPACE + "." + type.ToString() + EXPORT_FORMAT_NAME;
            IExportHolidaysFormat holidayStrategy = CreateObjectInstance <IExportHolidaysFormat>(strategyName);

            return(holidayStrategy);
        }
コード例 #5
0
ファイル: BackupServices.cs プロジェクト: gporte/BztToolbox
        private string GenerateExportFileName(string appName, ExportType type)
        {
            var fileName = string.Format(
                "{0}_{1}",
                DateTime.Now.ToString("yyyyMmddHHmmssfff"),
                appName
                );

            switch (type)
            {
            case ExportType.Binding:
                fileName += ".xml";
                break;

            case ExportType.ResourceSpec:
                fileName += "_Res.xml";
                break;

            case ExportType.Msi:
            case ExportType.MsiResourceSpec:
                fileName += ".msi";
                break;

            default:
                throw new Exception("Type d'export non pris en charge : " + type.ToString());
            }

            return(fileName);
        }
コード例 #6
0
        public void AddEnvironment(Identifier aasId, AssetAdministrationShellEnvironment_V2_0 environment, ExportType exportType)
        {
            if (aasId == null)
            {
                throw new ArgumentNullException(nameof(aasId));
            }
            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }

            string aasIdName = aasId.Id;

            foreach (char invalidChar in Path.GetInvalidFileNameChars())
            {
                aasIdName = aasIdName.Replace(invalidChar, '_');
            }

            string aasFilePath = AASX_FOLDER + "/" + aasIdName + "/" + aasIdName + ".aas." + exportType.ToString().ToLower();

            Uri partUri = PackUriHelper.CreatePartUri(new Uri(aasFilePath, UriKind.RelativeOrAbsolute));

            ClearRelationshipAndPartFromPackagePart(originPart, SPEC_RELATIONSHIP_TYPE, partUri);

            specPart = aasxPackage.CreatePart(partUri, GetContentType(aasFilePath), CompressionOption.Maximum);
            originPart.CreateRelationship(specPart.Uri, TargetMode.Internal, SPEC_RELATIONSHIP_TYPE);

            string environmentTemp = Path.GetRandomFileName() + "." + exportType.ToString().ToLower();

            environment.WriteEnvironment_V2_0(exportType, environmentTemp);

            CopyFileToPackagePart(specPart, environmentTemp);

            File.Delete(environmentTemp);
        }
コード例 #7
0
        protected TableCell GetExportCell(ExportType type, String callBackID)
        {
            ASPxImage btn = new ASPxImage();

            //btn.Text = type.ToString();
            btn.ImageAlign         = ImageAlign.Middle;
            btn.ImageUrl           = String.Format("~/img/filetypes/{0}.png", type.ToString());
            btn.Height             = Unit.Pixel(16);
            btn.Width              = Unit.Pixel(16);
            btn.ID                 = String.Format("{0}_btnExport{1}", callBackID, type.ToString());
            btn.ClientInstanceName = btn.ID;
            btn.SetClientSideEventHandler("Click", "function(s,e){" + callBackID + ".PerformCallback('EXPORT||||" + this.grid.UniqueID + "||||" + type.ToString() + "');}");
            TableCell cell = new TableCell();

            cell.Controls.Add(btn);
            return(cell);
        }
コード例 #8
0
        internal static bool To(ExportType type, string savePath, Dictionary <int, List <Cell> > dic)
        {
            var first =
                typeof(ExportType).GetField(type.ToString())
                .GetCustomAttributes(false)
                .OfType <DescriptionAttribute>()
                .FirstOrDefault();

            if (first != null)
            {
                savePath = Path.ChangeExtension(savePath, first.Description);
            }
            else
            {
                Debug.LogError("获取路径扩展名出错");
                return(false);
            }

            switch (type)
            {
            case ExportType.ToXml:
                ToXml(savePath, dic);
                break;

            case ExportType.ToXmlAttribute:
                ToXmlAttribute(savePath, dic);
                break;

            case ExportType.ToJson:
                ToJson(savePath, dic);
                break;

            case ExportType.ToCsv:
                ToCsv(savePath, dic);
                break;

            case ExportType.ToTxt:
                ToTxt(savePath, dic);
                break;

            case ExportType.ToBytes:
                ToBytes(savePath, dic);
                break;

            case ExportType.ToAsset:
                ToAsset(savePath, dic);
                break;

            case ExportType.ToLua:
                ToLua(savePath, dic);
                break;

            default:
                Debug.Log(Path.GetFileName(savePath) + "导表失败!");
                return(false);
            }
            return(true);
        }
コード例 #9
0
        public void Export(List <CandidateControl> cands, List <PartyControl> parts, string path, ExportType type)
        {
            try
            {
                using (var fileStream = File.Create($"{path}\\Candidates.{type.ToString()}"))
                {
                    Report candReport = PrepCandReport(cands);

                    if (type == ExportType.Pdf)
                    {
                        var writer = new DoddleReport.iTextSharp.PdfReportWriter();
                        writer.WriteReport(candReport, fileStream);
                    }
                    else
                    {
                        var writer = new DoddleReport.Writers.DelimitedTextReportWriter();
                        DelimitedTextReportWriter.DefaultDelimiter = ",";
                        writer.WriteReport(candReport, fileStream);
                    }
                }
                using (var fileStream = File.Create($"{path}\\Parties.{type.ToString()}"))
                {
                    Report partiesReport = PrepPartyReport(parts);

                    if (type == ExportType.Pdf)
                    {
                        var writer = new DoddleReport.iTextSharp.PdfReportWriter();
                        writer.WriteReport(partiesReport, fileStream);
                    }
                    else
                    {
                        var writer = new DoddleReport.Writers.DelimitedTextReportWriter();
                        DelimitedTextReportWriter.DefaultDelimiter = ",";
                        writer.WriteReport(partiesReport, fileStream);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.StackTrace);
            }
        }
コード例 #10
0
        public void SetData(ExportType type)
        {
            FileInfo fileInfo = new FileInfo(excelFullPath);

            var first = typeof(ExportType).GetField(type.ToString()).GetFirstCustomAttribute <DescriptionAttribute>();

            if (first != null)
            {
                tableName = fileInfo.Name.Replace(fileInfo.Extension, first.Description);
            }
            else
            {
                Debug.LogError("获取路径扩展名出错");
            }
        }
コード例 #11
0
ファイル: UModelFacade.cs プロジェクト: mcu8/OpenModManager
        public bool Export(string root, string package, string assetName, ExportType exportType, string destination, bool forceTgaToPng = false)
        {
            var tmpDir = GetTMPDir();

            if (Directory.Exists(tmpDir))
            {
                Directory.Delete(tmpDir, true);
            }
            Directory.CreateDirectory(tmpDir);

            // .\umodel.exe -game=ue3 -path="C:\Program Files (x86)\Steam\steamapps\common\HatinTime\HatinTimeGame\EditorCookedPC" -export HatinTime_Music_Metro4 Act_4_Pink_Paw_Station -sounds -out=".\test"
            var res = Run($"-game=ue3 -path=\"{root}\" -3rdparty -export {package} {assetName}{(exportType == ExportType.SoundNodeWave ? " -sounds" : " " + exportType.ToString())} -out=\"{tmpDir}\"");

            if (!res)
            {
                return(false);
            }

            var extension = GetExtensionForType(exportType);

            var path = Path.Combine(tmpDir, package, exportType.ToString(), assetName + extension);

            Debug.WriteLine("ExceptedPath: " + path);

            if (File.Exists(path))
            {
                if (File.Exists(destination))
                {
                    File.Delete(destination);
                }

                if (forceTgaToPng && exportType == ExportType.Texture2D)
                {
                    using (var b = new TargaImage(path))
                    {
                        b.Image.Save(destination, ImageFormat.Png);
                    }
                }
                else
                {
                    File.Move(path, destination);
                }
                return(true);
            }

            return(false);
        }
コード例 #12
0
ファイル: BackupServices.cs プロジェクト: gporte/BztToolbox
        private string GetCmdtext(ExportType type)
        {
            switch (type)
            {
            case ExportType.Binding:
                return("ExportBindings -ApplicationName:{0} -Destination:{1}");

            case ExportType.Msi:
                return("ExportApp -ApplicationName:{0} -Package:{1}");

            case ExportType.ResourceSpec:
                return("ListApp -ApplicationName:{0} -ResourceSpec:{1}");

            case ExportType.MsiResourceSpec:
                return("ExportApp -ApplicationName:{0} -Package:{1} -ResourceSpec:{2}");

            default:
                throw new Exception("Type d'export non pris en charge : " + type.ToString());
            }
        }
コード例 #13
0
        public static string GetMimeType(ExportType exportType)
        {
            switch (exportType)
            {
            case ExportType.Excel: return("application/vnd.ms-excel");

            case ExportType.PDF: return("application/pdf");

            case ExportType.Word: return("application/vnd.ms-word");

            case ExportType.ImagePNG: return("application/png");

            case ExportType.ImageJPG: return("application/jpg");

            case ExportType.HTML:
            case ExportType.HTMLOWC:
            case ExportType.MHTML:
                return("text/html");

            default: throw new NotSupportedException("Not supported MIME type: " + exportType.ToString());
            }
        }
コード例 #14
0
        private async Task <byte[]> RenderReportData(UserInfo userInfo, string entityName, int id, string reportName, ExportType exportType, ReportGenerator gen)
        {
            ParameterValue[] parameters =
            {
                new ParameterValue {
                    Name = "id", Value = id.ToString()
                },
                new ParameterValue {
                    Name = "userId", Value = userInfo.UserId.ToString()
                },
                new ParameterValue {
                    Name = "codeLanguage", Value = userInfo.UserLanguage
                },
                new ParameterValue {
                    Name = "entityName", Value = entityName
                }
            };

            byte[] repData = await gen.RenderReport(reportName, parameters, exportType.ToString());

            return(repData);
        }
コード例 #15
0
        /// <summary>
        /// Adds the SPListItem for the ExportJob to the GlymaExports lists if there isn't one already in the Scheduled ExportState for the exact same export.
        /// </summary>
        /// <param name="exportsList">The SPList that contains the ExportJobs</param>
        /// <param name="domainId">The DomainUid for the export to be created</param>
        /// <param name="rootmapId">The RootMapUid for the export to be created</param>
        /// <param name="mapType">The type of map (schema) that is being exported</param>
        /// <param name="type">The format of the export to be created</param>
        /// <param name="workItemId">The ID of the workitem</param>
        /// <param name="serializedExportProperties">The ExportProperties as an XML string</param>
        /// <returns>The ID of the list item created or -1 if it wasn't created because an existing item matched it in scheduled state.</returns>
        private int CreateExportJobListEntry(SPList exportsList, Guid domainId, Guid rootmapId, MapType mapType, ExportType type, Guid workItemId, string serializedExportProperties, int userId)
        {
            int listItemId = -1; //default value indicates that item wasn't created

            if (exportsList != null)
            {
                SPQuery query = new SPQuery();
                query.Query = "<Where><And><And><And><And>" +
                              "<And><Eq><FieldRef Name='DomainUid' /><Value Type='Text'>" + domainId.ToString() + "</Value></Eq>" +
                              "<Eq><FieldRef Name='RootMapUid' /><Value Type='Text'>" + rootmapId.ToString() + "</Value></Eq></And>" +
                              "<Eq><FieldRef Name='ExportStatus' /><Value Type='Choice'>" + ExportStatus.Scheduled.ToString() + "</Value></Eq></And>" +
                              "<Eq><FieldRef Name='ExportType' /><Value Type='Choice'>" + type.ToString() + "</Value></Eq></And>" +
                              "<Eq><FieldRef Name='ExportProperties' /><Value Type='Note'>" + serializedExportProperties + "</Value></Eq></And>" +
                              "<Eq><FieldRef Name='MapType' /><Value Type='Choice'>" + mapType.ToString() + "</Value></Eq>" +
                              "</And></Where>";
                // Query for where this particular rootmap has been scheduled for export to the same type already
                SPListItemCollection existingSchedules = exportsList.GetItems(query);

                if (existingSchedules.Count == 0)
                {
                    //TODO get field names from constants
                    SPListItem exportJob = exportsList.Items.Add();
                    exportJob["ExportType"]            = type.ToString();
                    exportJob["MapType"]               = mapType.ToString();
                    exportJob["ExportStatus"]          = ExportStatus.Scheduled.ToString();
                    exportJob["RootMapUid"]            = rootmapId.ToString();
                    exportJob["DomainUid"]             = domainId.ToString();
                    exportJob[SPBuiltInFieldId.Title]  = workItemId.ToString();
                    exportJob["ExportProperties"]      = serializedExportProperties;
                    exportJob["PercentageComplete"]    = 0;
                    exportJob[SPBuiltInFieldId.Author] = userId;
                    exportJob[SPBuiltInFieldId.Editor] = userId;
                    exportJob.Update();
                    listItemId = exportJob.ID;
                }
            }
            return(listItemId);
        }
コード例 #16
0
        private static Byte[] ConvertToByte(LocalReport localReport, ExportType expType)
        {
            try
            {
                Warning[] warnings;
                String[]  streamids;
                String    mimeType;
                String    encoding;
                String    extension;

                Byte[] bytes = localReport.Render(
                    expType.ToString(), null, out mimeType, out encoding,
                    out extension,
                    out streamids, out warnings);

                MimeType = mimeType;
                return(bytes);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
コード例 #17
0
        /// <summary>
        /// Exporta o relatório no formato informado.
        /// </summary>
        /// <param name="exportType">Formato que será usado na exportação.</param>
        /// <param name="createStreamCallback">Callback usada na criação a Stream de exportação.</param>
        /// <param name="warnings">Warnings.</param>
        /// <param name="culture"></param>
        public virtual void Export(ExportType exportType, CreateStreamCallback createStreamCallback, out Warning[] warnings, System.Globalization.CultureInfo culture)
        {
            var localReport = CreateLocalReport();

            PrepareLocalReport(localReport, culture);
            Dictionary <string, object> obj = new Dictionary <string, object>();

            Microsoft.Reporting.WebForms.Warning[] warnings2 = null;
            localReport.Render(exportType.ToString(), null, new Microsoft.Reporting.WebForms.CreateStreamCallback((name, extension, encoding, mimeType, willSeek) => createStreamCallback(name, extension, encoding, mimeType, willSeek)), out warnings2);
            if (warnings2 != null)
            {
                warnings = warnings2.Select(f => new Warning {
                    Code       = f.Code,
                    Message    = f.Message,
                    ObjectName = f.ObjectName,
                    ObjectType = f.ObjectType,
                    Severity   = f.Severity == Microsoft.Reporting.WebForms.Severity.Error ? Severity.Error : Severity.Warning
                }).ToArray();
            }
            else
            {
                warnings = null;
            }
        }
コード例 #18
0
 string IDataDefinitionExport.ToString()
 {
     return(string.Format("{0}\0{1}\0{2}", Reference, ExportType.ToString(), Name));
 }
コード例 #19
0
        /// <summary>
        /// Set the pair information using only either the entity or the type
        /// </summary>
        /// <param name="entityType">the entity or type</param>
        public void SetValueWithPair(IFCEntityType entityType)
        {
            string entityTypeStr = entityType.ToString();
            bool   isType        = entityTypeStr.Substring(entityTypeStr.Length - 4, 4).Equals("Type", StringComparison.CurrentCultureIgnoreCase);

            if (isType)
            {
                // Get the instance
                string instName          = entityTypeStr.Substring(0, entityTypeStr.Length - 4);
                IfcSchemaEntityNode node = IfcSchemaEntityTree.Find(instName);
                if (node != null && !node.isAbstract)
                {
                    IFCEntityType instType = IFCEntityType.UnKnown;
                    if (IFCEntityType.TryParse(instName, out instType))
                    {
                        ExportInstance = instType;
                    }
                }
                // If not found, try non-abstract supertype derived from the type
                node = IfcSchemaEntityTree.FindNonAbsInstanceSuperType(instName);
                if (node != null)
                {
                    IFCEntityType instType = IFCEntityType.UnKnown;
                    if (IFCEntityType.TryParse(node.Name, out instType))
                    {
                        ExportInstance = instType;
                    }
                }

                // set the type
                entityType = ElementFilteringUtil.GetValidIFCEntityType(entityType);
                if (entityType != IFCEntityType.UnKnown)
                {
                    ExportType = entityType;
                }
                else
                {
                    node = IfcSchemaEntityTree.FindNonAbsInstanceSuperType(entityTypeStr);
                    if (node != null)
                    {
                        IFCEntityType instType = IFCEntityType.UnKnown;
                        if (IFCEntityType.TryParse(node.Name, out instType))
                        {
                            ExportType = instType;
                        }
                    }
                }
            }
            else
            {
                // set the instance
                entityType = ElementFilteringUtil.GetValidIFCEntityType(entityType);
                if (entityType != IFCEntityType.UnKnown)
                {
                    ExportInstance = entityType;
                }
                else
                {
                    // If not found, try non-abstract supertype derived from the type
                    IfcSchemaEntityNode node = IfcSchemaEntityTree.FindNonAbsInstanceSuperType(entityTypeStr);
                    if (node != null)
                    {
                        IFCEntityType instType = IFCEntityType.UnKnown;
                        if (IFCEntityType.TryParse(node.Name, out instType))
                        {
                            ExportInstance = instType;
                        }
                    }
                }

                // set the type pair
                string typeName = entityType.ToString() + "Type";
                entityType = ElementFilteringUtil.GetValidIFCEntityType(typeName);
                if (entityType != IFCEntityType.UnKnown)
                {
                    ExportType = entityType;
                }
                else
                {
                    IfcSchemaEntityNode node = IfcSchemaEntityTree.FindNonAbsInstanceSuperType(typeName);
                    if (node != null)
                    {
                        IFCEntityType instType = IFCEntityType.UnKnown;
                        if (IFCEntityType.TryParse(node.Name, out instType))
                        {
                            ExportType = instType;
                        }
                    }
                }
            }

            ValidatedPredefinedType = IFCValidateEntry.GetValidIFCPredefinedTypeType("NOTDEFINED", ValidatedPredefinedType, ExportType.ToString());
        }
コード例 #20
0
ファイル: Format.cs プロジェクト: SuMinXin/tools
        private void Export(ExportType type)
        {
            string action = "匯出";

            try {
                string txtPath = string.Concat(@"E:\Data\Desktop\", txt_ExportName.Text, ".", type.ToString());

                using (StreamWriter sw = new StreamWriter(txtPath))
                {
                    sw.Write(richtxt_Output.Text);
                }
                MessageBox.Show(SystemMsg.succeed(action));
            } catch (Exception ex) {
                MessageBox.Show(SystemMsg.fail(action, ex.ToString()));
            }
        }
コード例 #21
0
        private static void ExportOrder(OrderData order, StyleConfigData config)
        {
            string     orderWords = config.filePaths.ConstructFileName(order).Replace(".cdr", String.Empty);
            ExportType exportType = config.GetExportType(order.itemCode);

            cdrFilter corelExport;

            switch (exportType)
            {
            case ExportType.Eps:
                corelExport = cdrFilter.cdrEPS;
                break;

            case ExportType.Plt:
                corelExport = cdrFilter.cdrPLT;
                break;

            default:
                ErrorHandler.HandleError(ErrorType.Alert, $"Invalid export type: {exportType}");
                return;
            }

            corel.ActiveDocument.ClearSelection();

            //NOTE(adam): try selecting specific sew shape
            if (exportType == ExportType.Plt)
            {
                Shape sewShape = corel.ActivePage.FindShape(orderWords + "_sew");
                if (sewShape != null)
                {
                    sewShape.AddToSelection();
                }
            }

            //NOTE(adam): if no shapes found, try selecting by order words
            if (corel.ActiveSelection.Shapes.Count == 0)
            {
                Shape found = corel.ActivePage.FindShape(orderWords);
                if (found != null)
                {
                    found.AddToSelection();
                }
            }

            //NOTE(adam): if no shapes found, select bottom right
            if (corel.ActiveSelection.Shapes.Count == 0)
            {
                corel.ActiveDocument.ReferencePoint = cdrReferencePoint.cdrTopLeft;
                corel.ActivePage.SelectShapesFromRectangle(corel.ActivePage.SizeWidth / 2,
                                                           corel.ActivePage.SizeHeight / 2,
                                                           corel.ActivePage.SizeWidth,
                                                           corel.ActivePage.SizeHeight,
                                                           false);
            }

            //NOTE(adam): if no shapes found, select on whole page
            if (corel.ActiveSelection.Shapes.Count == 0)
            {
                corel.ActiveDocument.ReferencePoint = cdrReferencePoint.cdrTopLeft;
                corel.ActivePage.SelectShapesFromRectangle(0,
                                                           0,
                                                           corel.ActivePage.SizeWidth,
                                                           corel.ActivePage.SizeHeight,
                                                           false);
            }

            //NOTE(adam): if no shapes found, select all
            if (corel.ActiveSelection.Shapes.Count == 0)
            {
                corel.ActivePage.SelectableShapes.All().AddToSelection();
            }


            if (corel.ActiveSelection.Shapes.Count == 0)
            {
                Messenger.Show("Could not get shapes for exporting. Manual export required.");
            }
            else
            {
                string exportUpper = exportType.ToString().ToUpper();
                Directory.CreateDirectory(config.filePaths.ConstructExportFolderPath(order, exportUpper));
                //NOTE(adam): options need to be specified within Corel previously
                corel.ActiveDocument.Export(config.filePaths.ConstructExportFilePath(order, exportUpper), corelExport, cdrExportRange.cdrSelection);
            }
        }
コード例 #22
0
        /// <summary>
        /// Creates an ExportJob and schedules the WorkItem for the timer job that processes the exports.
        /// </summary>
        /// <param name="domainUid">The DominUid for the map being exported</param>
        /// <param name="rootMapUid">The RootMapUid for the map being exported</param>
        /// <param name="exportProperties">The export properties for the export</param>
        /// <param name="mapType">The map type (schema) for the map being exported</param>
        /// <param name="exportType">The output format for the export</param>
        /// <returns>The ExportJob that was created</returns>
        public ExportJobResponse CreateExportJob(Guid domainUid, Guid rootMapUid, IDictionary<string, string> exportProperties, MapType mapType, ExportType exportType)
        {
            ExportJobResponse response = new ExportJobResponse();

            try
            {
                Guid webID = SPContext.Current.Web.ID;
                Guid siteID = SPContext.Current.Site.ID;
                SPUser currentUser = null;
                using (SPSite site = new SPSite(siteID)) 
                {
                    using (SPWeb web = site.OpenWeb(webID))
                    {
                        if (web != null)
                        {
                            currentUser = web.CurrentUser;
                        }
                    }
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    int userId = -1;
                    SPList exportsList = null;
                    int listItemIdNum = -1;
                    
                    using (SPSite site = new SPSite(siteID)) 
                    {
                        using (SPWeb web = site.OpenWeb(webID))
                        {
                            if (web != null)
                            {
                                if (currentUser == null)
                                {
                                    //The current user shouldn't be null, it should have been resolved outside of this RunWithElevatedPrivileges delegate
                                    currentUser = web.CurrentUser;
                                }
                                if (currentUser != null)
                                {
                                    userId = currentUser.ID;

                                    exportsList = web.TryGetList(web.GetServerRelativeListUrlPrefix() + "GlymaExports"); //TODO get the name from a constant
                                    if (exportsList != null)
                                    {

                                        //the text payload will contain the properties serialized into a simple XML format
                                        ExportPropertiesDictionary serializableDict = new ExportPropertiesDictionary(exportProperties);
                                        string textPayload = serializableDict.ConvertToXml();

                                        Guid workItemId = Guid.NewGuid(); // Create a unique id for the work item and export job
                                        listItemIdNum = CreateExportJobListEntry(exportsList, domainUid, rootMapUid, mapType, exportType, workItemId, textPayload, userId);

                                        // if the list item was created then create the export job, if it wasn't it was because an export
                                        // for this particular root map of this type was already scheduled (changing the properties doesn't have effect)
                                        if (listItemIdNum != -1)
                                        {
                                            site.AddWorkItem(workItemId, //gWorkItemId - A Guid that identifies the work item
                                                DateTime.Now.ToUniversalTime(), //schdDateTime - represents a time in universal time for when the work item should take place
                                                GlymaExportWorkItemTimerJob.WorkItemTypeId, //gWorkItemType - this must be the GUID used in the GlymaExportWorkItemTimerJob
                                                web.ID, //gWebId - The identifier of the web containing the list
                                                exportsList.ID, //gParentId - The list ID
                                                listItemIdNum, //nItemId - The list item ID number
                                                true, //fSetWebId - true to set the Web identifier
                                                exportsList.Items.GetItemById(listItemIdNum).UniqueId, //gItemGuid - The unique identifier of the list item
                                                domainUid, //gBatchId - A Guid context identifier for the work item engine
                                                userId, //nUserId - SPUser ID number
                                                null, //rgbBinaryPayload - not used
                                                textPayload, //strTextPayload
                                                Guid.Empty); //gProcessingId - needs to be Guid.Empty

                                            ExportJob scheduledJob = new ExportJob();
                                            scheduledJob.Created = (DateTime)exportsList.Items.GetItemById(listItemIdNum)[SPBuiltInFieldId.Created];
                                            scheduledJob.CreatedBy = new GlymaUser() { Name = currentUser.Name };
                                            scheduledJob.Id = workItemId;
                                            scheduledJob.IsCurrent = true;
                                            scheduledJob.Status = ExportStatus.Scheduled;
                                            scheduledJob.Type = exportType;
                                            scheduledJob.MapType = mapType;
                                            scheduledJob.ExportProperties = exportProperties;
                                            scheduledJob.PercentageComplete = 0;
                                            response.ExportJob = scheduledJob;
                                        }
                                        else
                                        {
                                            //already scheduled so throw an exception to be handled with an error
                                            throw new Exception(string.Format("A scheduled export job already exists for the Glyma map: DomainUid: {0}, RootMapUid: {1}, Export Type: {2}, Map Type: {3}",
                                                domainUid.ToString(), rootMapUid.ToString(), exportType.ToString(), mapType.ToString()));
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception("Failed to find the Glyma Exports list.");
                                    }
                                }
                                else
                                {
                                    throw new Exception("The current user was not able to be determined.");
                                }
                            }
                            else
                            {
                                throw new Exception("The SPSite and/or the SPWeb were null.");
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ExportError error = new ExportError() { ErrorMessage = "Failed to create the Glyma map export job." };
                throw new FaultException<ExportError>(error, ex.ToString());
            }

            return response;
        }
コード例 #23
0
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase,
                                                SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
        {
            Stopwatch sw = Stopwatch.StartNew(); //used to time how long the export took
            bool      processingAlready = false;

            try
            {
                if (workItem != null)
                {
                    //process the workItem
                    using (SPSite site = new SPSite(workItem.SiteId))
                    {
                        using (SPWeb web = site.OpenWeb(workItem.WebId))
                        {
                            // processing logic
                            // 1. SET GlymaExport list Item to ExportStatus.Processing
                            // 2. START export based on type in GlymaExport list item
                            // 3. STORE the export in the GlymaExport list against the item as an attachment
                            // 4. SET GlymaExport list item to ExportStatus.Completed
                            SPList     exportsList = null;
                            SPListItem exportItem  = null;
                            try
                            {
                                exportsList = web.Lists[workItem.ParentId];
                                exportItem  = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                if (exportItem != null)
                                {
                                    string exportStatus = exportItem["ExportStatus"] as string;
                                    if (exportStatus == ExportStatus.Scheduled.ToString())
                                    {
                                        // If the export was still marked as scheduled then set it to processing
                                        WriteExportStatus(workItem, ExportStatus.Processing);

                                        exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);

                                        if (exportItem != null)
                                        {
                                            // read the type of export that we should produce
                                            ExportType exportType = (ExportType)Enum.Parse(typeof(ExportType), exportItem["ExportType"] as string);
                                            MapType    mapType    = (MapType)Enum.Parse(typeof(MapType), exportItem["MapType"] as string);

                                            Dictionary <string, string> exportProperties = null;
                                            string exportPropertiesStr = exportItem["ExportProperties"] as string;
                                            if (!string.IsNullOrEmpty(exportPropertiesStr) && exportPropertiesStr.Trim() != string.Empty)
                                            {
                                                try
                                                {
                                                    ExportPropertiesDictionary exportDict = new ExportPropertiesDictionary(exportPropertiesStr);
                                                    exportProperties = exportDict as Dictionary <string, string>;
                                                }
                                                catch (XmlSchemaValidationException)
                                                {
                                                    exportProperties = null;
                                                }
                                            }

                                            bool useVerboseLogging = false;
                                            if (exportProperties != null)
                                            {
                                                if (exportProperties.ContainsKey("Verbose"))
                                                {
                                                    if (exportProperties["Verbose"].ToLower() == "true")
                                                    {
                                                        useVerboseLogging = true;
                                                    }
                                                }
                                            }

                                            if (useVerboseLogging)
                                            {
                                                LogMessage(workItem, "Creating Map Manager for the web: {0}.", web.Url);
                                            }

                                            // create the appropriate IExportUtility for the ExportType
                                            MapManagerFactory mapManagerFactory = new MapManagerFactory();
                                            IMapManager       mapManager        = mapManagerFactory.GetMapManager(web);
                                            if (mapManager != null)
                                            {
                                                if (useVerboseLogging)
                                                {
                                                    LogMessage(workItem, "Created Map Manager for the web: {0}.", web.Url);
                                                }

                                                ExportUtilityFactory exportUtilityFactory = new ExportUtilityFactory(mapManager);
                                                IExportUtility       exportUtility        = exportUtilityFactory.CreateExportUtility(mapType, exportType);

                                                if (exportUtility != null)
                                                {
                                                    if (useVerboseLogging)
                                                    {
                                                        LogMessage(workItem, "Created Export Utility for {0} map type to {1}.", mapType.ToString(), exportType.ToString());
                                                    }

                                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                                    if (exportItem != null)
                                                    {
                                                        Guid rootMapUid = Guid.Empty;
                                                        Guid domainUid  = Guid.Empty;
                                                        try
                                                        {
                                                            string rootMapUidValue = exportItem["RootMapUid"] as string;
                                                            string domainUidValue  = exportItem["DomainUid"] as string;
                                                            domainUid  = new Guid(domainUidValue);
                                                            rootMapUid = new Guid(rootMapUidValue);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            //The GUIDs were not parsed correctly
                                                        }
                                                        if (rootMapUid != Guid.Empty && domainUid != Guid.Empty)
                                                        {
                                                            //The export utility will do the grunt work and provide a URL to the temp file created
                                                            GlymaExportUserState userState = new GlymaExportUserState(workItem);
                                                            userState.UseVerboseLogging    = useVerboseLogging; //store the level of logging to use in the event handlers
                                                            exportUtility.ExportCompleted += exportUtility_ExportCompleted;
                                                            exportUtility.ProgressChanged += exportUtility_ProgressChanged;
                                                            exportUtility.ExceptionRaised += exportUtility_ExceptionRaised;

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Starting export.");
                                                            }

                                                            exportUtility.ExportMap(domainUid, rootMapUid, exportProperties, new List <Guid>(), userState);

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Waiting for export to complete.");
                                                            }

                                                            // Wait for the export to complete (up to the timeout)
                                                            bool signalled = userState.Completed.WaitOne(TIMEOUT_MS);
                                                            if (!signalled)
                                                            {
                                                                if (useVerboseLogging)
                                                                {
                                                                    LogMessage(workItem, "The export timed out after {0}ms", TIMEOUT_MS);
                                                                }
                                                                // The timeout occurred so don't process the completed or progress changed events
                                                                exportUtility.ExportCompleted -= exportUtility_ExportCompleted;
                                                                exportUtility.ProgressChanged -= exportUtility_ProgressChanged;
                                                                exportUtility.ExceptionRaised -= exportUtility_ExceptionRaised;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            throw new Exception(string.Format("The DomainUid and/or RootMapUid were not valid Guid's. DomainUid: {0} RootMapUid: {1}.", domainUid.ToString(), rootMapUid.ToString()));
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    throw new Exception(string.Format("Unable to create export utility for the export type: {0}.", exportType.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(string.Format("Unable to build an IMapManager for the current SPWeb. {0}", mapManagerFactory.ErrorMessage));
                                            }
                                        }
                                    }
                                    else if (exportStatus == ExportStatus.Processing.ToString())
                                    {
                                        //shouldn't do anything unless it's scheduled.
                                        processingAlready = true;
                                    }
                                }
                                else
                                {
                                    throw new Exception("The Export Job did not exist in the list.");
                                }
                            }
                            catch (TargetInvocationException tiex)
                            {
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}", tiex.Message);

                                    if (tiex.InnerException != null)
                                    {
                                        LogMessage(workItem, "Inner Exception({0}): {1}.\r\nStackTrace: {2}", tiex.InnerException.GetType().ToString(), tiex.InnerException.Message, tiex.InnerException.StackTrace);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //exception handling
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}.", ex.Message);
                                }
                            }
                            finally
                            {
                                if (!processingAlready)
                                {
                                    // delete the workItem after we've processed it
                                    workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                                }

                                //Update the progress of the timer job
                                Progress += (100 / workItems.Count); //estimate only, some maps will export faster than others and different types may export faster
                                if (Progress > 100)
                                {
                                    Progress = 100;
                                }
                                this.UpdateProgress(Progress); //The base classes timer job's overall progress

                                if (!processingAlready)        //this is if the timer job ran and started processing the item that was already being processed
                                {
                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                    if (exportItem != null)
                                    {
                                        string exportStatus = exportItem["ExportStatus"] as string;
                                        if (exportStatus == ExportStatus.Processing.ToString())
                                        {
                                            //if it's still processing and at this point then something has failed.
                                            WriteExportStatus(workItem, ExportStatus.Error);
                                            LogMessage(workItem, "The export failed as it was still in a processing state when it had apparently completed.");
                                        }

                                        LogMessage(workItem, "Completed in {0:0.000}s.", sw.Elapsed.TotalSeconds);//add in a metric for how long the export took (successful or failure)
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //exception handling
                throw new Exception("Failed to while processing Glyma Export Work Item Timer Job.", ex);
            }

            return(true);
        }
コード例 #24
0
        /// <summary>
        /// Add a new Importer
        /// </summary>
        private static void AddExporter(ExportType key, IMeshExporter exporter)
        {
            AvailableExporters.Add(key, exporter);

            ExporterTypes.Add(key.ToString(), key);
        }
コード例 #25
0
        /// <summary>
        /// Creates an ExportJob and schedules the WorkItem for the timer job that processes the exports.
        /// </summary>
        /// <param name="domainUid">The DominUid for the map being exported</param>
        /// <param name="rootMapUid">The RootMapUid for the map being exported</param>
        /// <param name="exportProperties">The export properties for the export</param>
        /// <param name="mapType">The map type (schema) for the map being exported</param>
        /// <param name="exportType">The output format for the export</param>
        /// <returns>The ExportJob that was created</returns>
        public ExportJobResponse CreateExportJob(Guid domainUid, Guid rootMapUid, IDictionary <string, string> exportProperties, MapType mapType, ExportType exportType)
        {
            ExportJobResponse response = new ExportJobResponse();

            try
            {
                Guid   webID       = SPContext.Current.Web.ID;
                Guid   siteID      = SPContext.Current.Site.ID;
                SPUser currentUser = null;
                using (SPSite site = new SPSite(siteID))
                {
                    using (SPWeb web = site.OpenWeb(webID))
                    {
                        if (web != null)
                        {
                            currentUser = web.CurrentUser;
                        }
                    }
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    int userId         = -1;
                    SPList exportsList = null;
                    int listItemIdNum  = -1;

                    using (SPSite site = new SPSite(siteID))
                    {
                        using (SPWeb web = site.OpenWeb(webID))
                        {
                            if (web != null)
                            {
                                if (currentUser == null)
                                {
                                    //The current user shouldn't be null, it should have been resolved outside of this RunWithElevatedPrivileges delegate
                                    currentUser = web.CurrentUser;
                                }
                                if (currentUser != null)
                                {
                                    userId = currentUser.ID;

                                    exportsList = web.TryGetList(web.GetServerRelativeListUrlPrefix() + "GlymaExports"); //TODO get the name from a constant
                                    if (exportsList != null)
                                    {
                                        //the text payload will contain the properties serialized into a simple XML format
                                        ExportPropertiesDictionary serializableDict = new ExportPropertiesDictionary(exportProperties);
                                        string textPayload = serializableDict.ConvertToXml();

                                        Guid workItemId = Guid.NewGuid(); // Create a unique id for the work item and export job
                                        listItemIdNum   = CreateExportJobListEntry(exportsList, domainUid, rootMapUid, mapType, exportType, workItemId, textPayload, userId);

                                        // if the list item was created then create the export job, if it wasn't it was because an export
                                        // for this particular root map of this type was already scheduled (changing the properties doesn't have effect)
                                        if (listItemIdNum != -1)
                                        {
                                            site.AddWorkItem(workItemId,                                            //gWorkItemId - A Guid that identifies the work item
                                                             DateTime.Now.ToUniversalTime(),                        //schdDateTime - represents a time in universal time for when the work item should take place
                                                             GlymaExportWorkItemTimerJob.WorkItemTypeId,            //gWorkItemType - this must be the GUID used in the GlymaExportWorkItemTimerJob
                                                             web.ID,                                                //gWebId - The identifier of the web containing the list
                                                             exportsList.ID,                                        //gParentId - The list ID
                                                             listItemIdNum,                                         //nItemId - The list item ID number
                                                             true,                                                  //fSetWebId - true to set the Web identifier
                                                             exportsList.Items.GetItemById(listItemIdNum).UniqueId, //gItemGuid - The unique identifier of the list item
                                                             domainUid,                                             //gBatchId - A Guid context identifier for the work item engine
                                                             userId,                                                //nUserId - SPUser ID number
                                                             null,                                                  //rgbBinaryPayload - not used
                                                             textPayload,                                           //strTextPayload
                                                             Guid.Empty);                                           //gProcessingId - needs to be Guid.Empty

                                            ExportJob scheduledJob = new ExportJob();
                                            scheduledJob.Created   = (DateTime)exportsList.Items.GetItemById(listItemIdNum)[SPBuiltInFieldId.Created];
                                            scheduledJob.CreatedBy = new GlymaUser()
                                            {
                                                Name = currentUser.Name
                                            };
                                            scheduledJob.Id                 = workItemId;
                                            scheduledJob.IsCurrent          = true;
                                            scheduledJob.Status             = ExportStatus.Scheduled;
                                            scheduledJob.Type               = exportType;
                                            scheduledJob.MapType            = mapType;
                                            scheduledJob.ExportProperties   = exportProperties;
                                            scheduledJob.PercentageComplete = 0;
                                            response.ExportJob              = scheduledJob;
                                        }
                                        else
                                        {
                                            //already scheduled so throw an exception to be handled with an error
                                            throw new Exception(string.Format("A scheduled export job already exists for the Glyma map: DomainUid: {0}, RootMapUid: {1}, Export Type: {2}, Map Type: {3}",
                                                                              domainUid.ToString(), rootMapUid.ToString(), exportType.ToString(), mapType.ToString()));
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception("Failed to find the Glyma Exports list.");
                                    }
                                }
                                else
                                {
                                    throw new Exception("The current user was not able to be determined.");
                                }
                            }
                            else
                            {
                                throw new Exception("The SPSite and/or the SPWeb were null.");
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ExportError error = new ExportError()
                {
                    ErrorMessage = "Failed to create the Glyma map export job."
                };
                throw new FaultException <ExportError>(error, ex.ToString());
            }

            return(response);
        }
コード例 #26
0
        /// <summary>
        /// Adds the SPListItem for the ExportJob to the GlymaExports lists if there isn't one already in the Scheduled ExportState for the exact same export.
        /// </summary>
        /// <param name="exportsList">The SPList that contains the ExportJobs</param>
        /// <param name="domainId">The DomainUid for the export to be created</param>
        /// <param name="rootmapId">The RootMapUid for the export to be created</param>
        /// <param name="mapType">The type of map (schema) that is being exported</param>
        /// <param name="type">The format of the export to be created</param>
        /// <param name="workItemId">The ID of the workitem</param>
        /// <param name="serializedExportProperties">The ExportProperties as an XML string</param>
        /// <returns>The ID of the list item created or -1 if it wasn't created because an existing item matched it in scheduled state.</returns>
        private int CreateExportJobListEntry(SPList exportsList, Guid domainId, Guid rootmapId, MapType mapType, ExportType type, Guid workItemId, string serializedExportProperties, int userId)
        {
            int listItemId = -1; //default value indicates that item wasn't created
            if (exportsList != null)
            {
                SPQuery query = new SPQuery();
                query.Query = "<Where><And><And><And><And>" +
                            "<And><Eq><FieldRef Name='DomainUid' /><Value Type='Text'>" + domainId.ToString() + "</Value></Eq>" +
                            "<Eq><FieldRef Name='RootMapUid' /><Value Type='Text'>" + rootmapId.ToString() + "</Value></Eq></And>" +
                            "<Eq><FieldRef Name='ExportStatus' /><Value Type='Choice'>" + ExportStatus.Scheduled.ToString() + "</Value></Eq></And>" +
                            "<Eq><FieldRef Name='ExportType' /><Value Type='Choice'>" + type.ToString() + "</Value></Eq></And>" +
                            "<Eq><FieldRef Name='ExportProperties' /><Value Type='Note'>" + serializedExportProperties + "</Value></Eq></And>" +
                            "<Eq><FieldRef Name='MapType' /><Value Type='Choice'>" + mapType.ToString() + "</Value></Eq>"  +
                            "</And></Where>";
                // Query for where this particular rootmap has been scheduled for export to the same type already
                SPListItemCollection existingSchedules = exportsList.GetItems(query);

                if (existingSchedules.Count == 0)
                {
                    //TODO get field names from constants
                    SPListItem exportJob = exportsList.Items.Add();
                    exportJob["ExportType"] = type.ToString();
                    exportJob["MapType"] = mapType.ToString();
                    exportJob["ExportStatus"] = ExportStatus.Scheduled.ToString();
                    exportJob["RootMapUid"] = rootmapId.ToString();
                    exportJob["DomainUid"] = domainId.ToString();
                    exportJob[SPBuiltInFieldId.Title] = workItemId.ToString();
                    exportJob["ExportProperties"] = serializedExportProperties;
                    exportJob["PercentageComplete"] = 0;
                    exportJob[SPBuiltInFieldId.Author] = userId;
                    exportJob[SPBuiltInFieldId.Editor] = userId;
                    exportJob.Update();
                    listItemId = exportJob.ID;
                }
            }
            return listItemId;
        }
コード例 #27
0
        public static void WriteScanJson(int ResultType, string BaseId, string CompareId, bool ExportAll, string OutputPath)
        {
            List <RESULT_TYPE> ToExport = new List <RESULT_TYPE> {
                (RESULT_TYPE)ResultType
            };
            Dictionary <RESULT_TYPE, int> actualExported = new Dictionary <RESULT_TYPE, int>();
            JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings()
            {
                Formatting           = Formatting.Indented,
                NullValueHandling    = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore,
                Converters           = new List <JsonConverter>()
                {
                    new StringEnumConverter()
                }
            });

            if (ExportAll)
            {
                ToExport = new List <RESULT_TYPE> {
                    RESULT_TYPE.FILE, RESULT_TYPE.CERTIFICATE, RESULT_TYPE.PORT, RESULT_TYPE.REGISTRY, RESULT_TYPE.SERVICE, RESULT_TYPE.USER
                };
            }

            foreach (RESULT_TYPE ExportType in ToExport)
            {
                Log.Information("Exporting {0}", ExportType);
                List <CompareResult> records = DatabaseManager.GetComparisonResults(AsaHelpers.RunIdsToCompareId(BaseId, CompareId), ExportType);

                actualExported.Add(ExportType, records.Count);

                if (records.Count > 0)
                {
                    serializer.Converters.Add(new StringEnumConverter());
                    var o = new Dictionary <string, Object>();
                    o["results"]  = records;
                    o["metadata"] = AsaHelpers.GenerateMetadata();
                    using (StreamWriter sw = new StreamWriter(Path.Combine(OutputPath, AsaHelpers.MakeValidFileName(BaseId + "_vs_" + CompareId + "_" + ExportType.ToString() + ".json.txt")))) //lgtm [cs/path-injection]
                    {
                        using (JsonWriter writer = new JsonTextWriter(sw))
                        {
                            serializer.Serialize(writer, o);
                        }
                    }
                }
            }

            serializer.Converters.Add(new StringEnumConverter());
            var output = new Dictionary <string, Object>();

            output["results"]  = actualExported;
            output["metadata"] = AsaHelpers.GenerateMetadata();
            using (StreamWriter sw = new StreamWriter(Path.Combine(OutputPath, AsaHelpers.MakeValidFileName(BaseId + "_vs_" + CompareId + "_summary.json.txt")))) //lgtm [cs/path-injection]
            {
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, output);
                }
            }
        }
コード例 #28
0
ファイル: Facade.cs プロジェクト: hellowod/xlsx2string
 private static string GetExporterPath(ExportType type)
 {
     return(string.Format("{0}/{1}", DataMemory.GetOptionsFrom().XlsxDstPath, type.ToString()));
 }
コード例 #29
0
        public Byte[] GetByte(string ReportServerUrl, string ReportUserName, string ReportPassword, string ReportDomain, string ReportPath, string ReportName, List <ReportParameter> paramter, ExportType exportType)
        {
            // Prepare Render arguments
            string historyID  = null;
            string deviceInfo = null;
            string format     = exportType.ToString();

            Byte[] results;
            string encoding  = String.Empty;
            string mimeType  = String.Empty;
            string extension = String.Empty;

            ReportExecution2005.Warning[] warnings = null;
            string[] streamIDs = null;
            ReportExecution2005.ParameterValue[] rptParameters = null;

            try
            {
                ReportExecution2005.ReportExecutionService myReport = new ReportExecution2005.ReportExecutionService();
                myReport.Url = ReportServerUrl;
                if (ReportDomain != string.Empty && ReportDomain.Length > 0)
                {
                    myReport.Credentials = new System.Net.NetworkCredential(ReportUserName, ReportPassword, ReportDomain);
                }
                else
                {
                    myReport.Credentials = new System.Net.NetworkCredential(ReportUserName, ReportPassword);
                }

                ReportExecution2005.ExecutionInfo ei;
                if (ReportPath != null && ReportPath.Length > 0)
                {
                    ei = myReport.LoadReport("/" + ReportPath + "/" + ReportName, historyID);
                }
                else
                {
                    if (ReportName != null && ReportName.Length > 0)
                    {
                        ei = myReport.LoadReport("/" + ReportName, historyID);
                    }
                    else
                    {
                        return(new Byte[0]);
                    }
                }

                /* This code for set credentials on runtime
                 * require [using SCG.eAccounting.Report.ReportExecution2005;]
                 * if (ei.CredentialsRequired)
                 * {
                 *  List<DataSourceCredentials> credentials = new List<DataSourceCredentials>();
                 *  foreach (DataSourcePrompt dsp in ei.DataSourcePrompts)
                 *  {
                 *      DataSourceCredentials cred = new DataSourceCredentials();
                 *      cred.DataSourceName = dsp.Name;
                 *      cred.UserName = [Database Username];
                 *      cred.Password = [Database Password];
                 *      credentials.Add(cred);
                 *  }
                 *
                 *  Console.WriteLine("Setting data source credentials...");
                 *  ei = myReport.SetExecutionCredentials(credentials.ToArray());
                 * }
                 */

                if (paramter != null && paramter.Count > 0)
                {
                    rptParameters = new ReportExecution2005.ParameterValue[paramter.Count];
                    for (int i = 0; i < paramter.Count; i++)
                    {
                        rptParameters[i]       = new ReportExecution2005.ParameterValue();
                        rptParameters[i].Name  = paramter[i].ParamterName;
                        rptParameters[i].Value = paramter[i].ParamterValue;
                    }
                }


                deviceInfo = "<DeviceInfo>" + "<SimplePageHeaders>True</SimplePageHeaders>" + "</DeviceInfo>";
                //render the PDF
                myReport.SetExecutionParameters(rptParameters, "th-TH");
                results = myReport.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(results);
        }