Exemplo n.º 1
0
        protected virtual void WebPreview()
        {
            Exporter exporter = new Exporter(OwnerCanvas);

            exporter.ExportMuseumGuideHTML("temp", Global.ExecutionPath);

            Global.MainWindow.WebPreview.Navigate(new Uri(Global.ExecutionPath + "temp\\index.htm").AbsoluteUri);
        }
        public ExporterViewModel(Exporter exporter)
        {
            BusinessName = exporter.BusinessName;

            Address = new AddressViewModel(exporter.Address);

            Contact = new ContactViewModel(exporter.Contact);
        }
 public ExporterViewModel(Exporter exporter)
 {
     Name = exporter.Business.Name;
     address = new AddressViewModel(exporter.Address);
     ContactPerson = exporter.Contact.FullName;
     Telephone = exporter.Contact.Telephone.ToFormattedContact();
     Fax = exporter.Contact.Fax.ToFormattedContact();
     Email = exporter.Contact.Email;
     RegistrationNumber = exporter.Business.RegistrationNumber;
 }
        public ExporterTests()
        {
            _log = Mock.Of<ILog>();
            _database = Mock.Of<IDatabase>();
            _markerStorage = Mock.Of<IMarkerStorage>();
            _ticketRetriever = Mock.Of<ITicketRetriever>();
            _mergeExporter = Mock.Of<IMergedTicketExporter>();
            _csvFileWriter = Mock.Of<ICsvFileWriter>();

            _sut = new Exporter(_log, _database, _markerStorage, _ticketRetriever, _mergeExporter, _csvFileWriter);

            SetupDefaultMocks();
        }
        public void ImportValues()
        {
            var container = ContainerFactory.Create();
            Importer importer = new Importer();
            Exporter exporter42 = new Exporter(42);

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            batch.AddPart(exporter42);

            CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotSetImport,
                                          ErrorId.ReflectionModel_ImportNotAssignableFromExport, RetryMode.DoNotRetry, () =>
            {
                container.Compose(batch);
            });            
        }
Exemplo n.º 6
0
        /// <summary>
        /// 
        /// </summary>
        public FormMain()
        {
            try
            {
                InitializeComponent();

                this.Show();

                cboPageLimit.SelectedIndex = 6; // 100

                _sql = new Sql();
                string ret = _sql.Load();
                if (ret.Length > 0)
                {
                    UserInterface.DisplayErrorMessageBox(this, "An error occurred whilst loading the SQL queries, the application cannot continue: " + ret);
                    Misc.WriteToEventLog(Application.ProductName, "An error occurred whilst loading the SQL queries, the application cannot continue: " + ret, System.Diagnostics.EventLogEntryType.Error);

                    Application.Exit();
                }

                controlEvents.SetSql(_sql);
                controlEvents.Message += Control_OnMessage;

                controlRules.SetParent(this);
                controlRules.SetSql(_sql);
                controlRules.Message += Control_OnMessage;

                controlSearch.SetSql(_sql);
                controlSearch.Message += Control_OnMessage;

                controlSensors.SetSql(_sql);
                controlSensors.Message += Control_OnMessage;

                LoadConnections();

                _exporter = new Exporter();
                _exporter.SetSql(_sql);
                _exporter.Complete += OnExporter_Complete;
                _exporter.Error += OnExporter_Error;
                _exporter.Exclamation += OnExporter_Exclamation;
            }
            catch (Exception ex)
            {
                Misc.WriteToEventLog(Application.ProductName, ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        public FormAcknowledgmentExport(Sql sql)
        {
            InitializeComponent();

            cboFormat.SelectedIndex = 0;
            cboTimeFrom.SelectedIndex = 0;
            cboTimeTo.SelectedIndex = 0;
            dtpDateTo.Checked = false;

            _sql = sql;

            _exporter = new Exporter();
            _exporter.SetSql(_sql);
            _exporter.Complete += OnExporter_Complete;
            _exporter.Error += OnExporter_Error;
            _exporter.Exclamation += OnExporter_Exclamation;
        }
Exemplo n.º 8
0
        private void ExportToFreeMind()
        {
            try
            {
                string tempTabSep = Path.GetTempPath() + "cases_" + (Guid.NewGuid()) + ".mm";
                // create a writer and open the file

                var ex = new Exporter(_fb, new Search(FormatSearch(), _cases));
                ex.CasesToMindMap().Save(tempTabSep);

                Process.Start("\"" + tempTabSep + "\"");
            }
            catch (Exception x)
            {
                MessageBox.Show(@"Sorry, couldn't launch Excel");
                Utils.LogError(x.ToString());
            }
        }
        public async Task<ActionResult> Index(Guid id, ExporterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var exporter = new Exporter(id)
            {
                Address = model.Address.AsAddress(),
                BusinessName = model.BusinessName,
                Contact = model.Contact.AsContact()
            };

            await mediator.SendAsync(new SetDraftData<Exporter>(id, exporter));

            return RedirectToAction("Index", "Importer");
        }
        public override void Execute(object parameter)
        {
            var stream = GetOutputStream();

            if (stream == null)
                return;

            var columns = model.Columns.Columns.ToList();
            var collectionSource = model.Documents.Source;

            if (model.DocumentsHaveId)
            {
                columns.Insert(0, new ColumnDefinition() { Binding = "$JsonDocument:Key", Header = "Id" });
            }

            var cts = new CancellationTokenSource();

            var progressWindow = new ProgressWindow() { Title = "Exporting Report"};
            progressWindow.Closed += delegate { cts.Cancel(); };

            var exporter = new Exporter(stream, collectionSource, columns);

            var exportTask = exporter.ExportAsync(cts.Token, progress => progressWindow.Progress = progress)
                                     .ContinueOnUIThread(t =>
                                     {
                                         // there's a bug in silverlight where if a ChildWindow gets closed too soon after it's opened, it leaves the UI
                                         // disabled; so delay closing the window by a few milliseconds
                                         TaskEx.Delay(TimeSpan.FromMilliseconds(350))
                                               .ContinueOnSuccessInTheUIThread(progressWindow.Close);

                                         if (t.IsFaulted)
                                         {
                                             ApplicationModel.Current.AddErrorNotification(t.Exception,
                                                                                           "Exporting Report Failed");
                                         }
                                         else if (!t.IsCanceled)
                                         {
                                             ApplicationModel.Current.AddInfoNotification("Report Exported Successfully");
                                         }
                                     });

            progressWindow.Show();
        }
Exemplo n.º 11
0
        private void ExportToFreeMind()
        {
            try
            {

                String tempTabSep = System.IO.Path.GetTempPath() + "cases_" + (Guid.NewGuid()).ToString() + ".mm";
                // create a writer and open the file

                Exporter ex = new Exporter(_fb, new Search(_filter.FormatSearchQuery(), _cases));
                ex.CasesToMindMap().Save(tempTabSep);

                System.Diagnostics.Process.Start("\"" + tempTabSep + "\"");
            }
            catch (System.Exception x)
            {
                MessageBox.Show("Sorry, couldn't launch Excel");
                Utils.Log.Error(x.ToString());
            }
        }
 public static NotificationApplicationOverview Load(NotificationApplication notification,
     NotificationAssessment assessment,
     WasteRecovery.WasteRecovery wasteRecovery,
     WasteDisposal wasteDisposal,
     Exporter.Exporter exporter,
     Importer.Importer importer,
     int charge,
     NotificationApplicationCompletionProgress progress)
 {
     return new NotificationApplicationOverview
     {
         Exporter = exporter,
         Importer = importer,
         Notification = notification,
         NotificationAssessment = assessment,
         WasteRecovery = wasteRecovery,
         WasteDisposal = wasteDisposal,
         Charge = charge,
         Progress = progress
     };
 }
Exemplo n.º 13
0
        /// <summary>
        /// Exports the found behaviour files.
        /// </summary>
        /// <param name="exporterinfo">The exporter info of the exporter we want to use.</param>
        /// <param name="files">The behaviour files.</param>
        /// <param name="outputFolder">The folder the behaviours will be exported into.</param>
        /// <param name="exportIntoOneFolder">Defines if we export all behaviours into the output folder directly or if we create any sub folders found.</param>
        private static void ExportBehaviors(ExporterInfo exporterinfo, List <FileToExport> files, string outputFolder, bool exportIntoOneFolder)
        {
            Exporter exporter = null;

            for (int i = 0; i < files.Count; ++i)
            {
                FileToExport file = files[i];

                LogMessage(string.Format("Exporting \"{0}\"...", file.File));

                // reset previously loaded behavior
                FileManagers.FileManager.ResetLoadedBehavior();

                // load the behaviour file
                BehaviorNode behavior = _behaviorManager.LoadBehavior(file.File);
                if (behavior == null)
                {
                    throw new Exception(string.Format("Could not load behavior {0}", file.File));
                }

                // check if the file we exported comes from a folder or a given file
                string relativefile;
                if (file.BaseFolder == string.Empty || exportIntoOneFolder)
                {
                    // simply use the filename as it is
                    relativefile = Path.GetFileName(file.File);
                }
                else
                {
                    // create a relative filename of the behaviour to the folder it comes from
                    Uri root    = new Uri(Path.GetFullPath(file.BaseFolder) + '\\');
                    Uri thefile = new Uri(Path.GetFullPath(file.File));

                    Uri relative = root.MakeRelativeUri(thefile);

                    relativefile = Uri.UnescapeDataString(relative.OriginalString).Replace('/', '\\');
                }

                // generate the export filename
                string targetfile = Path.GetFullPath(outputFolder + '\\' + relativefile);

                // ensure that the export folder exists
                string finalOutputFolder = Path.GetDirectoryName(targetfile);
                Directory.CreateDirectory(finalOutputFolder);

                // remove the file extension
                //targetfile= targetfile.Substring(0, targetfile.Length - Path.GetExtension(targetfile).Length);
                relativefile = relativefile.Substring(0, relativefile.Length - Path.GetExtension(relativefile).Length);

                // export the behaviour
                bool firstRun = exporter == null;
                exporter = exporterinfo.Create(behavior, outputFolder, relativefile);

                // check if we must call pre export
                if (firstRun)
                {
                    if (!exporter.PreExport(true))
                    {
                        throw new Exception("Export process was aborted");
                    }
                }

                exporter.Export();
            }

            // call post export
            if (exporter != null)
            {
                exporter.PostExport(true);
            }
        }
Exemplo n.º 14
0
        private static void RegenerateEverything(UnityProjectInfo unityProjectInfo, bool completeGeneration)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            long postCleanupAndCopyStamp = 0, solutionExportStart = 0, solutionExportEnd = 0, exporterStart = 0, exporterEnd = 0, propsFileGenerationStart = 0, propsFileGenerationEnd = 0;

            try
            {
                if (Directory.Exists(Utilities.MSBuildProjectFolder))
                {
                    // Create a copy of the packages as they might change after we create the MSBuild project
                    foreach (string file in Directory.EnumerateFiles(Utilities.MSBuildProjectFolder, "*", SearchOption.TopDirectoryOnly))
                    {
                        File.SetAttributes(file, FileAttributes.Normal);
                        File.Delete(file);
                    }
                }
                else
                {
                    Directory.CreateDirectory(Utilities.MSBuildProjectFolder);
                }

                postCleanupAndCopyStamp = stopwatch.ElapsedMilliseconds;

                propsFileGenerationStart = stopwatch.ElapsedMilliseconds;
                MSBuildUnityProjectExporter.ExportCommonPropsFile(Exporter, MSBuildForUnityVersion, unityProjectInfo.CurrentPlayerPlatform);
                if (completeGeneration)
                {
                    ExportCoreUnityPropFiles(unityProjectInfo);
                }
                propsFileGenerationEnd = stopwatch.ElapsedMilliseconds;

                solutionExportStart = stopwatch.ElapsedMilliseconds;
                if (completeGeneration)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(Utilities.MSBuildProjectFolder);
                    unityProjectInfo.ExportSolution(Exporter, new FileInfo(Exporter.GetSolutionFilePath(unityProjectInfo)), directoryInfo);
                    unityProjectInfo.ExportProjects(Exporter, directoryInfo);
                }
                MSBuildUnityProjectExporter.ExportTopLevelDependenciesProject(Exporter, MSBuildForUnityVersion, Config, new DirectoryInfo(Utilities.MSBuildProjectFolder), unityProjectInfo);
                solutionExportEnd = stopwatch.ElapsedMilliseconds;


                string nuGetConfigPath = Path.Combine(Utilities.AssetPath, Path.GetFileName(TemplateFiles.Instance.NuGetConfigPath));

                // Copy the NuGet.config file if it does not exist
                if (!File.Exists(nuGetConfigPath))
                {
                    File.Copy(TemplateFiles.Instance.NuGetConfigPath, nuGetConfigPath);
                }

                foreach (string otherFile in TemplateFiles.Instance.OtherFiles)
                {
                    File.Copy(otherFile, Path.Combine(Utilities.MSBuildProjectFolder, Path.GetFileName(otherFile)));
                }

                if (completeGeneration)
                {
                    string buildProjectsFile = "BuildProjects.proj";
                    if (!File.Exists(Path.Combine(Utilities.MSBuildOutputFolder, buildProjectsFile)))
                    {
                        GenerateBuildProjectsFile(buildProjectsFile, Exporter.GetSolutionFilePath(unityProjectInfo), unityProjectInfo.AvailablePlatforms);
                    }
                }
            }
            finally
            {
                stopwatch.Stop();
                Debug.Log($"Whole Generate Projects process took {stopwatch.ElapsedMilliseconds} ms; actual generation took {stopwatch.ElapsedMilliseconds - postCleanupAndCopyStamp}; solution export: {solutionExportEnd - solutionExportStart}; exporter creation: {exporterEnd - exporterStart}; props file generation: {propsFileGenerationEnd - propsFileGenerationStart}");
            }
        }
Exemplo n.º 15
0
        protected override void Initialize()
        {
            RegisterExportHandler <Model>(filePath =>
            {
                var configuration = ConfigurationList.Instance.CurrentConfiguration;

                var objectDatabase  = configuration?.ObjectDatabase;
                var textureDatabase = configuration?.TextureDatabase;
                var boneDatabase    = configuration?.BoneDatabase;

                Data.Save(filePath, objectDatabase, textureDatabase, boneDatabase);
            });
            RegisterExportHandler <Scene>(filePath => Exporter.ConvertAiSceneFromModel(Data, filePath));
            RegisterReplaceHandler <Model>(filePath =>
            {
                var configuration = ConfigurationList.Instance.CurrentConfiguration;

                var objectDatabase  = configuration?.ObjectDatabase;
                var textureDatabase = configuration?.TextureDatabase;

                var model = new Model();
                model.Load(filePath, objectDatabase, textureDatabase);
                return(model);
            });
            RegisterReplaceHandler <Scene>(filePath =>
            {
                if (Data.Meshes.Count > 1)
                {
                    return(Importer.ConvertModelFromAiScene(filePath));
                }

                return(Importer.ConvertModelFromAiSceneWithSingleMesh(filePath));
            });
            RegisterCustomHandler("Rename all shaders to...", () =>
            {
                using (var inputDialog = new InputDialog {
                    WindowTitle = "Rename all shaders", Input = "BLINN"
                })
                {
                    if (inputDialog.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    foreach (var material in Data.Meshes.SelectMany(x => x.Materials))
                    {
                        material.Shader = inputDialog.Input;
                    }
                }

                IsDirty = true;
            });
            RegisterCustomHandler("Convert triangles to triangle strips", () =>
            {
                foreach (var indexTable in Data.Meshes.SelectMany(x => x.SubMeshes).SelectMany(x => x.IndexTables))
                {
                    if (indexTable.PrimitiveType == PrimitiveType.Triangles)
                    {
                        ushort[] triangleStrip = Stripifier.Stripify(indexTable.Indices);
                        if (triangleStrip != null)
                        {
                            indexTable.PrimitiveType = PrimitiveType.TriangleStrip;
                            indexTable.Indices       = triangleStrip;
                        }
                    }
                }

                IsDirty = true;
            });
            RegisterCustomHandler("Combine all meshes into one", () =>
            {
                if (Data.Meshes.Count <= 1)
                {
                    return;
                }

                var combinedMesh = new Mesh {
                    Name = "Combined mesh"
                };
                var indexMap = new Dictionary <int, int>();

                foreach (var mesh in Data.Meshes)
                {
                    if (mesh.Skin != null)
                    {
                        if (combinedMesh.Skin == null)
                        {
                            combinedMesh.Skin = new Skin();
                            combinedMesh.Skin.Bones.AddRange(mesh.Skin.Bones);
                        }
                        else
                        {
                            for (int i = 0; i < mesh.Skin.Bones.Count; i++)
                            {
                                var bone      = mesh.Skin.Bones[i];
                                var boneIndex = combinedMesh.Skin.Bones
                                                .FindIndex(x => x.Name.Equals(bone.Name, StringComparison.OrdinalIgnoreCase));

                                if (boneIndex == -1)
                                {
                                    indexMap[i] = combinedMesh.Skin.Bones.Count;
                                    combinedMesh.Skin.Bones.Add(bone);
                                }
                                else
                                {
                                    indexMap[i] = boneIndex;
                                }
                            }

                            foreach (var indexTable in mesh.SubMeshes.SelectMany(x => x.IndexTables))
                            {
                                if (indexTable.BoneIndices?.Length >= 1)
                                {
                                    for (int i = 0; i < indexTable.BoneIndices.Length; i++)
                                    {
                                        indexTable.BoneIndices[i] = ( ushort )indexMap[indexTable.BoneIndices[i]];
                                    }
                                }
                            }
                        }
                    }

                    foreach (var indexTable in mesh.SubMeshes.SelectMany(x => x.IndexTables))
                    {
                        indexTable.MaterialIndex += combinedMesh.Materials.Count;
                    }

                    combinedMesh.SubMeshes.AddRange(mesh.SubMeshes);
                    combinedMesh.Materials.AddRange(mesh.Materials);
                }

                Data.Meshes.Clear();
                Data.Meshes.Add(combinedMesh);

                if (IsPopulated)
                {
                    IsPopulated = false;
                    Populate();
                }

                IsDirty = true;
            });

            base.Initialize();
        }
Exemplo n.º 16
0
        public void Exporter_VContact()
        {
            var contact = new VContact
            {
                Name = "Keith Williams",
                FormattedName = "Williams, Keith",
                Birthday = new DateTime(1981, 4, 23),
                Title = "Captain",
                Organization = "4verse",
                Note = "Lorem ipsum dolor sit amet."
            };

            contact.Addresses.Add(new VAddress
            {
                StreetAddress = "28 St. Paul's Terrace",
                Locality = "York",
                Region = "North Yorkshire",
                PostalCode = "YO24 4BL",
                Country = "UNITED KINGDOM"
            });

            contact.TelephoneNumbers.Add(new VTelephone
            {
                TelephoneType = TelephoneType.CELL,
                Value = "07941521644",
                CountryCode = 44
            });

            contact.TelephoneNumbers.Add(new VTelephone
            {
                TelephoneType = TelephoneType.HOME,
                Value = "658796",
                AreaCode = "01904",
                CountryCode = 44
            });

            contact.EmailAddresses.Add(new VEmail
            {
                EmailType = EmailType.INTERNET,
                Value = "*****@*****.**"
            });

            contact.EmailAddresses.Add(new VEmail
            {
                EmailType = EmailType.INTERNET,
                Value = "*****@*****.**"
            });

            var exporter = new Exporter(contact);
            //var result = exporter.Export();

            var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".vcf");
            exporter.SaveAs(path);
        }
Exemplo n.º 17
0
        private void ExportToXml_Click(object sender, RoutedEventArgs e)
        {
            Exporter exporter = new Exporter(workArea);

            string path = null;

            if (Global.Template == Data.Resources.TemplateType.UrbanGame)
            {
                 var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
                 folderDialog.Description = "Select the destination folder of the template.";
                 var dialogres = folderDialog.ShowDialog();
                 if (dialogres != System.Windows.Forms.DialogResult.OK)
                 { MessageBox.Show("Operation aborted."); return; }
                 path = folderDialog.SelectedPath;
            }
            else
            {
                var fileDialog = new Microsoft.Win32.SaveFileDialog();
                fileDialog.Filter = "CHe Xml File|*.xml";
                var result = fileDialog.ShowDialog();
                if (result.HasValue && result.Value)
                    path = fileDialog.SafeFileName;
            }

            if (path!=null)
            {
                bool success = true;
                switch (Global.Template)
                {
                    case Data.Resources.TemplateType.MuseumGuide:
                        exporter.ExportMuseumGuideXML(path);
                        break;
                    case Data.Resources.TemplateType.ExcursionGame:
                        success = exporter.ExportExcursionGameXML(path);
                        break;
                    case Data.Resources.TemplateType.UrbanGame:
                        success = exporter.ExportUrbanGameXML(path);
                        break;
                    default:
                        break;
                }
                if (success)
                    MessageBox.Show("Export operation successfully completed !", "Export", MessageBoxButton.OK, MessageBoxImage.Information);

            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Stores supplemental metadata representing distinct dictionary keys seen on the stream.
 /// </summary>
 /// <typeparam name="TKey">The type of dictionary key in the stream.</typeparam>
 /// <typeparam name="TValue">The type of dictionary value in the stream.</typeparam>
 /// <param name="source">The source stream to write.</param>
 /// <param name="writer">The store writer, created by e.g. <see cref="PsiStore.Create(Pipeline, string, string, bool, KnownSerializers)"/>.</param>
 public static void SummarizeDistinctKeysInSupplementalMetadata <TKey, TValue>(this IProducer <Dictionary <TKey, TValue> > source, Exporter writer)
 {
     writer.SummarizeDistinctKeysInSupplementalMetadata(source.Out);
 }
 public MovementExporterBlock(IList<MergeField> mergeFields, Exporter exporter)
     : base(mergeFields, exporter)
 {
 }
Exemplo n.º 20
0
        public ExporterBlock(IList<MergeField> mergeFields, Exporter exporter)
        {
            CorrespondingMergeFields = MergeFieldLocator.GetCorrespondingFieldsForBlock(mergeFields, TypeName);

            data = new ExporterViewModel(exporter);
        }
        public void ImportValueExceptionSetterException()
        {
            var container = ContainerFactory.Create();
            ImporterInvalidSetterException importer = new ImporterInvalidSetterException();
            Exporter exporter42 = new Exporter(42);

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            batch.AddPart(exporter42);

            CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotActivate,
                                          ErrorId.ReflectionModel_ImportThrewException, 
                                          RetryMode.DoNotRetry, () =>
            {
                container.Compose(batch);
            });
        }
        public void ImportValueExceptionMultiple()
        {
            var container = ContainerFactory.Create();
            Importer importer = new Importer();
            Exporter exporter42 = new Exporter(42);
            Exporter exporter6 = new Exporter(6);

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            batch.AddPart(exporter42);
            batch.AddPart(exporter6);

            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PartCannotSetImport,
                RetryMode.DoNotRetry, () =>
            {
                container.Compose(batch);
            });
        }
Exemplo n.º 23
0
 public void Setup()
 {
     // Runs before each test. (Optional)
     _importer = new Importer();
     _exporter = new Exporter();
 }
Exemplo n.º 24
0
 /// <summary>
 /// Writes the specified stream to a multi-stream \psi store.
 /// </summary>
 /// <typeparam name="TMessage">The type of messages in the stream.</typeparam>
 /// <param name="source">The source stream to write.</param>
 /// <param name="name">The name of the persisted stream.</param>
 /// <param name="writer">The store writer, created by e.g. <see cref="PsiStore.Create(Pipeline, string, string, bool, KnownSerializers)"/>.</param>
 /// <param name="largeMessages">Indicates whether the stream contains large messages (typically >4k). If true, the messages will be written to the large message file.</param>
 /// <param name="deliveryPolicy">An optional delivery policy.</param>
 /// <returns>The input stream.</returns>
 public static IProducer <TMessage> Write <TMessage>(this IProducer <TMessage> source, string name, Exporter writer, bool largeMessages = false, DeliveryPolicy <TMessage> deliveryPolicy = null)
 {
     writer.Write(source.Out, name, largeMessages, deliveryPolicy);
     return(source);
 }
Exemplo n.º 25
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Exporter obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Exemplo n.º 26
0
        public void ConvertModels(string inputDirectoryPath, string outputDirectoryPath, Exporter exporter)
        {
            string outputExtension = exporter.Options.OutputFormat.ToString().ToLower();

            ProgressUpdate("Enumerating files ...", 0, 1);
            List <string> inputFilePaths = EnumerateFiles(inputDirectoryPath, exporter.Options.InputFormat);

            ProgressUpdate("Converting resources ...", 0, 1);
            for (var i = 0; i < inputFilePaths.Count; i++)
            {
                string inputFilePath = inputFilePaths[i];

                string outputFilePath = Path.ChangeExtension(inputFilePath.Replace(inputDirectoryPath, outputDirectoryPath), outputExtension);

                FileManager.TryToCreateDirectory(outputFilePath);

                ProgressUpdate($"Converting: {inputFilePath}", i, inputFilePaths.Count);
                try
                {
                    Root model = LoadModel(inputFilePath, exporter.Options.InputFormat);
                    SaveModel(model, outputFilePath, exporter);
                }
                catch (Exception exc)
                {
                    ConversionError(inputFilePath, outputFilePath, exc);
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Base implementation to export IFC site object.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="document">The Revit document.  It may be null if element isn't.</param>
        /// <param name="element">The element.  It may be null if document isn't.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        private static void ExportSiteBase(ExporterIFC exporterIFC, Document document, Element element, GeometryElement geometryElement, ProductWrapper productWrapper)
        {
            IFCAnyHandle siteHandle = ExporterCacheManager.SiteHandle;

            int numSiteElements = (!IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle) ? 1 : 0);

            if (element == null && (numSiteElements != 0))
            {
                return;
            }

            Document doc = document;

            if (doc == null)
            {
                if (element != null)
                {
                    doc = element.Document;
                }
                else
                {
                    throw new ArgumentException("Both document and element are null.");
                }
            }

            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            Common.Enums.IFCEntityType elementClassTypeEnum;
            if (Enum.TryParse <Common.Enums.IFCEntityType>("IfcSite", out elementClassTypeEnum))
            {
                if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
                {
                    return;
                }
            }

            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                IFCAnyHandle siteRepresentation = null;
                if (element != null)
                {
                    // It would be possible that they actually represent several different sites with different buildings,
                    // but until we have a concept of a building in Revit, we have to assume 0-1 sites, 1 building.
                    bool appendedToSite     = false;
                    bool exportAsFacetation = !ExporterCacheManager.ExportOptionsCache.ExportAsCoordinationView2;
                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle))
                    {
                        IList <IFCAnyHandle> representations = IFCAnyHandleUtil.GetProductRepresentations(siteHandle);
                        if (representations.Count > 0)
                        {
                            IFCAnyHandle bodyRep     = representations[0];
                            IFCAnyHandle boundaryRep = null;
                            if (representations.Count > 1)
                            {
                                boundaryRep = representations[1];
                            }

                            siteRepresentation = RepresentationUtil.CreateSurfaceProductDefinitionShape(exporterIFC, element, geometryElement, true, exportAsFacetation, ref bodyRep, ref boundaryRep);
                            if (representations.Count == 1 && !IFCAnyHandleUtil.IsNullOrHasNoValue(boundaryRep))
                            {
                                // If the first site has no boundaryRep,
                                // we will add the boundaryRep from second site to it.
                                representations.Clear();
                                representations.Add(boundaryRep);
                                IFCAnyHandleUtil.AddProductRepresentations(siteHandle, representations);
                            }
                            appendedToSite = true;
                        }
                    }

                    if (!appendedToSite)
                    {
                        siteRepresentation = RepresentationUtil.CreateSurfaceProductDefinitionShape(exporterIFC, element, geometryElement, true, exportAsFacetation);
                    }
                }

                List <int>      latitude     = new List <int>();
                List <int>      longitude    = new List <int>();
                ProjectLocation projLocation = doc.ActiveProjectLocation;

                IFCAnyHandle relativePlacement = null;
                double       unscaledElevation = 0.0;
                if (projLocation != null)
                {
                    const double scaleToDegrees = 180 / Math.PI;
                    double       latitudeInDeg  = projLocation.GetSiteLocation().Latitude *scaleToDegrees;
                    double       longitudeInDeg = projLocation.GetSiteLocation().Longitude *scaleToDegrees;

                    ExporterUtil.GetSafeProjectPositionElevation(doc, out unscaledElevation);

                    int latDeg     = ((int)latitudeInDeg); latitudeInDeg -= latDeg; latitudeInDeg *= 60;
                    int latMin     = ((int)latitudeInDeg); latitudeInDeg -= latMin; latitudeInDeg *= 60;
                    int latSec     = ((int)latitudeInDeg); latitudeInDeg -= latSec; latitudeInDeg *= 1000000;
                    int latFracSec = ((int)latitudeInDeg);
                    latitude.Add(latDeg);
                    latitude.Add(latMin);
                    latitude.Add(latSec);
                    if (!ExporterCacheManager.ExportOptionsCache.ExportAs2x2)
                    {
                        latitude.Add(latFracSec);
                    }

                    int longDeg     = ((int)longitudeInDeg); longitudeInDeg -= longDeg; longitudeInDeg *= 60;
                    int longMin     = ((int)longitudeInDeg); longitudeInDeg -= longMin; longitudeInDeg *= 60;
                    int longSec     = ((int)longitudeInDeg); longitudeInDeg -= longSec; longitudeInDeg *= 1000000;
                    int longFracSec = ((int)longitudeInDeg);
                    longitude.Add(longDeg);
                    longitude.Add(longMin);
                    longitude.Add(longSec);
                    if (!ExporterCacheManager.ExportOptionsCache.ExportAs2x2)
                    {
                        longitude.Add(longFracSec);
                    }

                    ExportOptionsCache.SiteTransformBasis transformBasis = ExporterCacheManager.ExportOptionsCache.SiteTransformation;

                    Transform siteSharedCoordinatesTrf = Transform.Identity;

                    if (transformBasis != ExportOptionsCache.SiteTransformBasis.Internal)
                    {
                        BasePoint basePoint = null;
                        if (transformBasis == ExportOptionsCache.SiteTransformBasis.Project)
                        {
                            basePoint = new FilteredElementCollector(doc).WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_ProjectBasePoint)).First() as BasePoint;
                        }
                        else if (transformBasis == ExportOptionsCache.SiteTransformBasis.Site)
                        {
                            basePoint = new FilteredElementCollector(doc).WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_SharedBasePoint)).First() as BasePoint;
                        }

                        if (basePoint != null)
                        {
                            BoundingBoxXYZ bbox = basePoint.get_BoundingBox(null);
                            XYZ            xyz  = bbox.Min;
                            siteSharedCoordinatesTrf = Transform.CreateTranslation(new XYZ(-xyz.X, -xyz.Y, unscaledElevation - xyz.Z));
                        }
                        else
                        {
                            siteSharedCoordinatesTrf = projLocation.GetTransform().Inverse;
                        }
                    }

                    if (!siteSharedCoordinatesTrf.IsIdentity)
                    {
                        double unscaledSiteElevation = ExporterCacheManager.ExportOptionsCache.IncludeSiteElevation ? 0.0 : unscaledElevation;
                        XYZ    orig = UnitUtil.ScaleLength(siteSharedCoordinatesTrf.Origin - new XYZ(0, 0, unscaledSiteElevation));
                        relativePlacement = ExporterUtil.CreateAxis2Placement3D(file, orig, siteSharedCoordinatesTrf.BasisZ, siteSharedCoordinatesTrf.BasisX);
                    }
                }

                // Get elevation for site.
                double elevation = UnitUtil.ScaleLength(unscaledElevation);

                if (IFCAnyHandleUtil.IsNullOrHasNoValue(relativePlacement))
                {
                    relativePlacement = ExporterUtil.CreateAxis2Placement3D(file);
                }

                IFCAnyHandle localPlacement = IFCInstanceExporter.CreateLocalPlacement(file, null, relativePlacement);
                IFCAnyHandle ownerHistory   = ExporterCacheManager.OwnerHistoryHandle;
                string       siteObjectType = NamingUtil.CreateIFCObjectName(exporterIFC, element);

                ProjectInfo projectInfo     = doc.ProjectInformation;
                Element     mainSiteElement = (element != null) ? element : projectInfo;

                bool   exportSite          = false;
                string siteGUID            = null;
                string siteName            = null;
                string siteLongName        = null;
                string siteLandTitleNumber = null;
                string siteDescription     = null;

                if (element != null)
                {
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle))
                    {
                        exportSite = true;

                        // We will use the Project Information site name as the primary name, if it exists.
                        siteGUID = GUIDUtil.CreateSiteGUID(doc, element);

                        siteName        = NamingUtil.GetOverrideStringValue(projectInfo, "SiteName", NamingUtil.GetNameOverride(element, NamingUtil.GetIFCName(element)));
                        siteDescription = NamingUtil.GetDescriptionOverride(element, null);

                        // Look in site element for "IfcLongName" or project information for either "IfcLongName" or "SiteLongName".
                        siteLongName = NamingUtil.GetLongNameOverride(projectInfo, NamingUtil.GetLongNameOverride(element, null));
                        if (string.IsNullOrWhiteSpace(siteLongName))
                        {
                            siteLongName = NamingUtil.GetOverrideStringValue(projectInfo, "SiteLongName", null);
                        }

                        // Look in site element for "IfcLandTitleNumber" or project information for "SiteLandTitleNumber".
                        siteLandTitleNumber = NamingUtil.GetOverrideStringValue(element, "IfcLandTitleNumber", null);
                        if (string.IsNullOrWhiteSpace(siteLandTitleNumber))
                        {
                            siteLandTitleNumber = NamingUtil.GetOverrideStringValue(projectInfo, "SiteLandTitleNumber", null);
                        }
                    }
                }
                else
                {
                    exportSite = true;

                    siteGUID            = GUIDUtil.CreateProjectLevelGUID(doc, IFCProjectLevelGUIDType.Site);
                    siteName            = NamingUtil.GetOverrideStringValue(projectInfo, "SiteName", "Default");
                    siteLongName        = NamingUtil.GetLongNameOverride(projectInfo, NamingUtil.GetOverrideStringValue(projectInfo, "SiteLongName", null));
                    siteLandTitleNumber = NamingUtil.GetOverrideStringValue(projectInfo, "SiteLandTitleNumber", null);

                    // don't bother if we have nothing in the site whatsoever.
                    if ((latitude.Count == 0 || longitude.Count == 0) && IFCAnyHandleUtil.IsNullOrHasNoValue(relativePlacement) &&
                        string.IsNullOrWhiteSpace(siteLongName) && string.IsNullOrWhiteSpace(siteLandTitleNumber))
                    {
                        return;
                    }
                }

                COBieProjectInfo cobieProjectInfo = ExporterCacheManager.ExportOptionsCache.COBieProjectInfo;
                // Override Site information when it is a special COBie export
                if (ExporterCacheManager.ExportOptionsCache.ExportAs2x3COBIE24DesignDeliverable && cobieProjectInfo != null)
                {
                    siteName        = cobieProjectInfo.SiteLocation;
                    siteDescription = cobieProjectInfo.SiteDescription;
                }

                if (exportSite)
                {
                    bool         assignToBldg = false;
                    bool         assignToSite = false;
                    IFCAnyHandle address      = Exporter.CreateIFCAddress(file, doc, projectInfo, out assignToBldg, out assignToSite);
                    if (!assignToSite)
                    {
                        address = null;
                    }

                    siteHandle = IFCInstanceExporter.CreateSite(exporterIFC, element, siteGUID, ownerHistory, siteName, siteDescription, localPlacement,
                                                                siteRepresentation, siteLongName, IFCElementComposition.Element, latitude, longitude, elevation, siteLandTitleNumber, address);
                    productWrapper.AddSite(mainSiteElement, siteHandle);
                    ExporterCacheManager.SiteHandle = siteHandle;
                }


                tr.Commit();
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// 
        /// </summary>
        public ControlRules()
        {
            InitializeComponent();

            Helper.AddListColumn(listEvents, "Src IP", "IpSrcTxt");
            Helper.AddListColumn(listEvents, "Src Port", "SrcPort");
            Helper.AddListColumn(listEvents, "Dst IP", "IpDstTxt");
            Helper.AddListColumn(listEvents, "Dst Port", "DstPort");
            Helper.AddListColumn(listEvents, "Protocol", "Protocol");
            Helper.AddListColumn(listEvents, "Host", "HttpHost");
            Helper.AddListColumn(listEvents, "Timestamp", "Timestamp");
            Helper.AddListColumn(listEvents, "TCP Flags", "TcpFlagsString");
            Helper.AddListColumn(listEvents, "Classification", "AcknowledgmentClass");
            Helper.AddListColumn(listEvents, "Initials", "Initials");
            Helper.AddListColumn(listEvents, "Payload (ASCII)", "PayloadAscii");
            Helper.ResizeEventListColumns(listEvents, false);

            listEvents.RowFormatter = delegate(OLVListItem olvi)
            {
                Event temp = (Event)olvi.RowObject;
                if (temp != null)
                {
                    if (temp.AcknowledgmentClass.ToLower() == "taken")
                    {
                        olvi.BackColor = Color.FromArgb(255, 246, 127); // Yellow
                    }
                    else if (temp.Initials.Length > 0)
                    {
                        olvi.BackColor = Color.FromArgb(176, 255, 119); // Green
                    }
                }
            };

            cboTimeFrom.SelectedIndex = 0;
            cboTimeTo.SelectedIndex = 0;
            dtpDateTo.Checked = false;

            _querier = new Querier();
            _querier.Error += OnQuerier_Error;
            _querier.Exclamation += OnQuerier_Exclamation;
            _querier.RuleQueryComplete += OnQuerier_RuleQueryComplete;
            _querier.RuleCheckQueryComplete += OnQuerier_RuleCheckQueryComplete;
            _querier.EventQueryComplete += OnQuerier_EventQueryComplete;
            _querier.RuleIpCsvQueryComplete += OnQuerier_RuleIpCsvQueryComplete;
            _querier.RuleIpListQueryComplete += OnQuerier_RuleIpListQueryComplete;

            _exporter = new Exporter();
            _exporter.Complete += OnExporter_Complete;
            _exporter.Error += OnExporter_Error;
            _exporter.Exclamation += OnExporter_Exclamation;

            _commands = new Commands();
            if (_commands.FileExists == true)
            {
                string ret1 = _commands.Load();
                if (ret1.Length > 0)
                {
                    UserInterface.DisplayErrorMessageBox(this, "An error occurred whilst loading the commands: " + ret1);
                }
            }

            _alerts = new Alerts();
            string ret2 = _alerts.Load();
            if (ret2.Length == 0)
            {
                if (_alerts.Interval > 0)
                {
                    _timerCheck = new System.Timers.Timer();
                    _timerCheck.Elapsed += OnTimerCheck_Elapsed;
                    _timerCheck.Interval = (_alerts.Interval * 60000); // Convert to milliseconds
                    _timerCheck.Enabled = true;
                }
            }

            LoadPriorities();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Выполнить действия после приёма команды ТУ
        /// </summary>
        public override void OnCommandReceived(int ctrlCnlNum, Command cmd, int userID, ref bool passToClients)
        {
            // экспорт в ручном режиме
            if (normalWork)
            {
                bool exportCurData = ctrlCnlNum == config.CurDataCtrlCnlNum;
                bool exportArcData = ctrlCnlNum == config.ArcDataCtrlCnlNum;
                bool exportEvents  = ctrlCnlNum == config.EventsCtrlCnlNum;
                bool procCmd       = true;

                if (exportCurData)
                {
                    log.WriteAction(Localization.UseRussian ?
                                    "Получена команда экспорта текущих данных" :
                                    "Export current data command received");
                }
                else if (exportArcData)
                {
                    log.WriteAction(Localization.UseRussian ?
                                    "Получена команда экспорта архивных данных" :
                                    "Export archive data command received");
                }
                else if (exportEvents)
                {
                    log.WriteAction(Localization.UseRussian ?
                                    "Получена команда экспорта событий" :
                                    "Export events command received");
                }
                else
                {
                    procCmd = false;
                }

                if (procCmd)
                {
                    passToClients = false;

                    if (cmd.CmdTypeID == BaseValues.CmdTypes.Binary)
                    {
                        string   dataSourceName;
                        DateTime dateTime;
                        GetCmdParams(cmd, out dataSourceName, out dateTime);

                        if (dataSourceName == "")
                        {
                            log.WriteLine(string.Format(Localization.UseRussian ?
                                                        "Источник данных не задан" : "Data source is not specified"));
                        }
                        else
                        {
                            Exporter exporter = FindExporter(dataSourceName);

                            if (exporter == null)
                            {
                                log.WriteLine(string.Format(Localization.UseRussian ?
                                                            "Неизвестный источник данных {0}" : "Unknown data source {0}", dataSourceName));
                            }
                            else
                            {
                                log.WriteLine(string.Format(Localization.UseRussian ?
                                                            "Источник данных: {0}" : "Data source: {0}", dataSourceName));

                                if (exportCurData)
                                {
                                    ExportCurDataFromFile(exporter);
                                }
                                else if (exportArcData)
                                {
                                    if (dateTime == DateTime.MinValue)
                                    {
                                        log.WriteLine(string.Format(Localization.UseRussian ?
                                                                    "Некорректная дата и время" : "Incorrect date and time"));
                                    }
                                    else
                                    {
                                        log.WriteLine(string.Format(Localization.UseRussian ?
                                                                    "Дата и время: {0:G}" : "Date and time: {0:G}", dateTime));
                                        ExportArcDataFromFile(exporter, dateTime);
                                    }
                                }
                                else // exportEvents
                                {
                                    if (dateTime == DateTime.MinValue)
                                    {
                                        log.WriteLine(string.Format(Localization.UseRussian ?
                                                                    "Некорректная дата" : "Incorrect date"));
                                    }
                                    else
                                    {
                                        log.WriteLine(string.Format(Localization.UseRussian ?
                                                                    "Дата: {0:d}" : "Date: {0:d}", dateTime));
                                        ExportEventsFromFile(exporter, dateTime);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        log.WriteAction(ModPhrases.IllegalCommand);
                    }
                }
            }
        }
Exemplo n.º 30
0
 public ExportPointer CreateExportPointer(Object @object)
 {
     return(Exporter.CreateExportPointer(@object));
 }
        public void Export(Shape shape)
        {
            Exporter exporter = new Exporter();

            exporter.Export(shape);
        }
Exemplo n.º 32
0
 public void Download()
 {
     Exporter.Instance().Download();
 }
 public override void Export()
 {
     Exporter.Export(this);
 }
Exemplo n.º 34
0
        static void RenderComponent(PaddedStringBuilder output, BField dataBField, bool userRawStringForMessaging)
        {
            var valueAccessPath = Exporter.GetResolvedPropertyName(dataBField.Name);

            var label = "Message." + dataBField.Name;

            if (userRawStringForMessaging)
            {
                label = '"' + dataBField.Name + '"';
            }


            if (dataBField.ComponentType == ComponentType.BDateTimePicker)
            {
                output.AppendLine("<BDateTimePicker format = \"DDMMYYYY\"");
                output.AppendLine("                 value = {data." + valueAccessPath + "}");
                output.AppendLine("                 dateOnChange = {(e: any, value: Date) => data." + valueAccessPath + " = value}");
                output.AppendLine("                 floatingLabelTextDate = {" + label + "}");
                output.AppendLine("                 context = {context}/>");
                return;
            }

            if (dataBField.ComponentType == ComponentType.BInput)
            {
                output.AppendLine("<BInput value = {data." + valueAccessPath + "}");
                output.AppendLine("        onChange = {(e: any, value: string) => data." + valueAccessPath + " = value}");
                output.AppendLine("        floatingLabelText = {" + label + "}");
                output.AppendLine("        context = {context}/>");
                return;
            }

            if (dataBField.ComponentType == ComponentType.BInputNumeric)
            {
                output.AppendLine("<BInputNumeric value = {data." + valueAccessPath + "}");
                output.AppendLine("               onChange = {(e: any, value: any) => data." + valueAccessPath + " = value}");
                output.AppendLine("               floatingLabelText = {" + label + "}");
                if (dataBField.DotNetType == DotNetType.Decimal)
                {
                    output.AppendLine("               format = {\"D\"}");
                    output.AppendLine("               maxLength = {22}");
                }
                else
                {
                    output.AppendLine("               maxLength = {10}");
                }

                output.AppendLine("               context = {context}/>");
                return;
            }

            if (dataBField.ComponentType == ComponentType.BAccountComponent)
            {
                output.AppendLine("<BAccountComponent accountNumber = {data." + valueAccessPath + "}");
                output.AppendLine("                   onAccountSelect = {(selectedAccount: any) => data." + valueAccessPath + " = selectedAccount ? selectedAccount.accountNumber : null}");
                output.AppendLine("                   isVisibleBalance={false}");
                output.AppendLine("                   isVisibleAccountSuffix={false}");
                output.AppendLine("                   enableShowDialogMessagesInCallback={false}");
                output.AppendLine("                   isVisibleIBAN={false}");
                output.AppendLine("                   ref={(r: any) => this.snaps." + dataBField.GetSnapName() + " = r}");
                output.AppendLine("                   context = {context}/>");
                return;
            }

            if (dataBField.ComponentType == ComponentType.BCheckBox)
            {
                output.AppendLine("<BCheckBox checked = {data." + valueAccessPath + "}");
                output.AppendLine("           onCheck = {(e: Object, isChecked: boolean) => data." + valueAccessPath + " = isChecked}");
                output.AppendLine("           label   = {" + label + "}");
                output.AppendLine("           context = {context}/>");
                return;
            }

            if (dataBField.ComponentType == ComponentType.BParameterComponent)
            {
                if (dataBField.DotNetType == DotNetType.Int32)
                {
                    output.AppendLine("<BParameterComponent selectedParamCode = {Helper.numberToString(data." + valueAccessPath + ")}");
                    output.AppendLine("                     onParameterSelect = {(selectedParameter: BOA.Types.Kernel.General.ParameterContract) => data." + valueAccessPath + " = selectedParameter ? Helper.stringToNumber(selectedParameter.paramCode) : null}");
                }
                else
                {
                    output.AppendLine("<BParameterComponent selectedParamCode = {data." + valueAccessPath + "}");
                    output.AppendLine("                     onParameterSelect = {(selectedParameter: BOA.Types.Kernel.General.ParameterContract) => data." + valueAccessPath + " = selectedParameter ? selectedParameter.paramCode : null}");
                }

                if (dataBField.ParamType.IsNullOrWhiteSpace())
                {
                    output.AppendLine("                     paramType=\"GENDER\"");
                }
                else
                {
                    output.AppendLine("                     paramType=\"" + dataBField.ParamType + "\"");
                }

                output.AppendLine("                     hintText = {" + label + "}");
                output.AppendLine("                     labelText = {" + label + "}");
                output.AppendLine("                     isAllOptionIncluded={true}");
                output.AppendLine("                     paramColumns={[");
                output.AppendLine("                            { name: \"paramCode\",        header: Message.Code,        visible: false },");
                output.AppendLine("                            { name: \"paramDescription\", header: Message.Description, width:   200 }");
                output.AppendLine("                     ]}");
                output.AppendLine("                     ref={(r: any) => this.snaps." + dataBField.GetSnapName() + " = r}");
                output.AppendLine("                     context = {context}/>");
                return;
            }

            if (dataBField.ComponentType == ComponentType.BBranchComponent)
            {
                output.AppendLine("<BBranchComponent selectedBranchId = {data." + valueAccessPath + "}");
                output.AppendLine("                  onBranchSelect = {(selectedBranch: BOA.Common.Types.BranchContract) => data." + valueAccessPath + " = selectedBranch ? selectedBranch.branchId : null}");
                output.AppendLine("                  mode={\"horizontal\"}");
                output.AppendLine("                  labelText = {" + label + "}");
                output.AppendLine("                  sortOption={BBranchComponent.name}");
                output.AppendLine("                  context = {context}/>");
            }
        }
Exemplo n.º 35
0
        private void exportSubsetFASTAToolStripMenuItem_Click (object sender, EventArgs e)
        {
            if (session == null)
                return;

            using (var exporter = new Exporter(session) { DataFilter = viewFilter })
            using (var saveDialog = new SaveFileDialog())
            {
                string dataSource = session.Connection.GetDataSource();
                saveDialog.InitialDirectory = Path.GetDirectoryName(dataSource);
                saveDialog.FileName = Path.GetFileNameWithoutExtension(dataSource) + ".fasta";
                saveDialog.Filter = "FASTA|*.fasta";
                saveDialog.AddExtension = true;

                bool addDecoys = MessageBox.Show("Do you want to add a decoy for each target protein?",
                                                 "Add Decoys",
                                                 MessageBoxButtons.YesNo,
                                                 MessageBoxIcon.Question,
                                                 MessageBoxDefaultButton.Button2) == DialogResult.Yes;

                if (saveDialog.ShowDialog(this) == DialogResult.OK)
                    exporter.WriteProteins(saveDialog.FileName, addDecoys);
            }
        }
 public SetExporterDetailsForImportNotification(Guid importNotificationId, Exporter exporterDetails)
 {
     ImportNotificationId = importNotificationId;
     ExporterDetails      = exporterDetails;
 }
Exemplo n.º 37
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Initializes a new instance of the <c>ReportsGenerator</c> class.
        /// </summary>
        /// <param name="exporter">Data exporter.</param>
        /// <param name="reports">Reports template settings keeper.</param>
        public ReportsGenerator(Exporter exporter, ReportsFile reports)
        {
            Debug.Assert(null != exporter);
            Debug.Assert(null != reports);

            _exporter = exporter;
            _reports = reports;
        }
Exemplo n.º 38
0
        static void Main(string[] args)
        {
            WriteLine("Enter connection string:");
            var connectionString = System.Console.ReadLine();

            WriteLine("Connecting to database...");
            var schildExport = new Exporter();

            schildExport.Configure(connectionString, true);

            bool isExited = false;

            while (!isExited)
            {
                // MENU
                WriteLine("Choose what to export:");
                WriteLine("[0] quit");
                WriteLine("[1] students");
                WriteLine("[2] privacy categories");
                WriteLine("[3] student privacies");
                WriteLine("[4] teachers");
                WriteLine("[5] subjects");
                WriteLine("[6] grades");
                WriteLine("[7] study groups");
                WriteLine("[8] tuitions");
                WriteLine("[9] school info");

                int choice = ReadInt();

                if (choice < 0 || choice > 9)
                {
                    WriteError("Please chose a valid option.");
                }

                switch (choice)
                {
                case 0:
                    isExited = true;
                    break;

                case 1:
                    WriteLine("Exporting students...");
                    WriteJson(GetResult(schildExport.GetStudentsAsync()));
                    break;

                case 2:
                    WriteLine("Exporting privacy categories...");
                    WriteJson(GetResult(schildExport.GetPrivacyCategoriesAsync()));
                    break;

                case 3:
                    WriteLine("Exporting student privacies");
                    WriteJson(GetResult(schildExport.GetStudentPrivaciesAsync(GetResult(schildExport.GetStudentsAsync()))));
                    break;

                case 4:
                    WriteLine("Exporting teachers...");
                    WriteJson(GetResult(schildExport.GetTeachersAsync()));
                    break;

                case 5:
                    WriteLine("Exporting subjects...");
                    WriteJson(GetResult(schildExport.GetSubjectsAsync()));
                    break;

                case 6:
                    WriteLine("Exporting grades...");
                    WriteJson(GetResult(schildExport.GetGradesAsync()));
                    break;

                case 7:
                    WriteLine("Get current academic year info...");
                    var info = GetResult(schildExport.GetSchoolInfoAsync());
                    WriteLine($"Acamdemic year: {info.CurrentYear}");
                    WriteLine($"Acamdemic year section: {info.CurrentSection}");

                    WriteJson(GetResult(schildExport.GetStudyGroupsAsync(GetResult(schildExport.GetStudentsAsync()), info.CurrentYear.Value, info.CurrentSection.Value)));
                    break;

                case 8:
                    WriteLine("Get current academic year info...");
                    info = GetResult(schildExport.GetSchoolInfoAsync());
                    WriteLine($"Acamdemic year: {info.CurrentYear}");
                    WriteLine($"Acamdemic year section: {info.CurrentSection}");

                    WriteJson(GetResult(schildExport.GetTuitionsAsync(GetResult(schildExport.GetStudentsAsync()), info.CurrentYear.Value, info.CurrentSection.Value)));
                    break;

                case 9:
                    WriteLine("Get current academic year info...");
                    WriteJson(GetResult(schildExport.GetSchoolInfoAsync()));
                    break;
                }
            }

            WriteLine("Bye");
        }
Exemplo n.º 39
0
        public void CanCreateExporter()
        {
            var exporter = new Exporter(importNotificationId, "business name", address, contact);

            Assert.IsType<Exporter>(exporter);
        }
 public void Accept(Exporter exporter)
 {
     exporter.Export(this);
 }
 public void Add(Exporter exporter)
 {
     context.Exporters.Add(exporter);
 }
        //double dispathch
        public void Export2(Shape shape)
        {
            Exporter exporter = new Exporter();

            shape.Accept(exporter);
        }
Exemplo n.º 43
0
        public static int Run(ExportOptions options, Client client, AuthManager authManager)
        {
            string exportDir = options.Path ?? Directory.GetCurrentDirectory();

            if (string.IsNullOrEmpty(options.Container))
            {
                var accountData = client.GetAccount().Result;
                if (accountData.IsSuccess)
                {
                    if (accountData.Containers != null && accountData.Containers.Count > 0)
                    {
                        var exporter = new Exporter(client, authManager.Credentials());

                        if (string.IsNullOrEmpty(options.Prefix))
                        {
                            exporter.GetObjects(accountData.Containers, exportDir);
                        }
                        else
                        {
                            exporter.GetObjectsWithPrefix(options.Prefix, accountData.Containers, exportDir);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No containers found");
                    }
                }
                else
                {
                    Logger.LogError(accountData.Reason);
                }
            }

            return 0;
        }
Exemplo n.º 44
0
        void Work()
        {
            while (Convert.ToInt32(lblTimesToDo.Text) > 0)
            {
                lblTimesToDo.Text = (Convert.ToInt32(lblTimesToDo.Text) - 1).ToString();
                foreach (Command c in commands)
                {
                    switch (c.Open)
                    {
                    case "open":
                    {
                        _serialPort.BaudRate = c.Files;
                        try
                        {
                            _serialPort.Open();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            Application.Exit();
                        }
                        break;
                    }

                    case "close":
                    {
                        _serialPort.Close();
                        break;
                    }

                    case "send":
                    {
                        WritePort(c.Array);
                        break;
                    }

                    case "sleep":
                    {
                        Thread.Sleep(c.Files);
                        break;
                    }
                    }
                }
            }
            StartAnaly(Application.StartupPath + @"\SendData\" + DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日.txt"
                       , Application.StartupPath + @"\ReciveData\" + DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日.txt");

            while (pro != null && !pro.HasExited)
            {
                Thread.Sleep(1000);
            }


            this.lbAnaly.Items.Add("正在导出为Excel...");
            this.lbAnaly.SelectedIndex = this.lbAnaly.Items.Count - 1;
            try
            {
                Exporter ept = new Exporter(DateTime.Now);
                ept.Export();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "异常");
            }
            this.lbAnaly.Items.Add("正在导出为Excel完成!");
            this.lbAnaly.SelectedIndex = this.lbAnaly.Items.Count - 1;

            btnStart.Enabled = true;
            txtTimes.Enabled = true;
        }
Exemplo n.º 45
0
    private void OnOkButtonClicked(object o, EventArgs args)
    {
        Exporter exporter = new Exporter (catalog);
        exporter.Template = template;
        if (exporter.Export (outputFileEntry.Filename)) {
            Gtk.Dialog dialog = new MessageDialog (null,
                    DialogFlags.Modal,
                    MessageType.Info,
                    ButtonsType.Ok,
                    Mono.Posix.Catalog.GetString ("Catalog succesfully exported"));
            dialog.Run();

            dialog.Destroy ();
        }
        else {
            Gtk.Dialog dialog = new MessageDialog (null,
                    DialogFlags.Modal,
                    MessageType.Error,
                    ButtonsType.Close,
                    Mono.Posix.Catalog.GetString ("Some error while exporting the catalog"));
            dialog.Run();

            dialog.Destroy ();
        }

        this.Destroy();
    }
Exemplo n.º 46
0
        // Gets all the features in the SolidWorks model doc that match the specific feature name, and updates the specified combobox.
        private void updateComboBoxFromFeatures(PropertyManagerPageCombobox box, string featureName)
        {
            List <string> featureNames = Exporter.FindRefGeoNames(featureName);

            fillComboBox(box, featureNames);
        }
Exemplo n.º 47
0
 public static void Export(string path, xxParser xxParser, List<xxFrame> meshParents, List<xaParser> xaSubfileList, bool allFrames)
 {
     Exporter exporter = new Exporter(xxParser, meshParents, allFrames);
     exporter.Export(path, xxParser, xaSubfileList);
 }
        public void Write_additional_fields()
        {
            document = new Document(log);
            document.SetInvoice();

            document.ProviderDocumentId               = "24681251-001";
            document.DocumentDate                     = new DateTime(2012, 7, 17);
            document.Invoice.SellerName               = "Протек";
            document.Invoice.BuyerId                  = 278659;
            document.Invoice.BuyerName                = "УК Здоровые Люди г. Санкт-Петербург";
            document.Invoice.RecipientId              = 278654;
            document.Invoice.RecipientName            = "МСЦ г. Санкт-Петербург (Невский 114-116)";
            document.Invoice.DelayOfPaymentInBankDays = -1;
            document.Invoice.DelayOfPaymentInDays     = 90;
            document.Invoice.CommissionFee            = 0;
            document.Invoice.CommissionFeeContractId  = "50-1/2011";

            var line = document.NewLine(new DocumentLine());

            line.Code                   = "16004";
            line.Product                = "КАЛЬЦИЙ Д3 НИКОМЕД ФОРТЕ ТАБ. ЖЕВАТ. №120 С ЛИМОН. ВКУСОМ";
            line.Producer               = "Nycomed Pharma";
            line.Country                = "НОРВЕГИЯ";
            line.Quantity               = 2;
            line.Nds                    = 10;
            line.SupplierCost           = 448.95m;
            line.ProducerCostWithoutNDS = 381.44m;
            line.ExpireInMonths         = 36;
            line.BillOfEntryNumber      = "10130130/120512/0009561";
            line.Certificates           = "POCC NO.ФM08.Д47572/Паспорт (рус)^^";
            line.SerialNumber           = "10749253";
            line.DateOfManufacture      = new DateTime(2011, 12, 1);
            line.Period                 = "01.12.2014";
            line.EAN13                  = 5709932004838;
            line.CertificateAuthority   = "ООО\"ОЦКК\"  Москва^ООО\"ОЦКК\"  Москва";
            line.Amount                 = 897.91m;
            line.NdsAmount              = 81.63m;

            line                  = document.NewLine(new DocumentLine());
            line.Code             = "1314";
            line.Product          = "ЭГЛОНИЛ КАПС. 50МГ №30";
            line.VitallyImportant = true;
            line.Quantity         = 1;
            line.SupplierCost     = 175.13m;
            line.Nds              = 10;
            document.CalculateValues();

            Exporter.Convert(document, log, WaybillFormat.SstLong, new WaybillSettings());
            document.Lines[0].CertificateAuthority = "Test";
            var resultFile = Path.GetFullPath(@"DocumentPath\501\waybills\100_Тестовый поставщик(24681251-001).sst");
            var content    = File.ReadLines(resultFile, Encoding.GetEncoding(1251)).ToArray();

            Assert.That(content[0], Is.EqualTo("- Этим символом могут быть обозначены комментарии к файлу"));
            Assert.That(content[1], Is.EqualTo("- В следующей строке перечислены:"));
            Assert.That(content[2], Is.EqualTo("- Номер документа;Дата документа;Сумма с НДС по документу;Тип накладной;Cумма НДС 10%;Cумма НДС 18%;Тип валюты;Курс валюты;Ставка комиссионного вознаграждения;Номер договора комиссии;Наименование поставщика;Код плательщика;Наименование плательщика;Код получателя;Наименование получателя;Отсрочка платежа в банковских днях;Отсрочка платежа в календарных днях"));
            Assert.That(content[3], Is.EqualTo("[Header]"));
            Assert.That(content[4], Is.EqualTo("24681251-001;17.07.2012;1073.04;ПОСТАВКА;97.55;0;РУБЛЬ;;0;50-1/2011;Протек;278659;УК Здоровые Люди г. Санкт-Петербург;278654;МСЦ г. Санкт-Петербург (Невский 114-116);-1;90;"));
            Assert.That(content[5], Is.EqualTo("- В следующей строке перечислены:"));
            Assert.That(content[6], Is.EqualTo("- Код товара;Наименование товара;Производитель;Страна производителя;Количество;Цена с НДС;Цена производителя без НДС;Цена Протека без НДС;Резерв;Торговая надбавка оптового звена;Заводской срок годности в месяцах;ГТД;Серии сертификатов;Серия производителя;Дата выпуска препарата;Дата истекания срока годности данной серии;Штрих-код производителя;Дата регистрации цены  в реестре;Реестровая цена в рублях;Торговая наценка организации-импортера;Цена комиссионера с НДС;Комиссионное вознаграждение без НДС;НДС с комиссионного вознаграждения;Отпускная цена ЛБО;Стоимость позиции;Кто выдал сертификат;НДС;Сумма НДС;Цена производителя (в валюте, без НДС);Название валюты цены производителя (поля 36)"));
            Assert.That(content[7], Is.EqualTo("[Body]"));
            Assert.That(content[8], Is.EqualTo("16004;КАЛЬЦИЙ Д3 НИКОМЕД ФОРТЕ ТАБ. ЖЕВАТ. №120 С ЛИМОН. ВКУСОМ;Nycomed Pharma;НОРВЕГИЯ;2;448.95;381.44;408.14;448.95;7;36;10130130/120512/0009561;POCC NO.ФM08.Д47572/Паспорт (рус)^^;10749253;01.12.2011;01.12.2014;5709932004838;;;;;;;897.91;ООО\"ОЦКК\"  Москва^ООО\"ОЦКК\"  Москва;10;81.63;;"));
            Assert.That(content[9], Is.StringStarting("1314;ЭГЛОНИЛ КАПС. 50МГ №30 --ЖНиВЛС--;"));
        }
Exemplo n.º 49
0
        /// <summary>
        ///     Inicializa os valores 'padrões' na interface (controles de filtros por exemplo).
        /// </summary>
        private void InicializaValoresDefault()
        {
            cbxPrioridade.Items.Add(new ComboBoxItem("(Todos)"));
            cbxPrioridade.Items.Add(new ComboBoxItem("Baixa", Properties.Resources.p_baixa));
            cbxPrioridade.Items.Add(new ComboBoxItem("Normal (Médio)", Properties.Resources.p_normal));
            cbxPrioridade.Items.Add(new ComboBoxItem("Alta", Properties.Resources.p_alta));
            cbxPrioridade.SelectedIndex = 0;

            cbUsarData.Checked = false;
            dtData.Enabled     = false;
            dtData.DateTime    = DateTime.Now;

            //Remove a ordenação anterior que o usuário pode ter feito (fica salvo internamente no sistema).
            UltraGridOptions udgv_op = new UltraGridOptions(udgv, true, Imagens_NewLookInterface.escolher_editar_coluna_16,
                                                            Imagens_NewLookInterface.ordenar_crescente_16,
                                                            Imagens_NewLookInterface.ordenar_decrescente_16,
                                                            Imagens_NewLookInterface.remover_deletar,
                                                            Imagens_NewLookInterface.agrupamento_16);

            //Objects.DefineColorThemeInterface(this);
            mExporter = new Exporter(udgv, btnExportar, "Tarefas");

            //Fiz isso para resolver um bug do infragistics. Aparentemente, só foi resolvido na versão 10.1.
            //https://www.infragistics.com/community/forums/f/ultimate-ui-for-windows-forms/41560/code-generation-for-property-image-failed

            //Tarefas
            ueb.Groups[0].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.tarefa;
            ueb.Groups[0].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;

            //Ordens
            ueb.Groups[1].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.producao_fabrica;
            ueb.Groups[1].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;

            //Orçamentos
            ueb.Groups[2].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.moedas_cotacao;
            ueb.Groups[2].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;

            //Inventário
            ueb.Groups[3].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.produto_inventario;
            ueb.Groups[3].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;

            //Trabalhos
            ueb.Groups[4].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.trabalhos_pasta;
            ueb.Groups[4].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;
            ueb.Groups[4].Items[2].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;

            //Ferramentas
            ueb.Groups[5].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.ferramentas2;
            ueb.Groups[5].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.ferramentas2;
            ueb.Groups[5].Items[2].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.ferramentas2;

            //Máquinas
            ueb.Groups[6].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.maquinas;
            ueb.Groups[6].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;

            //Vendas
            ueb.Groups[7].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.vendas_pedidos;
            ueb.Groups[7].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;
            ueb.Groups[7].Items[2].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.novo;

            //Relatórios
            ueb.Groups[8].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.relatorios;

            //Outros
            ueb.Groups[9].Items[0].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.xml_azul;
            ueb.Groups[9].Items[1].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.servico_suporte;
            ueb.Groups[9].Items[2].Settings.AppearancesSmall.Appearance.Image = Imagens_NewLookInterface.web;

            customFilterControl1._GroupBox  = ugbFiltros;
            customFilterControl1._Interface = "Tarefas";
            customFilterControl1._Module    = "Tarefas";
        }
Exemplo n.º 50
0
 /// <summary>
 /// Writes the specified stream to a multi-stream \psi store.
 /// </summary>
 /// <typeparam name="TMessage">The type of messages in the stream.</typeparam>
 /// <typeparam name="TSupplementalMetadata">The type of supplemental stream metadata.</typeparam>
 /// <param name="source">The source stream to write.</param>
 /// <param name="supplementalMetadataValue">Supplemental metadata value.</param>
 /// <param name="name">The name of the persisted stream.</param>
 /// <param name="writer">The store writer, created by e.g. <see cref="PsiStore.Create(Pipeline, string, string, bool, KnownSerializers)"/>.</param>
 /// <param name="largeMessages">Indicates whether the stream contains large messages (typically >4k). If true, the messages will be written to the large message file.</param>
 /// <param name="deliveryPolicy">An optional delivery policy.</param>
 /// <returns>The input stream.</returns>
 public static IProducer <TMessage> Write <TMessage, TSupplementalMetadata>(this IProducer <TMessage> source, TSupplementalMetadata supplementalMetadataValue, string name, Exporter writer, bool largeMessages = false, DeliveryPolicy <TMessage> deliveryPolicy = null)
 {
     writer.Write(source.Out, supplementalMetadataValue, name, largeMessages, deliveryPolicy);
     return(source);
 }
Exemplo n.º 51
0
        public IHttpActionResult Export([FromUri] string exportType)
        {
            //var userId = User.Identity.GetUserId();
            //var user = unitOfWork.User.Get(userId);
            var       user     = unitOfWork.User.Get("appu");
            var       userId   = user.Id;
            var       usertype = ConvertIntToString(user.UserType.TypeOfUser);
            DataLinks links;

            try
            {
                string imgPath = string.Empty;

                if (!string.IsNullOrEmpty(user.Files))
                {
                    imgPath = $"{GetUserFolderPath(userId)}/{user.Files}";
                }
                var folderPath = GetUserDocumentFolderPath(userId);
                CreateUserFolder(folderPath);
                //var userPath = $"{folderPath}\\{user.Id}";
                var userPath = $"{folderPath}";
                localHost += $"{userId}/";
                if (exportType.Split('.').Length > 1)
                {
                    Exporter.ExportCsv(userPath, user, usertype, localHost, out Uri dataPath, out Uri ppPath);
                    Exporter.ExportPdf(userPath, user, usertype, localHost, imgPath, out Uri dataPdfPath);
                    links = new DataLinks(dataPath, ppPath, dataPdfPath);
                    string[] stringSeparators = new string[] { $"\\{user.Id}" };
                    //ne moze se zipovati onaj direktorijum koji koristimo promeniti puvanju na bude u istoj ravnini sa appu a ne u appu
                    using (FileStream zipFile = File.Open(userPath.Split(stringSeparators, StringSplitOptions.None)[0] + $"\\{user.Name}.zip", FileMode.Create))
                        using (Archive archive = new Archive())
                        {
                            DirectoryInfo corpus = new DirectoryInfo(folderPath);
                            archive.CreateEntries(corpus);
                            archive.Save(zipFile);
                            return(GetDocuments(userPath, user.Name, "zip"));
                        }
                    //return GetDocuments(userPath, user.Name, "csv");
                    //return GetDocuments(userPath, user.Name, "pdf");
                }
                else if (exportType.Equals("csv"))
                {
                    Exporter.ExportCsv(userPath, user, usertype, localHost, out Uri dataPath, out Uri ppPath);
                    links = new DataLinks(dataPath, ppPath, null);

                    using (FileStream zipFile = File.Open(userPath + $"\\{user.Name}CSV.zip", FileMode.Create))
                    {
                        // Files to be added to archive
                        FileInfo fi1 = new FileInfo($"{userPath}\\{user.Name}{user.Surname}.csv");
                        FileInfo fi2 = new FileInfo($"{userPath}\\{user.Name}{user.Surname}PayPal.csv");

                        using (var archive = new Archive())
                        {
                            archive.CreateEntry($"{userPath}\\{user.Name}{user.Surname}.csv", fi1);
                            archive.CreateEntry($"{userPath}\\{user.Name}{user.Surname}PayPal.csv", fi2);
                            archive.Save(zipFile, new ArchiveSaveOptions()
                            {
                                Encoding = Encoding.UTF8
                            });
                        }
                    }
                    return(GetDocuments(userPath, $"{user.Name}CSV", "zip"));
                }
                else if (exportType.Equals("pdf"))
                {
                    Exporter.ExportPdf(userPath, user, usertype, localHost, imgPath, out Uri dataPdfPath);
                    links = new DataLinks(null, null, dataPdfPath);
                    return(GetDocuments(userPath, user.Name, "pdf"));
                }
                else
                {
                    links = new DataLinks(null, null, null);
                }


                return(Ok(links));
            }
            catch (Exception ex)
            {
                //log
            }
            return(Ok(HttpStatusCode.NoContent));
        }
Exemplo n.º 52
0
 /// <summary>
 /// Writes the envelopes for the specified stream to a multi-stream \psi store.
 /// </summary>
 /// <typeparam name="TIn">The type of messages in the stream.</typeparam>
 /// <param name="source">The source stream for which to write envelopes.</param>
 /// <param name="name">The name of the persisted stream.</param>
 /// <param name="writer">The store writer, created by e.g. <see cref="PsiStore.Create(Pipeline, string, string, bool, KnownSerializers)"/>.</param>
 /// <param name="deliveryPolicy">An optional delivery policy.</param>
 /// <returns>The input stream.</returns>
 public static IProducer <TIn> WriteEnvelopes <TIn>(this IProducer <TIn> source, string name, Exporter writer, DeliveryPolicy <TIn> deliveryPolicy = null)
 {
     writer.WriteEnvelopes(source.Out, name, deliveryPolicy);
     return(source);
 }
Exemplo n.º 53
0
        public void ProcessItem()
        {
            if (config.Dest == null)
            {
                throw new ConfigurationException("Dest attribute must be set");
            }

            var directory = config.BaseDirectory;

            var dest     = Path.Combine(directory, config.Dest);
            var contdest = Path.ChangeExtension(dest, ".contradiction" + Path.GetExtension(dest));

            // TODO: Neat way to do this without mutability?
            factory.TilesByName = new Dictionary <string, Tile>();

            SampleSet sampleSet;

            if (config.SrcType == SrcType.Sample)
            {
                sampleSet           = LoadSample();
                factory.TilesByName = sampleSet.TilesByName ?? factory.TilesByName;
            }
            else
            {
                sampleSet = LoadFileSet();
            }
            var directions = sampleSet.Directions;

            var topology = factory.GetOutputTopology(directions);

            var tileRotation = factory.GetTileRotation(config.RotationTreatment, topology);

            var model = factory.GetModel(directions, sampleSet, tileRotation);

            var constraints = factory.GetConstraints(directions, tileRotation);

            System.Console.WriteLine($"Processing {dest}");
            var propagator = new TilePropagator(model, topology, config.Backtrack, constraints: constraints.ToArray());

            Resolution status = propagator.Status;

            for (var retry = 0; retry < 5; retry++)
            {
                if (retry != 0)
                {
                    status = propagator.Clear();
                }
                if (status == Resolution.Contradiction)
                {
                    System.Console.WriteLine($"Found contradiction in initial conditions, retrying");
                    continue;
                }
                if (config.Animate)
                {
                    status = RunAnimate(model, propagator, dest, sampleSet.ExportOptions);
                }
                else
                {
                    status = Run(propagator);
                }
                if (status == Resolution.Contradiction)
                {
                    System.Console.WriteLine($"Found contradiction, retrying");
                    continue;
                }
                break;
            }
            Directory.CreateDirectory(Path.GetDirectoryName(dest));
            if (status == Resolution.Decided)
            {
                System.Console.WriteLine($"Writing {dest}");
                Exporter.Export(model, propagator, dest, config, sampleSet.ExportOptions);
                File.Delete(contdest);
            }
            else
            {
                System.Console.WriteLine($"Writing {contdest}");
                Exporter.Export(model, propagator, contdest, config, sampleSet.ExportOptions);
                File.Delete(dest);
            }
        }
Exemplo n.º 54
0
        private void exportToHtml_Click(object sender, RoutedEventArgs e)
        {
            Exporter exporter = new Exporter(workArea);
            Microsoft.Win32.SaveFileDialog fileDialog = new Microsoft.Win32.SaveFileDialog();

            fileDialog.Filter = "CHe HTML File|*.html";
            bool? result = fileDialog.ShowDialog();

            if (result.HasValue)
            {
                switch (Global.Template)
                {
                    case Data.Resources.TemplateType.MuseumGuide:
                        exporter.ExportMuseumGuideHTML(
                            Path.GetFileNameWithoutExtension(fileDialog.SafeFileName),
                            Path.GetDirectoryName(fileDialog.FileName));
                        break;
                    default:
                        break;
                }

                MessageBox.Show("Export operation successfully completed !", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
Exemplo n.º 55
0
        //Fills the property boxes on the joint properties page
        public void FillJointPropertyBoxes(Joint joint)
        {
            FillBlank(jointBoxes);
            AutoUpdatingForm = true;
            if (joint != null) //For the base_link or if none is selected
            {
                // Limits are required for prismatic and revolute joints
                LimitRequiredLabel.Visible = (joint.Type == "prismatic" || joint.Type == "revolute");

                // Axis values are required, except for a fixed joint
                AxisRequiredLabel.Visible = (joint.Type != "fixed");

                joint.FillBoxes(textBoxJointName, comboBoxJointType);
                joint.Parent.FillBoxes(labelParent);
                joint.Child.FillBoxes(labelChild);

                //G5: Maximum decimal places to use (not counting exponential notation) is 5

                joint.Origin.FillBoxes(textBoxJointX,
                                       textBoxJointY,
                                       textBoxJointZ,
                                       textBoxJointRoll,
                                       textBoxJointPitch,
                                       textBoxJointYaw,
                                       "G5");

                if (joint.Type != "fixed")
                {
                    joint.Axis.FillBoxes(textBoxAxisX, textBoxAxisY, textBoxAxisZ, "G5");
                }

                if (joint.Limit != null && joint.Type != "fixed")
                {
                    joint.Limit.FillBoxes(textBoxLimitLower,
                                          textBoxLimitUpper,
                                          textBoxLimitEffort,
                                          textBoxLimitVelocity,
                                          "G5");
                }

                if (joint.Calibration != null)
                {
                    joint.Calibration.FillBoxes(textBoxCalibrationRising,
                                                textBoxCalibrationFalling,
                                                "G5");
                }

                if (joint.Dynamics != null)
                {
                    joint.Dynamics.FillBoxes(textBoxDamping,
                                             textBoxFriction,
                                             "G5");
                }

                if (joint.Safety != null)
                {
                    joint.Safety.FillBoxes(textBoxSoftLower,
                                           textBoxSoftUpper,
                                           textBoxKPosition,
                                           textBoxKVelocity,
                                           "G5");
                }
            }

            if (joint != null && (joint.Type == "revolute" || joint.Type == "continuous"))
            {
                labelLowerLimit.Text = "lower (rad)";
                labelLimitUpper.Text = "upper (rad)";
                labelEffort.Text     = "effort (N-m)";
                labelVelocity.Text   = "velocity (rad/s)";
                labelFriction.Text   = "friction (N-m)";
                labelDamping.Text    = "damping (N-m-s/rad)";
                labelSoftLower.Text  = "soft lower limit (rad)";
                labelSoftUpper.Text  = "soft upper limit (rad)";
                labelKPosition.Text  = "k position";
                labelKVelocity.Text  = "k velocity";
            }
            else if (joint != null && joint.Type == "prismatic")
            {
                labelLowerLimit.Text = "lower (m)";
                labelLimitUpper.Text = "upper (m)";
                labelEffort.Text     = "effort (N)";
                labelVelocity.Text   = "velocity (m/s)";
                labelFriction.Text   = "friction (N)";
                labelDamping.Text    = "damping (N-s/m)";
                labelSoftLower.Text  = "soft lower limit (m)";
                labelSoftUpper.Text  = "soft upper limit (m)";
                labelKPosition.Text  = "k position";
                labelKVelocity.Text  = "k velocity";
            }
            else
            {
                labelLowerLimit.Text = "lower";
                labelLimitUpper.Text = "upper";
                labelEffort.Text     = "effort";
                labelVelocity.Text   = "velocity";
                labelFriction.Text   = "friction";
                labelDamping.Text    = "damping";
                labelSoftLower.Text  = "soft lower limit";
                labelSoftUpper.Text  = "soft upper limit";
                labelKPosition.Text  = "k position";
                labelKVelocity.Text  = "k velocity";
            }
            comboBoxOrigin.Items.Clear();
            List <string> originNames = Exporter.GetRefCoordinateSystems();

            comboBoxOrigin.Items.AddRange(originNames.ToArray());
            comboBoxAxis.Items.Clear();
            List <string> axesNames = Exporter.GetRefAxes();

            comboBoxAxis.Items.AddRange(axesNames.ToArray());
            comboBoxOrigin.SelectedIndex =
                comboBoxOrigin.FindStringExact(joint.CoordinateSystemName);

            // Updating Mimic Element Fields
            List <string> jointNames = Exporter.GetJointNames();

            // We'll be setting this automatically, so unsubscribe callback
            MimicCheckBox.CheckedChanged -= MimicCheckBoxCheckedChanged;

            MimicJointComboBox.Items.Clear();
            MimicJointComboBox.Items.AddRange(jointNames.ToArray());
            if (joint.Mimic != null && joint.Mimic.AreRequiredFieldsSatisfied())
            {
                ShowMimicControls(true);
                MimicCheckBox.Checked            = true;
                MimicJointComboBox.SelectedIndex =
                    MimicJointComboBox.FindStringExact(joint.Mimic.JointName);
                joint.Mimic.FillBoxes(textBoxMimicMultiplier, textBoxMimicOffset);
            }
            else
            {
                ShowMimicControls(false);
                MimicCheckBox.Checked = false;
            }
            // Resubscribe to callback
            MimicCheckBox.CheckedChanged += MimicCheckBoxCheckedChanged;

            if (!String.IsNullOrWhiteSpace(joint.AxisName))
            {
                comboBoxAxis.SelectedIndex = comboBoxAxis.FindStringExact(joint.AxisName);
            }
            AutoUpdatingForm = false;
        }
Exemplo n.º 56
0
 public static void Export(string dest, xxParser parser, xxFrame[] meshParents, List<xaParser> xaSubfiles, int ticksPerSecond, int keyframeLength)
 {
     HashSet<string> meshNames = new HashSet<string>();
     foreach (xxFrame frame in meshParents)
     {
         meshNames.Add(frame.Name);
     }
     Exporter exporter = new Exporter(dest, parser, meshNames, xaSubfiles, ticksPerSecond, keyframeLength);
 }
Exemplo n.º 57
0
 public AssetType ToExportType(ClassIDType unityType)
 {
     return(Exporter.ToExportType(unityType));
 }
Exemplo n.º 58
0
 public string GetExportID(Object @object)
 {
     return(Exporter.GetExportID(@object));
 }
        public void TestSetUp()
        {
            //bind to a license - this is required so that we can mock a server object helper
            RuntimeManager.BindLicense(ProductCode.Server);
            if (!RuntimeManager.Bind(ProductCode.Server))
            {
                throw new ApplicationException("Cannot bind to ArcGIS Server License");

            }

            //create an instance of the extension & initialise it using the mock server object helper
            exporter = new Exporter();
            exporter.Init(MockServerObjectCreator.CreateMockServerObjectHelper(@"C:\Git\arcgis-exporter-extension\GPX.Server.Extension.Tests\testdata\California.mxd"));
            IPropertySet propSet = new PropertySet();
            exporter.Construct(propSet);
        }