示例#1
0
        public void EksportujDoPliku(string sciezka)
        {
            var myExport = new CsvExport(",", false);

            for (int i = 0; i < punkty.Count; i++)
            {
                myExport.AddRow();
                myExport["x"] = punkty[i][0];
                myExport["y"] = punkty[i][1];
                if (klasyWej[i][0] >= 0.0)
                {
                    myExport["cls"] = Convert.ToInt32(klasyWej[i][0] * 2 + 1.0);
                }
                if (klasyWy[i] <= 0.33)
                {
                    myExport["res"] = 1;
                }
                else if (klasyWy[i] <= 0.66)
                {
                    myExport["res"] = 2;
                }
                else
                {
                    myExport["res"] = 3;
                }
            }

            myExport.ExportToFile(sciezka);
            Console.WriteLine();
            Console.WriteLine("Zapisano wyniki do w pliku {0}", sciezka);
            Console.WriteLine();
        }
示例#2
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            ObservableCollection<RiddleItem> riddleObservable = new ObservableCollection<RiddleItem>();
            //CsvExport<RiddleItem> exporter = new CsvExport<RiddleItem>(riddleObservable);
            //exporter.ExportToFile("test.csv");
            busyIndicator.IsActive = true;
            busyIndicator.Visibility = Visibility.Visible;

            //XDocument doc = await RiddleManager.GetRiddleRssContents();
            //XDocument doc = await RiddleManager.LoadTestRssXml();
            //if (doc != null)
            {
                //List<RiddleItem> riddles = await RiddleManager.ParseRiddles(doc);
                List<RiddleItem> riddles = await RiddleManager.GetFeedAsync();
                Debug.Assert(riddles.Count > 0);
                DefaultViewModel["Items"] = riddles;

                bool success = await RiddleManager.FetchAnswers(riddles);

                foreach (var riddle in riddles)
                    riddleObservable.Add(riddle);
                // Show the riddles without answers at first to give better user experience
                DefaultViewModel["Items"] = riddleObservable;

                //RaisePropertyChanged("DefaultViewModel");
            }

            busyIndicator.IsActive = false;
            busyIndicator.Visibility = Visibility.Collapsed;

            CsvExport<RiddleItem> exporter = new CsvExport<RiddleItem>(riddleObservable);
            string outputFile = GetOutputFileName();
            exporter.ExportToFile(outputFile);
        }
示例#3
0
        public void OperandTypeConstructor()
        {
            var dutchBelgium = new Locales(this.Session).DutchBelgium;

            new C1Builder(this.Session).WithC1AllorsString("c1A").WithC1AllorsDecimal(10.5M).Build();
            new C1Builder(this.Session).WithC1AllorsString("c1B").WithC1AllorsDecimal(11.5M).Build();

            this.Session.Derive(true);

            var csvFile = new CsvExport("Test");

            csvFile.Columns.Add(new CsvExportPath(M.C1.C1AllorsString));
            csvFile.Columns.Add(new CsvExportPath(M.C1.C1AllorsDecimal));

            var aclMock = new Mock <IAccessControlList>();

            aclMock.Setup(acl => acl.CanRead(It.IsAny <PropertyType>())).Returns(true);
            var acls = new AccessControlListCache(null, (allorsObject, user) => aclMock.Object);

            var extent = this.Session.Extent(M.C1.ObjectType).AddSort(M.C1.C1AllorsString);
            var csv    = csvFile.Write(extent, dutchBelgium, acls);

            Assert.AreEqual(
                @"""C1AllorsString"";""C1AllorsDecimal""
""c1A"";""10,5""
""c1B"";""11,5""".Replace("\r\n", "\n"),
                csv.Replace("\r\n", "\n"));
        }
示例#4
0
        public void ProcessRequest(HttpContext httpContext)
        {
            Assert.ArgumentNotNull(httpContext, "httpContext");
            string action = httpContext.Request.Params["action"];

            if (action == "AllEmailCampaigns")
            {
                RecentlyDispatchedRepository        emailInfoRepository = new RecentlyDispatchedRepository(httpContext.Request.Params["managerroot"], httpContext.Request.Params["dbname"]);
                IEnumerable <DispatchedMessageInfo> dataItems           = emailInfoRepository.GetAllRecentlyDispatched("fast://{messages}//*[@@templatename='Message Folder' or @@templatename='Folder']/*[@@templatename!='Folder' and @@templatename!='Message Folder' and (@State='Sent' or @State='Sending')]");

                string detailListId = "{5A5F77F9-FC7F-45D5-B6EB-89804A70C03A}"; // an ID of the item to format csv

                string export = CsvExport.ExportDetailsListToCsv <DispatchedMessageInfo>(dataItems, detailListId);

                string filename = "AllEmailCampaigns_" + DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ");
                try
                {
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.ContentType = "text/csv";
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".csv");
                    HttpContext.Current.Response.Write(export);
                }
                catch (Exception exception)
                {
                    Log.Error(exception.Message, exception, this);
                }
                return;
            }
        }
        public void Constructor()
        {
            var dutchBelgium = new Locales(this.Session).DutchBelgium;

            new C1Builder(this.Session).WithC1AllorsString("c1A").WithC1C2One2One(new C2Builder(this.Session).WithC2AllorsString("c2A").Build()).Build();
            new C1Builder(this.Session).WithC1AllorsString("c1B").WithC1C2One2One(new C2Builder(this.Session).WithC2AllorsString("c2B").Build()).Build();

            this.Session.Derive(true);

            var aclMock = new Mock <IAccessControlList>();

            aclMock.Setup(acl => acl.CanRead(It.IsAny <PropertyType>())).Returns(true);
            var acls = new AccessControlListCache(null, (allorsObject, user) => aclMock.Object);

            var export = new CsvExport("Test");

            export.Columns.Add(new CsvExportPath(M.C1.C1AllorsString));
            export.Columns.Add(new CsvExportFunction <C1>("Function", (c1, aclFactory) => CsvExport.Escape("Hello " + c1.C1AllorsString)));

            var extent = this.Session.Extent(M.C1.ObjectType).AddSort(M.C1.C1AllorsString);
            var csv    = export.Write(extent, dutchBelgium, acls);

            Assert.AreEqual(
                @"""C1AllorsString"";""Function""
""c1A"";""Hello c1A""
""c1B"";""Hello c1B""".Replace("\r\n", "\n"),
                csv.Replace("\r\n", "\n"));
        }
示例#6
0
        public void Locale()
        {
            var englishGreatBritain = new Locales(this.Session).EnglishGreatBritain;
            var dutchBelgium        = new Locales(this.Session).DutchBelgium;

            new C1Builder(this.Session).WithC1AllorsString("c1A").WithC1AllorsDecimal(10.5M).Build();
            new C1Builder(this.Session).WithC1AllorsString("c1B").WithC1AllorsDecimal(11.5M).Build();

            this.Session.Derive(true);

            var column1 = new CsvExportPath(M.C1.C1AllorsString);
            var column2 = new CsvExportPath(M.C1.C1AllorsDecimal);

            var export = new CsvExport("Test");

            export.Columns.Add(column1);
            export.Columns.Add(column2);

            var extent = this.Session.Extent(M.C1.ObjectType).AddSort(M.C1.C1AllorsString);

            var user = new Users(this.Session).GetCurrentUser();
            var acls = new AccessControlListCache(user);

            var csvEn = export.Write(extent, englishGreatBritain, acls);
            var csvNl = export.Write(extent, dutchBelgium, acls);

            Assert.AreNotEqual(csvEn, csvNl);
        }
        public ActionResult exportFicheirosToCsv(UploadIsentosViewModel viewModel, string sort, string direction, string tabNr)
        {
            viewModel.PageSize = 0;
            if (tabNr == null || tabNr == "")
                tabNr = "1";

            viewModel.SetParameters(int.Parse(tabNr), 1, sort, direction, Request.Params);

            UploadIsentosViewModel result = getFicheiros(viewModel);

            List<FicheiroToCsv> ficheirosCsv = new List<FicheiroToCsv>();
            foreach (FicheiroIsentos file in result.ficheiros)
                ficheirosCsv.Add(new FicheiroToCsv
                {
                    entidade = file.entidade.nome,
                    nome = file.nomeFicheiro,
                    estado = file.estado.descricao.ToString(),
                    dataUpload = file.dataUpload.ToString(),
                    dataAlteracao = file.dataAlteracao.ToString(),
                    username = file.userName
                });

            CsvExport<FicheiroToCsv> csv = new CsvExport<FicheiroToCsv>(ficheirosCsv);

            byte[] fileBytes = csv.ExportToBytes();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "FicheirosIsentos_" + DateTime.Now.ToShortDateString() + ".csv");
        }
        private void btnGenerateCsv_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            using (var uow = DIContainer.CreateUnitOfWork())
            {
                var      repo = DIContainer.CreateRepository <IDriverWorkingStateRepository>(uow);
                DateTime?mostRecentDateStamp;
                var      data = repo.GetDurations(dteStartDate.SelectedDate.Value.Date, dteEndDate.SelectedDate.Value.Date, null, out mostRecentDateStamp);

                CsvExport.Export(
                    data,
                    "DriverTime.csv",
                    new CsvExport.PropertyMappings <Orchestrator.Repositories.DTOs.DriverDayDurations>
                {
                    { "Depot", i => i.DepotName },
                    { "Driver", i => i.DriverName },
                    { "Day", i => i.Day.ToShortDateString() },
                    { "Break", i => RoundSecondsToMinutes(i.RestDuration) },
                    { "POA", i => RoundSecondsToMinutes(i.AvailabilityDuration) },
                    { "Other Work", i => RoundSecondsToMinutes(i.WorkDuration) },
                    { "Drive", i => RoundSecondsToMinutes(i.DriveDuration) },
                });
            }
        }
示例#9
0
        public string ConsultaToCSV(IPrincipal user, string indexName, IList <string> selectFilter = null, IEnumerable <Tuple <string, string, string> > filterFilter = null, long numberEntries = 1000, bool allEntries = false)
        {
            try
            {
                int from = 0;
                int size = 10000;

                var tempDownloadFolderUser = Path.Combine(Configuration.DefaultTempFolder, user.Identity.Name, "downloadTemp");
                Directory.CreateDirectory(tempDownloadFolderUser);

                var fileName = Path.Combine(tempDownloadFolderUser, $"{indexName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv");

                if (allEntries)
                {
                    numberEntries = _unitOfWork.TotalDocuments(indexName: indexName);
                }

                do
                {
                    using (var export = new CsvExport())
                    {
                        var result = this._unitOfWork.MatchAll(indexName: indexName, selectFilter: selectFilter, filterFilter: filterFilter, from: from, size: size);

                        foreach (var item in result)
                        {
                            export.AddRow();

                            foreach (var key in item.Keys)
                            {
                                export[key] = item[key];
                            }
                        }

                        result.Clear();

                        if (from == 0)
                        {
                            export.ExportToFile(fileName, includeHeader: true);
                        }
                        else
                        {
                            export.AddLinesToFile(fileName);
                        }
                    }

                    from += size;

                    if ((from + size) >= numberEntries)
                    {
                        size = (int)(numberEntries - from);
                    }
                }while (from < numberEntries);

                return(fileName);
            }
            catch (Exception erro)
            {
                throw erro;
            }
        }
示例#10
0
        public HttpResponseMessage ExportUsersToExcel()
        {
            var users   = userService.Find().Where(i => !i.IsDeleted).ToList();
            var userCsv = new CsvExport();

            foreach (var user in users)
            {
                userCsv.AddRow();
                userCsv["Id"]            = user.Id;
                userCsv["FirstName"]     = user.FirstName;
                userCsv["LastName"]      = user.LastName;
                userCsv["Email"]         = user.Email;
                userCsv["LastLoginDate"] = user.LastLoginDateUtc.HasValue ? user.LastLoginDateUtc.Value.ToLocalTime().ToString("MM/dd/yyy hh:mm") : "";
            }

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(userCsv.ExportToBytes())
            };

            result.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Users_" + DateTime.UtcNow.ToLocalTime().ToString("MMddyyyy_hhmm") + ".xls"
            };
            return(result);
        }
        public FileContentResult Reflection(string model)
        {
            List <WidgetBeta>  listBetas  = null;
            List <WidgetGamma> listGammas = null;
            List <WidgetPrime> listPrimes = null;

            WidgetPrime singleSource = null;
            WidgetBeta  singleTarget = null;

            listBetas  = PopulateBeta();
            listGammas = PopulateGamma();

            listPrimes = PopulatePrime();// new List<WidgetPrime>();

            for (int i = 0; i < listPrimes.Count; i++)
            {
                singleSource = listPrimes[i];
                singleTarget = new WidgetBeta();

                singleTarget = (WidgetBeta)TransferValues(singleSource, singleTarget);

                listBetas.Add(singleTarget);
            }


            CsvExport <WidgetBeta> csv = new CsvExport <WidgetBeta>(listBetas);

            return(File(new System.Text.UTF8Encoding().GetBytes(csv.Export()), "text/csv", "test.csv"));

            // return RedirectToAction("Reflection");
        }
        public FileContentResult DownloadCSV()
        {
            List <ApplicationUser> users = userManager.GetUsers();
            var myExport = new CsvExport();

            foreach (ApplicationUser au in users)
            {
                myExport.AddRow();
                myExport["UserName"]          = au.UserName;
                myExport["Password"]          = au.PasswordHash;
                myExport["LastActivity"]      = au.LastActivityDate;
                myExport["AccessFailedCount"] = au.AccessFailedCount;
                myExport["Email"]             = au.Email;
                myExport["EmailConfirmed"]    = au.EmailConfirmed;
                myExport["Facebook"]          = au.Facebook;
                myExport["Google"]            = au.Google;
                myExport["Lockoutenabled"]    = au.LockoutEnabled;
                myExport["Lockout einddatum"] = au.LockoutEndDateUtc;
                myExport["telefoon"]          = au.PhoneNumber;
                myExport["2 factor"]          = au.TwoFactorEnabled;
                StringBuilder sb = new StringBuilder();
                foreach (Item i in au.FollowedItems)
                {
                    sb.Append(i.Name);
                    sb.Append("; ");
                }
                myExport["gevolgde paginas:"] = sb.ToString();
            }

            return(File(myExport.ExportToBytes(), "text/csv", "users.csv"));
        }
        private void btnTonnesToCustomer_Click(object sender, EventArgs e)
        {
            DateTime startDate = dteTTCStartDate.SelectedDate.Value.Date;
            DateTime endDate   = dteTTCEndDate.SelectedDate.Value.Date.Add(new TimeSpan(23, 59, 59));

            IEnumerable <int> businessTypeIDs = chkTTCBusinessType.AllBusinessTypesSelected ? null : chkTTCBusinessType.SelectedBusinessTypeIDs;

            Facade.IKPI facKPI   = new Facade.KPI();
            DataSet     dsSource = facKPI.TonnesToCustomer(businessTypeIDs, startDate, endDate);

            CsvExport.Export(
                dsSource.Tables[0],
                "TonnesToCustomer.csv",
                new CsvExport.ColumnMappings
            {
                { "Customer", "Customer" },
                { "TotalTonnes", "Total Tonnes" },
                { "Loads", "Loads" },
                { "Drops", "Drops" },
                { "AverageLoadSize", "Average Load Size" },
                { "AverageDropSize", "Average Drop Size" },
                { "RouteRate", "Route Rate" },
                { "AdditionalCollsCost", "Additional Collections Cost" },
                { "AdditionalDropsCost", "Additional Drops Cost" },
                { "FuelSurcharge", "Fuel Surcharge" },
                { "Demurrage", "Demurrage" },
                { "BankHoliday", "Bank Holiday" },
                { "TotalCost", "Total Cost" },
                { "TotalCostPerTonne", "Total Cost Per Tonne" },
            });
        }
示例#14
0
        public byte[] GetPatientsExcel(IEnumerable <PatientDTO> patients)
        {
            HashSet <string> symptomNames = new HashSet <string>();

            foreach (var patient in patients)
            {
                if (patient.Diagnose != null && patient.Diagnose.Symptoms != null)
                {
                    symptomNames.UnionWith(new HashSet <string>(patient.Diagnose.Symptoms.Keys));
                }
            }
            var myExport = new CsvExport(",", false);

            foreach (var patient in patients)
            {
                myExport.AddRow();
                myExport["Id"]   = patient.Id;
                myExport["Name"] = patient.Name;
                if (patient.Diagnose != null && patient.Diagnose.Symptoms != null)
                {
                    foreach (var symptom in symptomNames)
                    {
                        if (patient.Diagnose.Symptoms.ContainsKey(symptom))
                        {
                            if (patient.Diagnose.Symptoms[symptom] != null)
                            {
                                myExport[symptom] = patient.Diagnose.Symptoms[symptom].ToString();
                            }
                        }
                    }
                }
            }
            return(myExport.ExportToBytes());
        }
示例#15
0
        public static string MakeCSV(List <CapturePacket> packets)
        {
            var csvExport = new CsvExport();


            foreach (CapturePacket packet in packets)
            {
                csvExport.AddRow();
                csvExport["Time"] = packet.Date; // + "." + l.Time.Millisecond;
                csvExport["ms"]   = packet.Date.Millisecond;


                csvExport["Name"] = packet.Name;

                if (packet.ParsedData != null)
                {
                    csvExport["Data"] = Functions.MakeCommentString(packet.ParsedData.GetDataDictionary());
                }


                csvExport["Raw"] = BitConverter.ToString(packet.GetRawData());
            }

            string export = csvExport.Export();

            return(export);
        }
示例#16
0
 private void metroButton1_Click(object sender, EventArgs e)
 {
     try
     {
         CsvExport myExport = new CsvExport();
         foreach (DataGridViewRow row in metroGrid1.Rows)
         {
             myExport.AddRow();
             myExport["Store"]             = row.Cells["DG1_StoreName"].Value;
             myExport["ASIN / ISBN"]       = row.Cells["DG1_ASIN_ISBN"].Value;
             myExport["Name"]              = row.Cells["DG1_Name"].Value;
             myExport["Preis: Neu"]        = row.Cells["DG1_PreisNeu"].Value;
             myExport["Preis: Wie Neu"]    = row.Cells["DG1_PreisWieNeu"].Value;
             myExport["Preis: Sehr Gut"]   = row.Cells["DG1_PreisSehrGut"].Value;
             myExport["Preis: Gut"]        = row.Cells["DG1_PreisGut"].Value;
             myExport["Preis: Akzeptabel"] = row.Cells["DG1_PreisAkzeptabel"].Value;
             myExport["URL"]           = row.Cells["DG1_URL"].Value;
             myExport["Letzter Check"] = row.Cells["DG1_LetzterCheck"].Value;
         }
         string filename = "Export_" + DateTime.Now.ToString("dd.MM.yyyy_HH.mm.ss") + "_" + (metroComboBox2.SelectedIndex == -1 ? "ALLE" : metroComboBox2.Text) + ".csv";
         myExport.ExportToFile(Path.Combine(FoldersFilesAndPaths.Export, filename));
         MetroMessageBox.Show(this, "Du findest die Datei: " + filename + Environment.NewLine + "in deinem Export Ordner.", "Excel Export erfolgreich", MessageBoxButtons.OK, MessageBoxIcon.Question);
     }
     catch (Exception ex)
     {
         Logger.Write("Escel Export Fehlgeschlagen - Grund: " + ex.Message);
         MetroMessageBox.Show(this, "Bitte versuche es erneut oder Kontaktiere den Entwickler." + Environment.NewLine + Environment.NewLine + @"Fehlercode: " + ex.Message, "Excel Export Fehlgeschlagen", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
示例#17
0
        public bool DownloadCSV(BONoticeSearchCriteria criteria)
        {
            var csvExport = new CsvExport();

            try
            {
                var noticeList = criteria.NoticeList;
                // noticeList = ReduceDuplicates(noticeList);

                foreach (var Item in noticeList)
                {
                    csvExport.AddRow();
                    csvExport["Subject"]     = Item.Subject;
                    csvExport["Posted Date"] = Item.PostingDateTime;
                }

                Response.Clear();
                MemoryStream Ms = new MemoryStream(csvExport.ExportToBytes());
                Response.ContentType = "application/CSV";
                Response.AddHeader("content-disposition", "attachment;filename=" + "NoticesDataTable.csv");
                Response.Buffer = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Ms.WriteTo(Response.OutputStream);
                Response.End();
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
示例#18
0
        public FileResult Export(IngredientGroupFilter filter)
        {
            var responseIngredientGroup = _ingredientGroupService.Filter(filter);

            var csv = new CsvExport();

            csv.ConcatRow(0, "COLOR,GRUPO DE INGREDIENTE,INGREDIENTES,ESTADO");
            foreach (var ingredientGroup in responseIngredientGroup.IngredientGroups)
            {
                var responseIngredient = _ingredientService.Filter(new IngredientFilter {
                    IngredientGroupId = ingredientGroup.Id, OnlyStatusActivated = true
                });
                var rowIngredientGroup = String.Format("{0},{1},,{2}", ingredientGroup.Color, ingredientGroup.Name, ingredientGroup.Status);
                csv.ConcatRow(0, rowIngredientGroup);
                foreach (var ingredient in responseIngredient.Ingredients)
                {
                    var rowIngredient = String.Format(",,{0},{1}", ingredient.Name, ingredient.Status);
                    csv.ConcatRow(0, rowIngredient);
                }
            }

            var stream = csv.RetrieveFile();

            return(new StreamFactory().Csv(stream, "Grupo de ingredientes"));
        }
示例#19
0
        private void btnDownloadTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                using (var folderBrowserDialog = new FolderBrowserDialog
                {
                    Description = @"Select folder to save the template",
                    ShowNewFolderButton = true
                })
                {
                    var data = ResultService.DownloadReportResultSingleCourse();
                    var csv  = new CsvExport <ResultSingleCourseTemplateDownloadModel>(Enumerable.Range(0, 25).ToList(), data.ToList());

                    if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                    {
                        string path = Path.Combine(folderBrowserDialog.SelectedPath, "ResultSingleCourse.csv");
                        csv.ExportToFile(path);
                        var lblFolderName = $@"Your Single Course Result template saved successfully to :{Environment.NewLine}{folderBrowserDialog.SelectedPath}{Environment.NewLine}{Environment.NewLine}File: Name: ResultSingleCourse.csv";
                        this.ShowMessageBox(lblFolderName, @"Template Path", MessageBoxButtons.OK, RadMessageIcon.Info);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error Message: " + ex.Message, ex);
                this.ShowMessageBox($@"Message: {ex.Message}{Environment.NewLine}Stack Message: {ex.StackTrace}", $@"Error Message from {typeof(AllStudentCourseResult)}");
            }
        }
示例#20
0
        private void btnDownloadTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                lblFolderName.Text = "";
                using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()
                {
                    Description = "Select folder to save the template",
                    ShowNewFolderButton = true,
                })
                {
                    var csv = new CsvExport <CourseTemplateDownloadModel>(new List <int>()
                    {
                        0, 1, 2
                    },
                                                                          new List <CourseTemplateDownloadModel>());

                    if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                    {
                        string path = Path.Combine(folderBrowserDialog.SelectedPath, "course.csv");
                        csv.ExportToFile(path);
                        lblFolderName.Text = $@"Course template saved to :{Environment.NewLine}{folderBrowserDialog.SelectedPath}";
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error Message: " + ex.Message.ToString(), ex);
                MessageBox.Show($@"Message: {ex.Message}{Environment.NewLine}Stack Message: {ex.StackTrace}", $@"Error Message from {typeof(ListForm)}");
            }
        }
示例#21
0
        public IActionResult Export(string exportType)
        {
            switch (exportType)
            {
            case "XML":
                var ms = new MemoryStream();
                this.applicationState.CurrentDataResult.VersionedExportXml.Save(ms);
                ms.Position = 0;

                this.Response.Headers.Add("Content-Disposition", "attachment; filename=result.xml");
                return(new FileStreamResult(ms, "text/xml"));

            case "CSV_LOG_ITEMS":
                this.Response.Headers.Add("Content-Disposition", "attachment; filename=export.csv");
                return(new FileContentResult(CsvExport.ExportLog(this.applicationState.CurrentDataResult?.Model?.LogEntries), "text/csv"));

            default:
                var selectedOvl = this.applicationState.CurrentDataResult.OriginalValueLists.FirstOrDefault(
                    ovl => ovl.GetOriginalValueListIdent() == exportType);

                if (selectedOvl != null)
                {
                    this.Response.Headers.Add("Content-Disposition", "attachment; filename=export.csv");
                    return(new FileContentResult(CsvExport.ExportOriginalValueList(selectedOvl), "text/csv"));
                }

                break;
            }

            return(this.NotFound());
        }
示例#22
0
        static void Main(string[] args)
        {
            CsvExport csv = new CsvExport();
            int       n = N;
            double    xi1, xi2;

            xi_finder(n, out xi1, out xi2);
            Console.WriteLine($" xi1 = {xi1}");
            Console.WriteLine($" xi2 = {xi2}");
            double t_i, x_i;
            double h = 1d / n;

            double delta;
            double z = 0;

            for (int i = 0; i <= n; i++)
            {
                t_i = i * h;
                x_i = t_i;
                csv.AddRow();
                csv["x"]    = x_i;
                csv["B(t)"] = bez3_point(t_i, fun(0), xi1, xi2, fun(1));
                csv["f(x)"] = fun(x_i);
                delta       = Math.Abs(bez3_point(t_i, fun(0), xi1, xi2, fun(1)) - fun(x_i));
                if (delta > z)
                {
                    z = delta;
                }
            }
            Console.WriteLine($" z = {z}");
            csv.ExportToFile("data.csv");
            Console.WriteLine($"int = {integrate( xi1, xi2, 0, 1 )}");
            Console.ReadLine();
        }
示例#23
0
        public void CsvExport(string path)
        {
            try {
                var coffeeLogExport = new CsvExport();

                coffeeLogExport.AddRow();
                coffeeLogExport["Region"]      = "Los Angeles, USA";
                coffeeLogExport["Sales"]       = 100000;
                coffeeLogExport["Date Opened"] = new DateTime(2003, 12, 31);

                coffeeLogExport.AddRow();
                coffeeLogExport["Region"]      = "Canberra \"in\" Australia";
                coffeeLogExport["Sales"]       = 50000;
                coffeeLogExport["Date Opened"] = new DateTime(2005, 1, 1, 9, 30, 0);

                coffeeLogExport.ExportToFile(path);


                string myCsv     = coffeeLogExport.Export();
                byte[] myCsvData = coffeeLogExport.ExportToBytes();
                // File(myExport.ExportToBytes(), "text/csv", "results.csv");
            } catch (Exception ex) {
                Console.WriteLine(String.Format("Error while Export CSV {0}", ex));
            }
        }
        private void btnProductReturns_Click(object sender, EventArgs e)
        {
            DateTime startDate = dtePRStartDate.SelectedDate.Value.Date;
            DateTime endDate   = dtePREndDate.SelectedDate.Value.Date.Add(new TimeSpan(23, 59, 59));

            Facade.IKPI facKPI   = new Orchestrator.Facade.KPI();
            DataSet     dsSource = facKPI.ProductReturns(startDate, endDate);

            CsvExport.Export(
                dsSource.Tables[0],
                "ProductReturns.csv",
                new CsvExport.ColumnMappings
            {
                { "OriginalCollectionPoint", "Despatch Point" },
                { "OriginalDeliveryOrderNumber", "Docket Number" },
                { "ReturnDeliveryDateTime", "Return Date", this.DateFormatter },
                { "RefusalType", "Refusal Type" },
                { "RefusalReceiptNumber", "Refusal Receipt Number" },
                { "RefusalNotes", "Refusal Notes" },
                { "ProductCode", "Product Code" },
                { "ProductName", "Product Name" },
                { "PackSize", "Pack Size" },
                { "QuantityRefused", "Quantity Refused" },
                { "ReturnDeliveryPoint", "Return To" },
                { "ReturnOrderRate", "ReturnOrderRate" },
            });
        }
示例#25
0
        // print out the chemInventory as a pdf
        public FileContentResult ExportCSV()
        {
            var dataTable = from m in _context.ChemInventory2.Include(c => c.Chemical).Include(c => c.Location).Include(c => c.Order)
                            select m;

            var export = new CsvExport();

            export.AddRow();
            export["Barcode"]      = "Barcode";
            export["CAS"]          = "CAS Number";
            export["CAT"]          = "CAT Number";
            export["LOT"]          = "LOT Number";
            export["Chem"]         = "Chemical Name";
            export["Qty"]          = "Quantity Left";
            export["Units"]        = "Units";
            export["Department"]   = "Department";
            export["Location"]     = "Location";
            export["Manufacturer"] = "Manufacturer";

            foreach (var item in dataTable)
            {
                export.AddRow();
                export["Barcode"]      = item.Barcode;
                export["CAS"]          = item.Chemical.CAS;
                export["CAT"]          = item.CAT;
                export["LOT"]          = item.LOT;
                export["Chem"]         = item.Chemical.FormulaName;
                export["Qty"]          = item.QtyLeft;
                export["Units"]        = item.Units;
                export["Department"]   = item.Department;
                export["Location"]     = item.NormalizedLocation;
                export["Manufacturer"] = item.Manufacturer;
            }
            return(File(export.ExportToBytes(), "text/csv", "Chemical Inventory.csv"));
        }
示例#26
0
        private void OnExport()
        {
            //    var type = typeof(Grade);
            //    var properties = type.GetProperties();

            _fileDialog.SaveFileDialog.Filter = "CSV|*.csv";
            _fileDialog.SaveFileDialog.Title  = "Export Grades to CSV";

            if (_fileDialog.SaveFileDialog.ShowDialog() == true)
            {
                var csvExport = new CsvExport();

                foreach (var grade in _allGrades)
                {
                    csvExport.AddRow();
                    csvExport["StudentID"]       = grade.StudentID;
                    csvExport["Student"]         = grade.Student.FullName;
                    csvExport["TestID"]          = grade.TestID;
                    csvExport["Test"]            = grade.Test.Name;
                    csvExport["Date"]            = grade.Test.Date;
                    csvExport["Maximum Points"]  = grade.Test.MaximumPoints;
                    csvExport["Points Achieved"] = grade.Points;
                    csvExport["Percentage"]      = grade.PercentAverage;
                }

                csvExport.ExportToFile(_fileDialog.SaveFileDialog.FileName);
            }
        }
示例#27
0
        private async void OnSaveAsCommand(object obj)
        {
            var saveAsDialog = new ProSaveAsFormatView();
            var vm           = new ProSaveAsFormatViewModel();

            saveAsDialog.DataContext = vm;

            if (saveAsDialog.ShowDialog() == true)
            {
                var fcUtils = new FeatureClassUtils();

                string path = fcUtils.PromptUserWithSaveDialog(vm.FeatureIsChecked, vm.ShapeIsChecked, vm.KmlIsChecked, vm.CSVIsChecked);
                if (path != null)
                {
                    try
                    {
                        string folderName   = System.IO.Path.GetDirectoryName(path);
                        var    mapPointList = CoordinateAddInPoints.Select(i => i.Point).ToList();
                        if (vm.FeatureIsChecked)
                        {
                            await fcUtils.CreateFCOutput(path,
                                                         SaveAsType.FileGDB,
                                                         mapPointList,
                                                         MapView.Active.Map.SpatialReference,
                                                         MapView.Active,
                                                         CoordinateConversionLibrary.GeomType.Point);
                        }
                        else if (vm.ShapeIsChecked || vm.KmlIsChecked)
                        {
                            await fcUtils.CreateFCOutput(path, SaveAsType.Shapefile, mapPointList, MapView.Active.Map.SpatialReference, MapView.Active, CoordinateConversionLibrary.GeomType.Point, vm.KmlIsChecked);
                        }
                        else if (vm.CSVIsChecked)
                        {
                            var aiPoints = CoordinateAddInPoints.ToList();

                            if (aiPoints == null || !aiPoints.Any())
                            {
                                return;
                            }

                            var csvExport = new CsvExport();
                            foreach (var point in aiPoints)
                            {
                                csvExport.AddRow();
                                csvExport["Coordinate"] = point.Text;
                            }
                            csvExport.ExportToFile(path);

                            System.Windows.Forms.MessageBox.Show(CoordinateConversionLibrary.Properties.Resources.CSVExportSuccessfulMessage + path,
                                                                 CoordinateConversionLibrary.Properties.Resources.CSVExportSuccessfulCaption);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
示例#28
0
        public async Task <ActionResult> ManCreate([Bind(Include = "Name, Filename")] mortal mortal)
        {
            AfisEngine Afis = new AfisEngine();

            Afis.Threshold = 180;

            var    myExport = new CsvExport();
            string apppath  = System.IO.Path.Combine(Server.MapPath("~"), "images");


            for (int i = 0; i < 40; i++)
            {
                string pathToImageO = (System.IO.Path.Combine(apppath, "original/" + (i + 1).ToString() + ".png"));

                for (int j = 0; j < 40; j++)
                {
                    string      pathToImageM2 = (System.IO.Path.Combine(apppath, "augmented/" + (j + 1).ToString() + ".jpg"));
                    Fingerprint fp1           = new Fingerprint();
                    Fingerprint fp2           = new Fingerprint();

                    MyPerson personO = new MyPerson();
                    MyPerson personM = new MyPerson();

                    Bitmap bitmap1 = fp1.AsBitmap = new Bitmap(Image.FromFile(pathToImageO));
                    Bitmap bitmap2 = fp2.AsBitmap = new Bitmap(Image.FromFile(pathToImageM2));

                    personO.Fingerprints.Add(fp1);
                    personM.Fingerprints.Add(fp2);
                    Afis.Extract(personO);
                    Afis.Extract(personM);
                    float score = Afis.Verify(personO, personM);
                    if (score > Afis.Threshold)
                    {
                        myExport.AddRow();
                        myExport["Theshold"]     = Afis.Threshold;
                        myExport["Match"]        = 1;
                        myExport["FingerprintO"] = i + 1;
                        myExport["FingerprintM"] = j + 1;
                    }
                    else
                    {
                        myExport.AddRow();
                        myExport["Theshold"]     = Afis.Threshold;
                        myExport["Match"]        = 0;
                        myExport["FingerprintO"] = i + 1;
                        myExport["FingerprintM"] = j + 1;
                    }
                }
            }



            ///ASP.NET MVC action example
            return(File(myExport.ExportToBytes(), "text/csv", "results(180).csv"));

            //return View();
            //Response.Write("<script>alert('Please Enter Filename');</script>");
        }
示例#29
0
        private void btnGenerateCsv_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            using (var uow = DIContainer.CreateUnitOfWork())
            {
                var repo     = DIContainer.CreateRepository <IProfitReportRunRepository>(uow);
                var filter   = this.GetFilter();
                var fileName = "Profitability.csv";

                switch (filter.ReportInstance)
                {
                case ReportInstanceEnum.ByPlanner:
                    CsvExport.Export(
                        repo.GetReportDataByPlanner(filter.FromDate, filter.ToDate, string.Join(",", filter.PlannerIDs)),
                        fileName,
                        new CsvExport.PropertyMappings <Orchestrator.Repositories.DTOs.ProfitabilityReport.ByPlannerRow>
                    {
                        { "Planner", i => i.PlannerName },
                        { "Driver", i => i.VehicleRegistration },
                        { "PayrollNo", i => i.PayrollNo },
                        { "Revenue", i => i.Revenue.ToString("f2") },
                        { "Cost", i => i.Cost.ToString("f2") },
                        { "Profit", i => i.Profit.ToString("f2") },
                        { "Margin", i => i.Margin.ToString("p2") },
                        { "Single Delivery Count", i => i.SingleDeliveryCount.ToString() },
                        { "Multiple Delivery Count", i => i.MultipleDeliveryCount.ToString() },
                    }
                        );

                    break;

                case ReportInstanceEnum.BySingleDriver:
                    CsvExport.Export(
                        repo.GetReportDataByPlannerSingleDriver(filter.FromDate, filter.ToDate, filter.DriverIdentityID.Value),
                        fileName,
                        new CsvExport.PropertyMappings <Orchestrator.Repositories.DTOs.ProfitabilityReport.ByPlannerSinglePlannerRow>
                    {
                        { "Planner", i => i.PlannerName },
                        { "Vehicle", i => i.VehicleRegistration },
                        { "Driver", i => i.DriverName },
                        { "Revenue", i => i.Revenue.ToString("f2") },
                        { "Cost", i => i.Cost.ToString("f2") },
                        { "Profit", i => i.Profit.ToString("f2") },
                        { "Margin", i => i.Margin.ToString("p2") },
                        { "Single Delivery Count", i => i.SingleDeliveryCount.ToString() },
                        { "Multiple Delivery Count", i => i.MultipleDeliveryCount.ToString() },
                    }
                        );

                    break;
                }
            }
        }
示例#30
0
        private void exportButton_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            var customerIdentityID      = Utilities.ParseNullable <int>(clientCombo.SelectedValue);
            var fromDate                = this.startDate.SelectedDate.Value.Date;
            var toDate                  = this.endDate.SelectedDate.Value.Date;
            var businessTypeIDs         = this.businessTypeCheckList.AllBusinessTypesSelected ? null : this.businessTypeCheckList.SelectedBusinessTypeIDs;
            var subcontractorIdentityID = Utilities.ParseNullable <int>(this.cboSubcontractor.SelectedValue);
            var isInvoiced              = this.rblInvoiced.SelectedIndex == 1 ? false : this.rblInvoiced.SelectedIndex == 2 ? true : (bool?)null;
            var hasSubcontractorInvoice = this.rblSubcontractorInvoiced.SelectedIndex == 1 ? false : this.rblInvoiced.SelectedIndex == 2 ? true : (bool?)null;

            Facade.IOrder facOrder = new Facade.Order();
            var           dtSource = facOrder.GetOrderListForExport(customerIdentityID, fromDate, toDate, businessTypeIDs, subcontractorIdentityID, isInvoiced, hasSubcontractorInvoice).Tables[0];

            if (dtSource.Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "NoData", "$(function() { alert('No matching orders were found'); });", true);
                return;
            }

            Func <DataRow, string, string> dateFormatter             = (dr, col) => dr.Field <DateTime>(col).ToShortDateString();
            Func <DataRow, string, string> nullableCurrencyFormatter = (dr, col) => string.Format("{0:n2}", dr.Field <decimal?>(col));
            Func <DataRow, string, string> nullableIntFormatter      = (dr, col) => string.Format("{0}", dr.Field <int?>(col));

            CsvExport.Export(
                dtSource,
                "Orders.csv",
                new CsvExport.ColumnMappings
            {
                { "OrderID", "Order ID" },
                { "CustomerName", "Customer" },
                { "DeliveryOrderNumber", "Docket number" },
                { "CustomerOrderNumber", "Load number" },
                { "JobID", "Run ID", nullableIntFormatter },
                { "BusinessType", "Business Type" },
                { "CollectionPoint", "Collection point" },
                { "CollectionPostcode", "Collection postcode" },
                { "DeliveryPoint", "Delivery point" },
                { "DeliveryPostcode", "Delivery postcode" },
                { "PalletSpaces", "Pallet spaces" },
                { "Weight", "Weight" },
                { "SubcontractorRate", "Subcontractor cost", nullableCurrencyFormatter },
                { "ForeignRateIncludingFuelSurcharge", "Total revenue" },
                { "ExtrasForeignTotal", "Extras" },
                { "FuelSurchargeForeignAmount", "Fuel surcharge" },
                { "ForeignRate", "Revenue" },
                { "CollectionDateTime", "Collection date", dateFormatter },
                { "DeliveryDateTime", "Delivery date", dateFormatter },
                { "SubcontractorName", "Subcontractor" },
                { "OrderStatus", "Order status" },
                { "HasSubcontractorInvoice", "Has subcontractor invoice?", (dr, col) => dr.Field <bool>(col) ? "Yes" : "No" },
            });
        }
        private void DownloadShopperVisitsDay(DateTime date)
        {
            string sql      = "EXEC SelectShopperVisitsDay @Day, @Month, @Year";
            var    myExport = new CsvExport();

            using (SqlConnection conn = Connection.GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@Day", date.Day);
                    cmd.Parameters.AddWithValue("@Month", date.Month);
                    cmd.Parameters.AddWithValue("@Year", date.Year);
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            if (dr.HasRows)
                            {
                                while (dr.Read())
                                {
                                    myExport.AddRow();
                                    myExport["Date"]        = dr.GetValue(0).ToString();
                                    myExport["Name"]        = dr.GetValue(1).ToString();
                                    myExport["Email"]       = dr.GetValue(2).ToString();
                                    myExport["Phone"]       = dr.GetValue(3).ToString();
                                    myExport["Address"]     = dr.GetValue(4).ToString();
                                    myExport["First"]       = dr.GetValue(5).ToString();
                                    myExport["Children"]    = dr.GetValue(6).ToString();
                                    myExport["Case Worker"] = dr.GetValue(7).ToString();
                                    myExport["Relation"]    = dr.GetValue(8).ToString();
                                    myExport["Description"] = dr.GetValue(9).ToString();
                                }
                                myExport.ExportToFile(Server.MapPath("~/Data/ShopperVisits.csv"));
                                FileInfo file = new FileInfo(Server.MapPath("~/Data/ShopperVisits.csv"));
                                string   a    = file.Directory.ToString();
                                string   b    = file.FullName;
                                if (file.Exists)
                                {
                                    Response.Clear();
                                    Response.ContentType = "application/octet-stream";
                                    Response.AppendHeader("Content-Disposition", "filename=" + "ShopperVisits" + "-" + Session["Year"].ToString() + "-" + Session["Month"].ToString() + "-" + Session["Day"].ToString() + ".csv");
                                    Response.TransmitFile(Server.MapPath("~/Data/ShopperVisits.csv"));
                                    Response.End();
                                    file.Delete();
                                }
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        throw exc;
                    }
                }
            }
        }
示例#32
0
        internal protected override void Export(WaitProgressForm wait)
        {
            wait.Message = "Initalize";

            DoWorkCorrectly = true;
            StreamWriter streamWriter = null;
            FileStream   fs           = null;
            CsvExport    exporter     = new CsvExport(delimiter, Data, ExportWithColumnName);

            try
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                wait.Message = "Create CSV Format";

                fs           = new FileStream(fileName, FileMode.CreateNew);
                streamWriter = new StreamWriter(fs, System.Text.Encoding.UTF8);

                exporter.Progress += (s, e) =>
                {
                    wait.Value = e.CurrentIndex;
                    if (CancelWork)
                    {
                        exporter.CancelWork = true;
                    }
                };

                exporter.Convert(streamWriter);

                streamWriter.Flush();
                fs.Flush();
                streamWriter.Close();
                fs.Close();
            }
            catch
            {
                DoWorkCorrectly = false;
                if (fs != null)
                {
                    if (streamWriter != null)
                    {
                        streamWriter.Close();
                    }
                    fs.Close();
                }
            }
        }
示例#33
0
	public Descripteurs(){
		m_export = new CsvExport();
		_amplitudeMin = 300;
		_amplitudeMax = 0;
		_nbPoing = 0;
		_vitesseMax = 0;
		_vitesseMin = 0;
		_vitesseMoy = 0;
		_distMax = 0;
		_distMin = 0;
	}
示例#34
0
        public ActionResult Export()
        {
            var issues = TempData["search_results"] as IEnumerable<Issue>;
            foreach (var i in issues)
            {
                i.Body = string.Empty;
                i.Labels = null;
            }

            var exporter = new CsvExport<Issue>(issues);
            var bytes = exporter.ExportToBytes(seperatorChar: ';');

            return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "issues.csv");
        }
示例#35
0
    protected void ExcelClick_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("HelpRequests_Reports_By");
        cmd.Parameters.AddWithValue("@BuildAllSQL", getSQL());
        cmd.Parameters.AddWithValue("@DisplayBy", DisplayResutlsbyDD.SelectedValue);

        CsvExport myExport = new CsvExport();
        ArrayList columns = new ArrayList();
        DataTableReader dtr = DataBase.executeStoreProcudure(cmd).CreateDataReader();

        for (int i = 0; i < dtr.FieldCount; i++)
        {
            columns.Add(dtr.GetName(i));
        }

        if (dtr.HasRows)
        {
            while (dtr.Read())
            {

                //   Then you can do any of the following three output options:
                myExport.AddRow();
                foreach (var ii in columns)
                {
                    string columnName = ii.ToString();
                    if (columnName == "Assigned To")
                    {
                        myExport[columnName] = getResourceRequestsAdminUsers(dtr[columnName].ToString());
                    }
                    else
                    {
                        myExport[columnName] = dtr[columnName].ToString();
                    }
                }

            }
        }

        myCsv = myExport.Export();

        string attachment = "attachment; filename=AdHocResourcesReports-data-" + DateTime.Now.ToShortDateString() + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.Write(myCsv);
        HttpContext.Current.Response.End();
    }
示例#36
0
        public static async void Write(List<Product> products, string path)
        {
            var csvExport = new CsvExport();
            csvExport.AddRows(products.Select(x => new
            {
                x.Model,
                x.Brand,
                x.DeviceType,
                x.AdditionalComments
            }));

            using (var streamWriter = new StreamWriter(path, false, Encoding.UTF8))
            {
                await streamWriter.WriteAsync(csvExport.Export());
                await streamWriter.FlushAsync();
            }
        }
示例#37
0
        /// <summary>
        /// Converte o excel em csv e apaga o excel
        /// </summary>
        /// <param name="instanceFile"></param>
        private static void ConverterEmCsvEApagar(FileInfo instanceFile)
        {
            var myExport = new CsvExport();

            FileStream stream = File.Open(instanceFile.FullName, FileMode.Open, FileAccess.Read);

            // Reading from a OpenXml Excel file (2007 format; *.xlsx)
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            excelReader.IsFirstRowAsColumnNames = true;
            var firstRow = false;

            while (excelReader.Read())
            {
                if (firstRow)
                {
                    myExport.AddRow();

                    myExport["Rodada"] = excelReader.GetString(0);
                    myExport["Individuo"] = excelReader.GetString(1);
                    myExport["Operacao"] = excelReader.GetString(2);
                    myExport["Fitness"] = excelReader.GetString(3);
                    myExport["Tempo"] = excelReader.GetString(4).Replace("31/12/1899 ", ""); //Bug na leitura do campo
                    myExport["Testes"] = excelReader.GetString(5);
                }

                firstRow = true;
            }

            // Free resources (IExcelDataReader is IDisposable)
            excelReader.Close();

            string output = instanceFile.FullName.Replace("xlsx", "csv");
            if (File.Exists(output))
                File.Delete(output);

            myExport.ExportToFile(output);

            File.Delete(instanceFile.FullName);
        }
示例#38
0
        public static async void Write(IEnumerable<ProductReview> reviews, string path)
        {
            var csvExport = new CsvExport();
            csvExport.AddRows(reviews.Select(x => new
            {
                x.Reviewer,
                x.ScoreMark,
                x.Recommendation,
                x.AddedOn,
                x.ConsideredAsUsefulCount,
                x.UsefulnessBaseCount,
                ProductAdventages = string.Join("; ", x.ProductAdventages.Select(productAdventage => productAdventage.Feature)),
                ProductDisadvantages = string.Join("; ", x.ProductDisadvantages.Select(productDisadvantage => productDisadvantage.Feature)),
                x.Body
            }));

            using (var streamWriter = new StreamWriter(path, false, Encoding.UTF8))
            {
                await streamWriter.WriteAsync(csvExport.Export());
                await streamWriter.FlushAsync();
            }
        }
        public ActionResult exportIsentosToCsv(IsentosListViewModel viewModel, string sort, string direction)
        {
            viewModel.PageSize = 0;
            viewModel.SetParameters(1, 1, sort, direction, Request.Params);

            IsentosListViewModel result = getIsentos(viewModel);

            List<ApoliceIsentoToCsv> isentosCsv = new List<ApoliceIsentoToCsv>();
            foreach (ApoliceIsento apo in result.apolicesIsentos)
                isentosCsv.Add(new ApoliceIsentoToCsv
                {
                    entidade = apo.entidade.nome,
                    matricula = apo.matricula,
                    dataFim = apo.dataFim.ToString(),
                    dataInicio = apo.dataInicio.ToString(),
                    confidencial = apo.confidencial ? "Sim" : "Não",
                    dataModificacao = apo.dataModificacao.ToString()
                });

            CsvExport<ApoliceIsentoToCsv> csv = new CsvExport<ApoliceIsentoToCsv>(isentosCsv);

            byte[] fileBytes = csv.ExportToBytes();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "Isentos_" + DateTime.Now.ToShortDateString() + ".csv");
        }
示例#40
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            FilterPosts(chkMatchRows.Checked);

            var saveFileDialog = new SaveFileDialog
            {
                InitialDirectory = Directory.GetCurrentDirectory(),
                Filter =
                    "HTML Files (*.html) |*.html; *.HTML; *.Html |CSV Files (*.csv) |*.csv; *.CSV; *.Csv |All files (*.*)|*.*",
                FilterIndex = 0,
                RestoreDirectory = true,
                Title = "Export " + toSave.Count + " Posts..."
            };

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Console.WriteLine("File Extension: " + Path.GetExtension(saveFileDialog.FileName.ToLower()));

                    switch (Path.GetExtension(saveFileDialog.FileName.ToLower()))
                    {
                        case ".csv":
                            var csv = new CsvExport(toSave);
                            csv.ExportToFile(saveFileDialog.FileName);
                            break;
                        case ".html":
                            var html = new HtmlExport(toSave);
                            html.ExportToFile(saveFileDialog.FileName);
                            break;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not save file to disk. Error: " + ex.Message);
                }
            }
        }
 /// <summary>
 /// Metoda wywoływana przez przycisk "To CSV". Dzięki niej aplikacja zapisuje komentarze do danego produktu w pliku CSV.
 /// Wszystkie elementy listy są przekazywane do konstrukora klasy CsvExport.
 /// Następnie wywoływana jest metoda ExportToFile, której argumentem jest proponowana nazwa pliku.
 /// Plik zapisywany jest w wybranej przez użytkownika lokalizacji.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ExportToCSVButton_Click(object sender, RoutedEventArgs e)
 {
     var csv = new CsvExport<Comment>(CommentsList.Items.ToList());
     csv.ExportToFile(pageTitle.Text + " Comments");
 }
    protected void ExcelClick_Click(object sender, EventArgs e)
    {
        CsvExport myExport = new CsvExport();
        ArrayList columns = new ArrayList();
        DataTableReader dtr = DataBase.dbDataTable(ReportSQLStatement).CreateDataReader();

        for (int i = 0; i < dtr.FieldCount; i++)
        {
            columns.Add(dtr.GetName(i));
        }

        if (dtr.HasRows)
        {
            while (dtr.Read())
            {

                //   Then you can do any of the following three output options:
                myExport.AddRow();
                foreach (var ii in columns)
                {
                    string columnName = ii.ToString();
                    myExport[columnName] = dtr[columnName].ToString();
                }

            }
        }

        myCsv = myExport.Export();

        string attachment = "attachment; filename=AdHocResourcesReports-data-" + DateTime.Now.ToShortDateString() + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.Write(myCsv);
        HttpContext.Current.Response.End();
    }
示例#43
0
        public static string ToCsv(CsvExport signficant = CsvExport.All)
        {
            var result = new StringBuilder();
            result.AppendLine(Match.ToCsvHeader());
            switch (signficant)
            {
                case CsvExport.All:
                    foreach (var match in MatchList)
                    {
                        result.AppendLine(match.ToCsv());
                    }
                    break;
                case CsvExport.Significant:
                    foreach (var match in GetChromosomes())
                    {
                        result.AppendLine(match.ToCsv());
                    }

                    break;
                case CsvExport.Chromosomes:
                    foreach (var match in GetActualChromosomes())
                    {
                        result.AppendLine(match.ToCsv());
                    }
                    break;

            }
            result.AppendLine(Copyright);
            return result.ToString();
        }
示例#44
0
    protected void DownloadReport_Click(object sender, EventArgs e)
    {
        StartDateTxt = StartDate.Text;
        EndDateTxt = EndDate.Text;
        string CompareDataAgainstTxt = CompareDataAgainst.SelectedValue;
        string DateRangeTxt = DateRange.SelectedValue;
        Resources = getResources();
        switch (ReportTypeDD.SelectedValue)
        {
            case "Comparative Resource Pricing":
                showComparativeResults(Resources, CompareDataAgainstTxt, DateRangeTxt);
                break;

            case "Pricing Over Time":
                showPricingOver(Resources, CompareDataAgainstTxt, DateRangeTxt);
                break;

            case "Procurement Method":
                showProcurementMethod(Resources, CompareDataAgainstTxt, DateRangeTxt);
                break;

            case "Contract Expiration":
                showExpirationContracts(Resources, CompareDataAgainstTxt, DateRangeTxt);
                break;
        }

        //ResultsGridView.DataSource = dtResults;

        CsvExport myExport = new CsvExport();
        ArrayList columns = new ArrayList();
        DataTableReader dtr = dtResults.CreateDataReader();

        for (int i = 0; i < dtr.FieldCount; i++)
        {
            columns.Add(dtr.GetName(i));
        }

        if (dtr.HasRows)
        {
            while (dtr.Read())
            {

                //   Then you can do any of the following three output options:
                myExport.AddRow();
                foreach (var ii in columns)
                {
                    string columnName = ii.ToString();
                    myExport[columnName] = dtr[columnName].ToString();
                }

            }
        }

        myCsv = myExport.Export();

        string attachment = "attachment; filename=AdHocResourcesReports-data-" + DateTime.Now.ToShortDateString() + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.Write(myCsv);
        HttpContext.Current.Response.End();
    }
示例#45
0
        /// <summary>
        /// Export the contents of the patient data record to the user's harddrive.
        /// </summary>
        /// <param name="patientDataId"></param>
        /// <returns></returns>
        public string ExportData(string patientDataId)
        {
            string path = @"c:\exports\" + Guid.NewGuid().ToString();
            ExportPath = path;
            //Create download directory
            Directory.CreateDirectory(path);

            PatientData patientData = _patientDataService.GetPatientData(patientDataId);

            //Export any activity information associated with the patient data record.
            if(patientData.Activities != null && patientData.Activities.Count > 0) {
                CsvExport activityExport = new CsvExport();
                foreach(Activity activity in patientData.Activities) {
                    activityExport.AddRow();
                    activityExport["Start Time"] = activity.StartTime;
                    activityExport["End Time"] = activity.EndTime;
                    activityExport["Activity Type"] = (ActivityType)activity.DataActivity;
                }
                activityExport.ExportToFile(@path + "\\Activities_" + patientData.Name);
            }

            List<string> columnNames = new List<string>();
            CsvExport export = new CsvExport();
            int count = 0;
            int index = 1;
            string fileIndex = string.Empty;
            try {
                switch (patientData.DataType) {
                    case (int)File_Type.Accelerometer:
                        Device_Type deviceType = PatientLogic.DetermineDeviceType(patientData.Name);
                        switch (deviceType) {
                            case Device_Type.Zephyr:
                                IEnumerable<ZephyrAccelerometer> zephyrAccelData = null;
                                index = 1;
                                do {
                                    zephyrAccelData = _zephyrAccelService.GetZephyrAccelerometerData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                                    count = 0;
                                    foreach (ZephyrAccelerometer data in zephyrAccelData) {
                                        export.AddRow();
                                        export["Time"] = data.Time;
                                        export["Vertical"] = data.Vertical;
                                        export["Lateral"] = data.Lateral;
                                        export["Sagittal"] = data.Sagittal;
                                        count++;
                                        if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                            export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                            index++;
                                            fileIndex = index.ToString() + "_";
                                            export = new CsvExport();
                                        }
                                    }
                                } while (zephyrAccelData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                                break;
                            case Device_Type.Microsoft_Band:
                                IEnumerable<MSBandAccelerometer> msAccelData = null;
                                index = 1;
                                do {
                                    msAccelData = _msBandAccelService.GetMSBandAccelerometerData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                                    count = 0;
                                    foreach (MSBandAccelerometer data in msAccelData) {
                                        export.AddRow();
                                        export["Time Stamp"] = data.Date;
                                        export["X(m/s²)"] = data.Lateral;
                                        export["Y(m/s²)"] = data.Vertical;
                                        export["Z(m/s²)"] = data.Sagittal;
                                        count++;
                                        if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                            export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                            index++;
                                            fileIndex = index.ToString() + "_";
                                            export = new CsvExport();
                                        }
                                    }
                                } while (msAccelData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                                break;
                            default:
                                break;
                        }
                        break;
                    case (int)File_Type.Breathing:
                        IEnumerable<ZephyrBreathingWaveform> zephyrBreathingData = null;
                        index = 1;
                        do {
                            zephyrBreathingData = _breathingService.GetZephyrBreathingWaveformData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (ZephyrBreathingWaveform data in zephyrBreathingData) {
                                export.AddRow();
                                export["Time"] = data.Time;
                                export["BreathingWaveform"] = data.Data;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (zephyrBreathingData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.Calorie:
                        IEnumerable<MSBandCalories> calorieData = null;
                        index = 1;
                        do {
                            calorieData = _msBandCaloriesService.GetMSBandCaloriesData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (MSBandCalories data in calorieData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Date;
                                export["Total Calories(kCal)"] = data.Total;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (calorieData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.Distance:
                        IEnumerable<MSBandDistance> distanceData = null;
                        index = 1;
                        do {
                            _msBandDistanceService.GetMSBandDistanceData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (MSBandDistance data in distanceData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Date;
                                export["Motion Type"] = data.MotionType;
                                export["Pace(min/km)"] = data.Pace;
                                export["Speed(km/hr)"] = data.Speed;
                                export["Total(km)"] = data.Total;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (distanceData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.ECG:
                        IEnumerable<ZephyrECGWaveform> ecgData = null;
                        index = 1;
                        do {
                            ecgData = _ecgService.GetZephyrECGWaveFormData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (ZephyrECGWaveform data in ecgData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Time;
                                export["Motion Type"] = data.Data;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (ecgData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.EventData:
                        IEnumerable<ZephyrEventData> eventData = null;
                        index = 1;
                        do {
                            eventData = _eventDataService.GetZephyrEventData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (ZephyrEventData data in eventData) {
                                export.AddRow();
                                export["SeqNo"] = "0";
                                export["Time Stamp"] = data.Date;
                                export["EventCode"] = data.EventCode;
                                export["Type"] = data.Type;
                                export["Source"] = data.Source;
                                export["EventID"] = data.EventId;
                                export["EventSpecificData"] = data.EventSpecificData;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (eventData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.Gyroscope:
                        IEnumerable<MSBandGyroscope> gyroscopeData = null;
                        index = 1;
                        do {
                            gyroscopeData = _msBandGyroscopeService.GetMSBandGyroscopeData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (MSBandGyroscope data in gyroscopeData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Date;
                                export["X-Axis(°/s)"] = data.X;
                                export["Y-Axis(°/s)"] = data.Y;
                                export["Z-Axis(°/s)"] = data.Z;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (gyroscopeData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.HeartRate:
                        IEnumerable<MSBandHeartRate> heartRateData = null;
                        index = 1;
                        do {
                            heartRateData = _msBandHeartRateService.GetMSBandHeartRateData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (MSBandHeartRate data in heartRateData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Date;
                                export["Read Status"] = data.ReadStatus;
                                export["Heart Rate(bpm)"] = data.HeartRate;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (heartRateData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.Pedometer:
                        IEnumerable<MSBandPedometer> pedometerData = null;
                        index = 1;
                        do {
                            pedometerData = _msBandPedometerService.GetMSBandPedometerData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (MSBandPedometer data in pedometerData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Date;
                                export["Steps"] = data.Steps;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (pedometerData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.Summary:
                        Device_Type summaryDevice = PatientLogic.DetermineDeviceType(patientData.Name);
                        switch (summaryDevice) {
                            case Device_Type.Zephyr:
                                IEnumerable<ZephyrSummaryData> zephyrSummaryData = null;
                                index = 1;
                                do {
                                    zephyrSummaryData = _summaryService.GetZephyrSummaryData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                                    count = 0;
                                    foreach (ZephyrSummaryData data in zephyrSummaryData) {
                                        export.AddRow();
                                        export["Time"] = data.Date;
                                        export["HR"] = data.HeartRate;
                                        export["BR"] = data.BreathingRate;
                                        export["SkinTemp"] = data.SkinTemp;
                                        export["Posture"] = data.Posture;
                                        export["Activity"] = data.Activity;
                                        export["PeakAccel"] = data.PeakAccel;
                                        export["BatteryVolts"] = data.BatteryVolts;
                                        export["BatteryLevel"] = data.BatteryLevel;
                                        export["BRAmplitude"] = data.BRAmplitude;
                                        export["BRNoise"] = data.BRNoise;
                                        export["BRConfidence"] = data.BRConfidence;
                                        export["ECGAmplitude"] = data.ECGAmplitude;
                                        export["ECGNoise"] = data.ECGNoise;
                                        export["HRConfidence"] = data.HRConfidence;
                                        export["HRV"] = data.HRV;
                                        export["SystemConfidence"] = data.SystemConfidence;
                                        export["GSR"] = data.GSR;
                                        export["ROGState"] = data.ROGState;
                                        export["ROGTime"] = data.ROGTime;
                                        export["VerticalMin"] = data.VerticalMin;
                                        export["VerticalPeak"] = data.VerticalPeak;
                                        export["LateralMin"] = data.LateralMin;
                                        export["LateralPeak"] = data.LateralPeak;
                                        export["SagittalMin"] = data.SagittalMin;
                                        export["SagittalPeak"] = data.SagittalPeak;
                                        export["DeviceTemp"] = data.DeviceTemp;
                                        export["StatusInfo"] = data.StatusInfo;
                                        export["LinkQuality"] = data.LinkQuality;
                                        export["RSSI"] = data.RSSI;
                                        export["TxPower"] = data.TxPower;
                                        export["CoreTemp"] = data.CoreTemp;
                                        export["AuxADC1"] = data.AuxADC1;
                                        export["AuxADC2"] = data.AuxADC2;
                                        export["AuxADC3"] = data.AuxADC3;
                                        count++;
                                        if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                            export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                            index++;
                                            fileIndex = index.ToString() + "_";
                                            export = new CsvExport();
                                        }
                                    }
                                } while (zephyrSummaryData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                                break;
                            case Device_Type.BasisPeak:
                                IEnumerable<BasisPeakSummaryData> basisData = null;
                                index = 1;
                                do {
                                    basisData = _basisPeakService.GetBasisPeakSummaryData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                                    count = 0;
                                    foreach (BasisPeakSummaryData data in basisData) {
                                        export.AddRow();
                                        export["date"] = data.Date;
                                        export["calories"] = data.Calories;
                                        export["gsr"] = data.GSR;
                                        export["heart-rate"] = data.HeartRate;
                                        export["skin-temp"] = data.SkinTemp;
                                        export["steps"] = data.Steps;
                                        count++;
                                        if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                            export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                            index++;
                                            fileIndex = index.ToString() + "_";
                                            export = new CsvExport();
                                        }
                                    }
                                } while (basisData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                                break;
                            default:
                                break;
                        }
                        break;
                    case (int)File_Type.General:
                        IEnumerable<ZephyrSummaryData> zephyrGeneralData = null;
                        index = 1;
                        do {
                            zephyrGeneralData = _summaryService.GetZephyrSummaryData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (ZephyrSummaryData data in zephyrGeneralData) {
                                export.AddRow();
                                export["Timestamp"] = data.Date;
                                export["HR"] = data.HeartRate;
                                export["BR"] = data.BreathingRate;
                                export["Temp"] = data.SkinTemp;
                                export["Posture"] = data.Posture;
                                export["Activity"] = data.Activity;
                                export["Acceleration"] = data.PeakAccel;
                                export["Battery"] = data.BatteryVolts;
                                export["BRAmplitude"] = data.BRAmplitude;
                                export["ECGAmplitude"] = data.ECGAmplitude;
                                export["ECGNoise"] = data.ECGNoise;
                                export["XMin"] = data.LateralMin;
                                export["XPeak"] = data.LateralPeak;
                                export["YMin"] = data.VerticalMin;
                                export["YPeak"] = data.VerticalPeak;
                                export["ZMin"] = data.SagittalMin;
                                export["ZPeak"] = data.SagittalPeak;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (zephyrGeneralData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.Temperature:
                        IEnumerable<MSBandTemperature> temperatureData = null;
                        index = 1;
                        do {
                            temperatureData = _msBandTemperatureService.GetMSBandTemperatureData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (MSBandTemperature data in temperatureData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Date;
                                export["Temperature(°C)"] = data.Temperature;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (temperatureData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.UV:
                        IEnumerable<MSBandUV> uvData = null;
                        index = 1;
                        do {
                            uvData = _msBandUVService.GetMSBandUVData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (MSBandUV data in uvData) {
                                export.AddRow();
                                export["Time Stamp"] = data.Date;
                                export["UV Index (0-4)"] = data.UVIndex;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (uvData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    case (int)File_Type.BR_RR:
                        IEnumerable<ZephyrBRRR> brRrData = null;
                        index = 1;
                        do {
                            brRrData = _brRrService.GetZephyrBRRRData(patientData, ((index - 1) * count), SystemConstants.MAX_ITEMS_RETURNED);
                            count = 0;
                            foreach (ZephyrBRRR data in brRrData) {
                                export.AddRow();
                                export["Time Stamp"] = data.TimeStamp;
                                export["BR"] = data.BR;
                                export["RtoR"] = data.RR;
                                count++;
                                if (count == SystemConstants.MAX_ITEMS_RETURNED) {
                                    export.ExportToFile(@path + "\\" + index + "_" + patientData.Name);
                                    index++;
                                    fileIndex = index.ToString() + "_";
                                    export = new CsvExport();
                                }
                            }
                        } while (brRrData != null && count == SystemConstants.MAX_ITEMS_RETURNED);
                        break;
                    default:
                        break;
                }
            }
            catch(OutOfMemoryException ex) {
                //Don't need to do anything here just catch the exception and continue.  Meant to prevent
                //error screen but still allow some data to export.  This would need to be troubleshooted
                //by a future team.
            }

            export.ExportToFile(@path + "\\" + fileIndex + patientData.Name);

            string zipFileName = "PatientDataRecord-" + patientData.Name + ".zip";

            ZipArchive zip = ZipFile.Open(path + "\\" + zipFileName, ZipArchiveMode.Create);

            foreach (var file in Directory.EnumerateFiles(path)) {
                if (!file.Contains(".zip")) {
                    zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
                }
            }
            zip.Dispose();

            return zipFileName;
        }
示例#46
0
        /// <summary>
        /// Executa a Otimização.
        /// </summary>
        /// <param name="caminhoBibliotecaJs"></param>
        /// <param name="caminhoTestesJs"></param>
        /// <returns>
        /// Verdadeiro se encontrar melhoria
        /// </returns>
        public bool Otimizar(string caminhoBibliotecaJs, string caminhoTestesJs)
        {
            bool otimizou = false;

            _caminhoScriptTestes = caminhoTestesJs;
            _caminhoBiblioteca = caminhoBibliotecaJs;

            Console.WriteLine(string.Format("Iniciando Otimização do {0}", caminhoBibliotecaJs));
            Console.WriteLine(string.Format("    SetTimeout {0}", _usarSetTimeout));
            Console.WriteLine(string.Format("    Heuristica {0}", Heuristica));

            _javascriptHelper = new JavascriptHelper(_diretorioFontes, _usarSetTimeout, false);
            _javascriptHelper.ConfigurarGeracao();

            var sw = new Stopwatch();
            sw.Start();
            if(Heuristica == "GA")
                otimizou = OtimizarUsandoGa();
            else if(Heuristica == "RD")
                otimizou = OtimizarUsandoRd();
            else if (Heuristica == "HC")
                otimizou = OtimizarUsandoHc();
            else if (Heuristica == "HCF")
                otimizou = OtimizarUsandoHcPorFuncao();
            else
                throw new ApplicationException(string.Format("Heurística ainda não definida. {0}", Heuristica));

            #region Gera o CSV da rodada

            var myExport = new CsvExport();

            myExport.AddRow();
            myExport["Rodada"] = RodadaGlobalExterna;
            myExport["Individuo"] = MelhorIndividuo.Arquivo;
            myExport["Operacao"] = MelhorIndividuo.CriadoPor;
            myExport["Fitness"] = MelhorIndividuo.Fitness;
            myExport["Tempo"] = MelhorIndividuo.TempoExecucao;
            myExport["Testes"] = MelhorIndividuo.TestesComSucesso;

            myExport.ExportToFile("rodadas.csv");

            #endregion

            #region limpa o diretório de execução.

            var files = new DirectoryInfo(_diretorioExecucao).EnumerateFiles("*.js").ToList();

            files.ForEach(f => f.Delete());

            #endregion

            sw.Stop();
            Console.WriteLine("  Tempo total: {0}", sw.Elapsed.ToString(@"hh\:mm\:ss\,ffff"));

            return otimizou;
        }
示例#47
0
        /// <summary>
        /// Dumps statistics to files.
        /// </summary>
        public void Dump()
        {
            CsvExport<IterationData> csvExport = new CsvExport<IterationData>(_iterations);
            csvExport.ExportToFile(Path.Combine(_directory, "iterations.csv"));

            var bestChromosome = _bestChromosome as BinaryChromosome;
            var genotype = new String(bestChromosome.Genotype.Select(x => x ? '1' : '0').ToArray());

            File.WriteAllLines(Path.Combine(_directory, "best_chromosome.txt"), new string[] { _bestChromosomeValue.ToString(), genotype });
        }
示例#48
0
        /// <summary>
        /// Inclui a linha no excel
        /// </summary>
        /// <param name="indice"></param>
        /// <param name="sujeito"></param>
        /// <param name="testesComSucesso"></param>
        /// <param name="tempoTotal"></param>
        private void CriarLinhaExcel(int indice, Individuo sujeito, int testesComSucesso, string tempoTotal)
        {
            #region Inclui no  CSV

            var myExport = new CsvExport();

            myExport.AddRow();

            myExport["Geracao"] = _generationCount;
            myExport["Individuo"] = sujeito.Arquivo;
            myExport["Operacao"] = sujeito.CriadoPor.ToString();
            myExport["Fitness"] = sujeito.Fitness;
            myExport["Tempo"] = tempoTotal;
            myExport["Testes"] = testesComSucesso;

            myExport.ExportToFile(Path.Combine(_diretorioExecucao, "resultados.csv"));

            #endregion
        }
示例#49
0
        /// <summary>
        /// Processa a roda do GA
        /// </summary>
        /// <param name="directoryGa"></param>
        /// <param name="biblioteca"></param>
        /// <param name="resultsDirectory"></param>
        private static List<RodadaMapper> ProcessarDiretorio(DirectoryInfo directoryGa, DirectoryInfo biblioteca, string resultsDirectory)
        {
            //pego o csv ou xsls
            var rodadas = new List<RodadaMapper>();
            var instanceFile = directoryGa.GetFiles().FirstOrDefault();

            if (instanceFile == null)
            {
                Console.WriteLine("Deveria existir um arquivo com as rodadas | {0}", directoryGa.FullName);
                Environment.Exit(-1);
            }

            Console.WriteLine("         Algoritmo {0}", directoryGa.Name);
            ConverterTodosExceis(directoryGa);

            if (instanceFile.Extension == ".csv")
            {
                rodadas = RecuperarRodadasDoGaNoCsv(instanceFile, biblioteca, directoryGa);
            }

            #region Exporta CSV

            var myExport = new CsvExport();

            foreach (var rodadaMapper in rodadas)
            {
                myExport.AddRow();

                myExport["Rodada"] = rodadaMapper.Rodada;
                myExport["TempoOriginalUnload"] = rodadaMapper.TempoOriginalComUnload;
                myExport["TempoFinalUnload"] = rodadaMapper.TempoFinalComUnload;
                myExport["TempoOriginalMS"] = rodadaMapper.Fitness;
                myExport["TempoFinalMS"] = rodadaMapper.FitnessFinal;
                myExport["LOCOriginal"] = rodadaMapper.LocOriginal;
                myExport["LOCFinal"] = rodadaMapper.LocFinal;
                myExport["CaracteresOrginal"] = rodadaMapper.CaracteresOriginal;
                myExport["CaracteresFinal"] = rodadaMapper.CaracteresFinal;
                myExport["Operacao"] = rodadaMapper.Operacao;
                myExport["Arquivo"] = rodadaMapper.Individuo;

            }

            var fileName = Path.Combine(resultsDirectory, biblioteca.Name + directoryGa.Name + ".csv");

            if (File.Exists(fileName))
                File.Delete(fileName);

            myExport.ExportToFile(fileName);

            #endregion

            return rodadas;
        }
示例#50
0
    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        AqlQuery q = GetOrderSelectionQuery((OrderFilter)Utils.GetIntegerOnly(ddlFilterBy.SelectedValue));
        List<Order> orders = new List<Order>();
        AqlResultSet rs = q.Execute();
        while (rs.Read()) {
            orders.Add((Order)rs[0]);
        }
        Shop shop = WAFShopHelper.GetCurrentShop();
        //List<Order> orders = WAFContext.Session.Query<Order>().Where(AqlOrder.SiteId == WAFContext.Session.SiteId).Where(AqlOrder.IsDerived == false).OrderBy(AqlOrder.Name).Execute();
        CsvExport export = new CsvExport();
        foreach (Order o in orders) {
            export.AddRow();
            export["OrderId"] = o.NodeId;
            export["OrderStatus"] = WAFContext.Session.GetEnumName(o.OrderStatus);
            export["Email"] = o.Email;
            if (o.DateOrdered > o.CreateDate) {
                export["DateOrdered"] = o.DateOrdered;
            } else {
                export["DateOrdered"] = " - ";
            }
            if (o.DateShipped > o.CreateDate) {
                export["DateShipped"] = o.DateShipped;
            } else {
                export["DateShipped"] = " - ";
            }
            export["OrderTotal"] = o.OrderTotal;
            export["VATAmount"] = o.VATAmount;
            export["ItemsSubtotalExVat"] = o.ItemsSubtotalExVat;
            double itemsIncVat = 0;
            foreach (OrderItem item in o.OrderItems.Get()) {
                itemsIncVat = itemsIncVat + item.ItemTotalIncVat;
            }
            export["ItemsSubtotalIncVat"] = o.ItemsSubtotalExVat;

            export["PaymentTransactionId"] = o.PaymentTransactionId;
            if (o.PaymentMethod.IsSet()) {
                export["PaymentMethod"] = o.PaymentMethod.Get().Name;
            } else {
                export["PaymentMethod"] = "";
            }
            export["ShippingAmountExVat"] = o.ShippingAmount;
            double taxPercetage = ((double)shop.DefaultTaxRate / (double)100);
            export["ShippingAmountIncVat"] = o.ShippingAmount * (1 + taxPercetage);

            if (o.ShippingMethod.IsSet()) {
                export["ShippingMethod"] = o.ShippingMethod.Get().Name;
            } else {
                export["ShippingMethod"] = "";
            }

            string currency = "";
            if (o.Currency.IsSet()) {
                currency = o.Currency.Get().Code;
            }
            export["Currency"] = currency;
            export["NumberOfItemsInOrder"] = o.GetNumberOfItemsInCart();

            if (o.ClassId != Order.ContentClassId) {
                //inherited class. add custom fields
                ContentDefinition def = WAFContext.Engine.Definition;

                var baseProp = def.ContentClass[Order.ContentClassId].GetAllPropertyIds();
                var newPropIds = def.ContentClass[o.ClassId].GetAllPropertyIds().Where(p => !baseProp.Contains(p));

                foreach (var p in newPropIds.Select(id => def.Property[id])) {
                    switch (p.BasePropertyClassId) {
                        case PropertyBaseClass.CheckBoxProperty:
                        case PropertyBaseClass.FloatProperty:
                        case PropertyBaseClass.ShortTextProperty:
                            // case PropertyBaseClass.LongTextProperty:
                            try { export[p.CodeName] = o.GetProperty(p.Id).ToString(); } catch { }
                            break;
                        case PropertyBaseClass.IntegerProperty:
                            if (p.PropertyClassId == -14) {
                                EnumerationPropertySettings enumPropSettings = (EnumerationPropertySettings)p.GetSettings(o.ClassId);
                                IntegerDataValue dv = (IntegerDataValue)o.GetDataValue(p.DataValueIdList[0]);

                                MemDefEnumeration defEnum = WAFContext.Session.Definitions.Enumeration[enumPropSettings.EnumerationTypeName];
                                if (dv.Value > 0) {
                                    export[p.CodeName] = defEnum.Values[dv.Value].GetName(WAFContext.Session);
                                } else {
                                    export[p.CodeName] = "";
                                }
                                //MemDefEnumerationValue value in o.Session.Definitions.Enumeration[s.EnumerationTypeName].Values.Values

                            } else {
                                IntegerDataValue dv = (IntegerDataValue)o.GetDataValue(p.DataValueIdList[0]);
                                export[p.CodeName] = dv.Value;
                            }
                            break;
                        default: break;
                    }
                    //customPropIds.Add(id);
                }
            }

            export["BillingForename"] = o.BillingForename;
            export["BillingSurname"] = o.BillingSurname;
            export["BillingCompany"] = o.BillingCompany;
            export["BillingAddress"] = o.BillingAddress;
            export["BillingAddress2"] = o.BillingAddress2;
            export["BillingState"] = WAFContext.Session.GetEnumName(o.BillingState);
            export["BillingZip"] = o.BillingZip;
            export["BillingCity"] = o.BillingCity;
            string billingCountry = "";
            if (o.BillingCountry.IsSet()) {
                billingCountry = o.BillingCountry.Get().Name;
            }
            export["BillingCountry"] = billingCountry;
            export["BillingMobile"] = o.BillingMobile;
            export["BillingPhone"] = o.BillingPhone;

            export["ShippingForename"] = o.ShippingForename;
            export["ShippingSurname"] = o.ShippingSurname;
            export["ShippingCompany"] = o.ShippingCompany;
            export["ShippingAddress"] = o.ShippingAddress;
            export["ShippingAddress2"] = o.ShippingAddress2;
            export["ShippingState"] = WAFContext.Session.GetEnumName(o.ShippingState);
            export["ShippingZip"] = o.ShippingZip;
            export["ShippingCity"] = o.ShippingCity;
            string shippingCountry = "";
            if (o.ShippingCountry.IsSet()) {
                shippingCountry = o.ShippingCountry.Get().Name;
            }
            export["ShippingCountry"] = shippingCountry;
            export["ShippingMobile"] = o.ShippingMobile;
            export["ShippingPhone"] = o.ShippingPhone;

            export["InvoiceNotes"] = o.InvoiceNotes;
            export["SiteId"] = o.SiteId;
            export["LCID"] = o.LCID;
            export["TemplateId"] = o.TemplateId;

            export["CreateDate"] = o.CreateDate;
            export["ChangeDate"] = o.ChangeDate;
            export["PublishDate"] = o.PublishDate;

        }
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment;filename=orders_" + DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year + "_kl_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + ".csv");
        //Response.Charset = "UTF-8";
        Response.ContentEncoding = Encoding.Default;//Encoding.GetEncoding("iso-8859-1"); //Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage); //Encoding.Default;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "text/csv";
        Response.Write(export.Export());
        Response.End();
    }
示例#51
0
        public ActionResult AsCsv(int id, bool? onlyEmail)
        {
            var leadSearch = RavenSession.Load<Core.LeadSearch>("leadsearches/" + id);

            var csvLeads = new List<CsvLead>();

            var leads = leadSearch.Leads;

            if( onlyEmail.HasValue && onlyEmail == true )
            {
                leads = leads.Where(l => l.Emails.Any()).ToList();
            }

            foreach( var lead in leads )
            {
                var csvLead = new CsvLead()
                                  {
                                      Industry = lead.PrimaryCategory,
                                      Emails = string.Join("-", lead.Emails),
                                      Name = lead.BusinessName,
                                      Website = string.Join("-", lead.Websites),
                                      ContactUsUrls = string.Join("-", lead.ContactUsUris),
                                      Street = lead.Street,
                                      City = lead.City,
                                      State = lead.State,
                                      Zip = lead.Zip
                                  };

                csvLeads.Add(csvLead);
            }

            var csv = new CsvExport<CsvLead>(csvLeads);

            return File(csv.ExportToBytes(), "text/csv", string.Format("Export-{0}.csv", DateTime.Now.ToString("yyyyMMdd-HHmmss")));
        }
    protected void ExcelClick_Click(object sender, EventArgs e)
    {
        CsvExport myExport = new CsvExport();
        //   Then you can do any of the following three output options:

        DataTableReader reader = DataBase.dbDataTable(currentViewSQL.Value).CreateDataReader();
        while (reader.Read())
        {
            myExport.AddRow();

            myExport["ResourceName"] = reader["ResourceName"].ToString().Trim();
            myExport["PasswordActive"] = reader["PasswordActive"].ToString().Trim();

        }

        reader.Close();
        myCsv = myExport.Export();

        string attachment = "attachment; filename=resource-data-" + DateTime.Now.ToShortDateString() + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.Write(myCsv);
        HttpContext.Current.Response.End();
    }
示例#53
0
    protected void ExcelClick_Click(object sender, EventArgs e)
    {
        CsvExport myExport = new CsvExport();
        //   Then you can do any of the following three output options:
        myExport.AddRow();
        myExport["Statistic"] = "Unique Visitors";
        myExport["FY" + lastYearDisplay + "(Full)"] = long.Parse(uniqueVistor_LastYearFull).ToString("N0");
        myExport["FY" + lastYearDisplay + "(to Date)"] = long.Parse(uniqueVistor_LastYeartoDate).ToString("N0");
        myExport["FY" + thisYearDisplay + "(to Date)"] = long.Parse(uniqueVistor_thisYeartoDate).ToString("N0");
        myExport["% Difference to Date"] = percentDetails_uniqueVisitor;

        myExport.AddRow();
        myExport["Statistic"] = "Number of Hits";
        myExport["FY" + lastYearDisplay + "(Full)"] = long.Parse(NumberofHits_LastYearFull).ToString("N0");
        myExport["FY" + lastYearDisplay + "(to Date)"] = long.Parse(NumberofHits_LastYeartoDate).ToString("N0");
        myExport["FY" + thisYearDisplay + "(to Date)"] = long.Parse(NumberofHits_thisYeartoDate).ToString("N0");
        myExport["% Difference to Date"] = percentDetails_NumberofHits;

        myCsv = myExport.Export();

        string attachment = "attachment; filename=uniqueVisitors-data-" + DateTime.Now.ToShortDateString() + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.Write(myCsv);
        HttpContext.Current.Response.End();
    }
示例#54
0
    protected void ExcelClick_Click(object sender, EventArgs e)
    {
        CsvExport myExport = new CsvExport();
        //   Then you can do any of the following three output options:

        DataTableReader reader = DataBase.dbDataTable(currentViewSQL.Value).CreateDataReader();
        while (reader.Read())
        {
            myExport.AddRow();
            string pindb = reader["UserPIN"].ToString().Trim();
            //Dictionary<string, string> uDetails = loginSSA.GetUsersDetails(pindb);
            myExport["LastName"] = reader["UserLastName"].ToString().Trim(); //uDetails["LastName"];
            myExport["FirstName"] = reader["UserFirstName"].ToString().Trim(); //uDetails["FirstName"];
            myExport["Email"] = reader["UserEmail"].ToString().Trim(); //uDetails["Email"];
            myExport["PIN"] = pindb;
            myExport["officeCode"] = reader["UserofficeCode"].ToString().Trim(); //uDetails["OfficeCode"];
        }

        reader.Close();
        myCsv = myExport.Export();

        string attachment = "attachment; filename=resource-data-" + DateTime.Now.ToShortDateString() + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.Write(myCsv);
        HttpContext.Current.Response.End();
    }
 private void ExportToCSVFile()
 {
     var csv = new CsvExport<BoardItem>(DashBoardItems.ToList());
     csv.ExportToFile("myexportresult.csv");
 }
示例#56
0
        public static void printCSVResults(Dictionary<String, List<Result>> results, String filename, String pathToTrim)
        {
            var csvExport = new CsvExport();

            foreach (KeyValuePair<String, List<Result>> pair in results)
            {
                foreach (Result result in pair.Value)
                {
                    csvExport.AddRow();
                    csvExport["Controller"] = pair.Key.Replace(pathToTrim, "");
                    csvExport["Method Name"] = result.MethodName;
                    csvExport["Route"] = result.Route;
                    csvExport["HTTP Method"] = string.Join(", ", result.HttpMethods.ToArray());
                    csvExport["Attributes"] = string.Join(", ", result.Attributes.ToArray());
                }
            }

            File.Create(filename).Dispose();
            csvExport.ExportToFile(filename);
            Console.WriteLine("CSV output written to: " + filename);
        }
示例#57
0
    protected void ExcelClick_Click(object sender, EventArgs e)
    {
        CsvExport myExport = new CsvExport();
        //   Then you can do any of the following three output options:

        DataTableReader reader = DataBase.dbDataTable(currentViewSQL).CreateDataReader();
        while (reader.Read())
        {
            myExport.AddRow();
            string resourceID = reader["ResourceToAccess"].ToString().Trim();
            myExport["Date"] = reader["SubmissionDateandTime"].ToString().Trim();
            myExport["Requestor"] = getResourceRequestsAdminUsers(resourceID);
            myExport["Assignted To"] = getUserNameByPIN(reader["SubmittedByPIN"].ToString().Trim());
            myExport["Status"] = reader["FormStatus"].ToString().Trim();

        }

        reader.Close();
        myCsv = myExport.Export();

        string attachment = "attachment; filename=resource-data-" + DateTime.Now.ToShortDateString() + ".csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");
        HttpContext.Current.Response.Write(myCsv);
        HttpContext.Current.Response.End();
    }
示例#58
0
    protected void btnExportProductsData_Click(object sender, EventArgs e)
    {
        List<ProductBase> products = WAFContext.Session.Query<ProductBase>().Where(AqlProductBase.SiteId == WAFContext.Session.SiteId).Where(AqlProductBase.IsDerived == false).OrderBy(AqlProductBase.Name).Execute();
        CsvExport export = new CsvExport();
        foreach (ProductBase p in products) {
            export.AddRow();
            export["Name"] = p.Name;
            export["NodeId"] = p.NodeId;
            export["SiteId"] = p.SiteId;
            export["LCID"] = p.LCID;
            export["TemplateId"] = p.TemplateId;
            export["ItemNumber"] = p.ItemNumber;
            export["NumberInStock"] = p.NumberInStock;
            export["PriceExVat"] = p.PriceExVat;
            export["ShippingCost"] = p.ShippingCost;
            export["Currency1PriceExVat"] = p.Currency1PriceExVat;
            export["Currency2PriceExVat"] = p.Currency2PriceExVat;
            export["Currency3PriceExVat"] = p.Currency3PriceExVat;
            export["Currency4PriceExVat"] = p.Currency4PriceExVat;
            export["Currency5PriceExVat"] = p.Currency5PriceExVat;
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();

        Response.AddHeader("content-disposition", "attachment;filename=products_" + DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year + ".csv");
        Response.ContentEncoding = Encoding.Default;//Encoding.GetEncoding("iso-8859-1"); //Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage); //Encoding.Default;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "text/csv";
        Response.Write(export.Export());
        Response.End();
    }
示例#59
0
	void Start(){
		controller = new Controller();
		export = new CsvExport();
	}
示例#60
0
    protected void btnExport_Click(object sender, EventArgs e)
    {
        int reportType = Utils.GetIntegerOnly(ddlReportType.SelectedValue);
        CsvExport export = new CsvExport();
        string fileName = "export";
        if(reportType==0){
            //Sales summary
            QueryData qd = GetSalesSummaryQuery();
            UniqueList<string> values = lstSalesSummary.GetAllValues();
            //IAqlQuery
            IAqlQuery q = new DataQuery(qd);
            List<string> fieldNames = q.GetFieldNames();
            AqlResultSet rs = q.Execute(true);
            while(rs.Read()){
                export.AddRow();
                export[fieldNames[0]] = rs[0]; //Period
                export[fieldNames[1]] = rs[1]; //Number of orders
                export[fieldNames[2]] = rs[2]; //Total revenue
                export[fieldNames[3]] = rs[3]; // Average order value
                export[fieldNames[4]] = rs[4]; //biggest order
                int mostSoldProductRevenue = Utils.GetIntegerOnly(rs[5].ToString());
                if (mostSoldProductRevenue > 0) {
                    ProductBase pMostSoldRevenue = WAFContext.Session.GetContent<ProductBase>(mostSoldProductRevenue);
                    export[fieldNames[5]] = pMostSoldRevenue.Name + " (" + mostSoldProductRevenue + ")"; //MostPopularProductRevenue
                } else {
                    export[fieldNames[5]] = "";
                }
                int mostSoldProductNumItems = Utils.GetIntegerOnly(rs[5].ToString());
                if (mostSoldProductNumItems > 0) {
                    ProductBase pMostSoldItems = WAFContext.Session.GetContent<ProductBase>(mostSoldProductNumItems);
                    export[fieldNames[6]] = pMostSoldItems.Name + " (" + mostSoldProductNumItems + ")"; //MostPopularProductNumItems
                } else {
                    export[fieldNames[6]] = "";
                }
            }
            fileName = "sales_summary";
        }else if(reportType ==1){
            //Sales over time
            AqlQuery q = null;
            if (txtStartDate.Text.Length > 0) {
                DateTime startDT = DateTime.Parse(txtStartDate.Text);
                DateTime endDT = DateTime.Now;
                if (txtEndDate.Text.Length > 0) {
                    endDT = DateTime.Parse(txtEndDate.Text);
                }
                ReportPeriod period = new ReportPeriod();
                period.FromDate = startDT;
                period.ToDate = endDT;
               q  = WebshopStatistics.GetGroupSalesData(period, GetDateTimePart());
            } else {
               q = WebshopStatistics.GetGroupSalesData(this.GetReportPeriod(DefaultReportPeriod.AllTime), GetDateTimePart());
            }
            List<string> fieldNames = q.GetFieldNames();
            AqlResultSet rs = q.Execute(true);
            while (rs.Read()) {
                export.AddRow();
                export["Period"] = GetPeriodDescription(Utils.GetIntegerOnly(rs[0]), Utils.GetIntegerOnly(rs[3])); //DateTimePart
                export["Revenue in period"] = ((double)rs[1]).ToString("N2"); //Revenue
                export["Number of orders in period"] = rs[2]; //NumOrders
            }
            fileName = "sales_over_time";
        }else if(reportType == 2){
            //stock list
            AqlQuery q = null;
            if (txtStartDate.Text.Length > 0) {
                DateTime startDT = DateTime.Parse(txtStartDate.Text);
                DateTime endDT = DateTime.Now;
                if (txtEndDate.Text.Length > 0) {
                    endDT = DateTime.Parse(txtEndDate.Text);
                }
                ReportPeriod period = new ReportPeriod();
                period.FromDate = startDT;
                period.ToDate = endDT;
                q = WebshopStatistics.GetProductStockReportData(period, null);
            } else {
               q = WebshopStatistics.GetProductStockReportData(this.GetReportPeriod(DefaultReportPeriod.AllTime), null);
            }
            List<string> fieldNames = q.GetFieldNames();
            AqlResultSet rs = q.Execute(true);
            while (rs.Read()) {
                export.AddRow();
                export["NodeId"] = rs[0];
                export["Item number"] = rs[1];
                export["Product name"] = rs[2];
                export["Number in stock"] = rs[3];
            }
            fileName = "stock_list";
        }else if(reportType == 3){
            //product sales report
            AqlQuery q = null;
            if (txtStartDate.Text.Length > 0) {
                DateTime startDT = DateTime.Parse(txtStartDate.Text);
                DateTime endDT = DateTime.Now;
                if (txtEndDate.Text.Length > 0) {
                    endDT = DateTime.Parse(txtEndDate.Text);
                }
                ReportPeriod period = new ReportPeriod();
                period.FromDate = startDT;
                period.ToDate = endDT;
                q = WebshopStatistics.GetProductSalesData(period, null);
            } else {
                q = WebshopStatistics.GetProductSalesData(this.GetReportPeriod(DefaultReportPeriod.AllTime), null);
            }
            List<string> fieldNames = q.GetFieldNames();
            q.IncludeUnpublished = true;
            AqlResultSet rs = q.Execute(true);
            while (rs.Read()) {
                export.AddRow();
                export["NodeId"] = rs[0];
                export["Item number"] = rs[1];
                export["Product name"] = rs[2];
                export["Numberof items sold"] = rs[3];
                export["Revenue"] = rs[4];
                export["Last sale"] = rs[5];
                export["First sale"] = rs[6];
            }
            fileName = "products";
        }else if(reportType == 4){
            //customers

            fileName = "customers";
        }
        //foreach (ProductBase p in products) {
        //    export.AddRow();
        //    export["Name"] = p.Name;
        //    export["NodeId"] = p.NodeId;
        //    export["SiteId"] = p.SiteId;
        //    export["Currency5PriceExVat"] = p.Currency5PriceExVat;
        //}
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment;filename="+fileName+"_" + DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year + ".csv");
        //Response.Charset = "UTF-8";
        Response.ContentEncoding = Encoding.Default;//Encoding.GetEncoding("iso-8859-1"); //Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage); //Encoding.Default;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "text/csv";
        Response.Write(export.Export());
        Response.End();
    }