Exemplo n.º 1
0
        /// <summary>
        /// File handler demo for classic Asp.Net or HTML.
        /// To access it in an Javascript ajax request use: <code>var url = "/Handler/FileHandler.ashx";</code>.
        /// </summary>
        /// <remarks>
        /// NOTE. Edit the web.config file to allow the DELETE method in the system.webServer.handlers section
        /// </remarks>
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            try
            {
                // Wrap the request into a HttpRequestBase type
                HttpRequestBase request = new HttpRequestWrapper(context.Request);


                // Create and initialize the handler
                IFileHandler handler = Backload.FileHandler.Create();
                handler.Init(request);


                // Call the execution pipeline and get the result
                IBackloadResult result = await handler.Execute();


                // Write result to the response and flush
                ResultCreator.Write(context.Response, result);
                context.Response.Flush();
            }
            catch
            {
                context.Response.StatusCode = 500;
            }
        }
 public void ShouldReturnNullIfAtEnd()
 {
     var result = ResultCreator.CreateResult(1);
     result.Take(1).ToList();
     var record = result.Peek();
     record.Should().BeNull();
 }
Exemplo n.º 3
0
        public async Task <ActionResult> FileHandler()
        {
            try
            {
                // Create and initialize the handler
                IFileHandler handler = Backload.FileHandler.Create();


                // Attach event handlers to events
                handler.Events.IncomingRequestStarted  += Events_IncomingRequestStarted;
                handler.Events.GetFilesRequestStarted  += Events_GetFilesRequestStarted;
                handler.Events.GetFilesRequestFinished += Events_GetFilesRequestFinished;


                // Init Backloads execution environment and execute the request
                handler.Init(HttpContext.Request);
                IBackloadResult result = await handler.Execute();


                // Helper to create an ActionResult object from the IBackloadResult instance
                return(ResultCreator.Create(result));
            }
            catch
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 4
0
        private void Generate(CommandType commandType)
        {
            try
            {
                Cursor         = Cursors.WaitCursor;
                txtResult.Text = string.Empty;
                SaveSettings();

                var fileRows = ParseDataContent(chkFirstLineHoldsColumnNames.Checked);

                var result = ResultCreator.GetResult(commandType, fileRows, MappedColumns, cboTableNameTarget.Text);
                txtResult.Text      = result;
                lblResultCount.Text = $"{txtResult.ActiveTextAreaControl.TextArea.Document.TotalNumberOfLines} records generated at {DateTime.Now.ToString("HH:mm:ss")}";
                SetShowState();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Generate", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
                txtResult.Refresh();
            }
        }
 public void ShouldConsumeAllRecords()
 {
     var result = ResultCreator.CreateResult(0, 3);
     result.Consume();
     result.Count().Should().Be(0);
     result.Peek().Should().BeNull();
 }
Exemplo n.º 6
0
        public async Task <ActionResult> Upload()
        {
            try
            {
                IFileHandler handler = Backload.FileHandler.Create();

                using (var provider = new BackloadDataProvider(this.Request))
                {
                    var name = provider.Files[0].FileName;
                    provider.Files[0].FileName = string.Format("{0}.{1}", Guid.NewGuid(), "xlsx");

                    handler.Init(provider);
                    IBackloadResult result = await handler.Execute();

                    result.ContentType = "Content-Type: application/json; charset=utf-8";

                    return(ResultCreator.Create(result));
                }
            }
            catch (Exception ex)
            {
                MvcApplication.log.Error(ex, "Не удалось загрузить файл контактов");
            }

            return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
        }
            public void ShouldReturnNextRecordWithoutMovingCurrentRecord()
            {
                var result = ResultCreator.CreateResult(1);
                var record = result.Peek();
                record.Should().NotBeNull();

                result.GetEnumerator().Current.Should().BeNull();
            }
            public void ShouldReturnRecordIfSingle()
            {
                var result = ResultCreator.CreateResult(1);
                var record = result.Single();

                record.Should().NotBeNull();
                record.Keys.Count.Should().Be(1);
            }
            public void ShouldGetTheFirstRecordAndMoveToNextPosition()
            {
                var result = ResultCreator.CreateResult(1, 3);
                var record = result.First();
                record[0].ValueAs<string>().Should().Be("record0:key0");

                record = result.First();
                record[0].ValueAs<string>().Should().Be("record1:key0");
            }
            public void ShouldThrowNoExceptionWhenCallingMultipleTimes()
            {
                var result = ResultCreator.CreateResult(1);

                result.Consume();
                var ex = Xunit.Record.Exception(() => result.Consume());

                ex.Should().BeNull();
            }
            public void ShouldThrowInvalidOperationExceptionIfMoreThanOneRecordFound()
            {
                var result = ResultCreator.CreateResult(1, 2);
                var ex     = Xunit.Record.Exception(() => result.Single());

                ex.Should().BeOfType <InvalidOperationException>();
                // INFO: Changed message because use of Enumerable.Single for simpler implementation
                ex.Message.Should().Be("Sequence contains more than one element");
            }
Exemplo n.º 12
0
            public void ShouldConsumeRecordCorrectly()
            {
                var result = ResultCreator.CreateResult(1, 3);

                result.Consume();
                result.Count().Should().Be(0); // the records left after consume

                result.GetEnumerator().Current.Should().BeNull();
                result.GetEnumerator().MoveNext().Should().BeFalse();
            }
            public void ShouldCallGetSummaryWhenGetSummaryIsNotNull()
            {
                bool getSummaryCalled = false;
                var  result           = ResultCreator.CreateResult(1, 0, () => { getSummaryCalled = true; return(null); });

                // ReSharper disable once UnusedVariable
                var summary = result.Summary;

                getSummaryCalled.Should().BeTrue();
            }
            public void ShouldThrowInvalidOperationExceptionWhenNotAtEnd()
            {
                var result = ResultCreator.CreateResult(1);

                result.AtEnd.Should().BeFalse();

                var ex = Xunit.Record.Exception(() => result.Summary);

                ex.Should().BeOfType <InvalidOperationException>();
            }
            public void ShouldReturnExistingSummaryWhenSummaryHasBeenRetrieved()
            {
                int getSummaryCalled = 0;
                var result = ResultCreator.CreateResult(1, 0, () => { getSummaryCalled++; return new FakeSummary(); });

                // ReSharper disable once NotAccessedVariable
                var summary = result.Summary;
                // ReSharper disable once RedundantAssignment
                summary = result.Summary;
                getSummaryCalled.Should().Be(1);
            }
Exemplo n.º 16
0
            public void ShouldAlwaysAdvanceRecordPosition()
            {
                var result     = ResultCreator.CreateResult(1, 3);
                var enumerable = result.Take(1);
                var records    = result.Take(2).ToList();

                records[0][0].As <string>().Should().Be("record0:key0");
                records[1][0].As <string>().Should().Be("record1:key0");

                records = enumerable.ToList();
                records[0][0].As <string>().Should().Be("record2:key0");
            }
            public void ShouldThrowInvalidOperationExceptionIfNotTheFistRecord()
            {
                var result     = ResultCreator.CreateResult(1, 2);
                var enumerator = result.GetEnumerator();

                enumerator.MoveNext().Should().BeTrue();
                enumerator.Current.Should().NotBeNull();

                var ex = Xunit.Record.Exception(() => result.Single());

                ex.Should().BeOfType <InvalidOperationException>();
                ex.Message.Should().Be("The first record is already consumed.");
            }
            public void ShouldConsumeSummaryCorrectly()
            {
                int getSummaryCalled = 0;
                var result           = ResultCreator.CreateResult(1, 0, () => { getSummaryCalled++; return(new FakeSummary()); });


                result.Consume();
                getSummaryCalled.Should().Be(1);

                // the same if we call it multiple times
                result.Consume();
                getSummaryCalled.Should().Be(1);
            }
        public async Task <ActionResult> FileHandler()
        {
            try
            {
                IFileHandler handler = Backload.FileHandler.Create();
                handler.Init(HttpContext.Request);

                IBackloadResult result = await handler.Execute(false);

                return(ResultCreator.Create(result));
            }
            catch
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 20
0
        public async Task <ActionResult> Upload()
        {
            try
            {
                IFileHandler handler = Backload.FileHandler.Create();

                handler.Events.IncomingRequestStarted += Events_IncomingRequestStarted;

                handler.Init(this.HttpContext, _hosting);
                IBackloadResult result = await handler.Execute();

                return(ResultCreator.Create(result));
            }
            catch
            {
                return(new StatusCodeResult((int)HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 21
0
        public async Task <ActionResult> FileHandler()
        {
            IBackloadResult result = null;
            IFileStatus     status = null;

            try
            {
                // Create and initialize the handler
                IFileHandler handler = Backload.FileHandler.Create();
                handler.Init(HttpContext.Request);


                // This demo calls high level API methods.
                // Http methhod related API methods are in handler.Services.[HttpMethod].
                // Low level API methods are in handler.Services.Core
                if (handler.Context.HttpMethod == "GET")
                {
                    status = await handler.Services.GET.Execute();
                }
                else if (handler.Context.HttpMethod == "POST")
                {
                    status = await handler.Services.POST.Execute();
                }
                else if (handler.Context.HttpMethod == "DELETE")
                {
                    status = await handler.Services.DELETE.Execute();
                }


                // Create a client plugin specific result.
                // In this example we could simply call CreateResult(), because handler.FilesStatus also has the IFileStatus object
                result = handler.Services.Core.CreatePluginResult(status, Backload.Contracts.Context.Config.PluginType.JQueryFileUpload);


                // Helper to create an ActionResult object from the IBackloadResult instance
                return(ResultCreator.Create(result));
            }
            catch
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 22
0
        // Executes DELETE requsts
        private async Task <ActionResult> DeleteHandler(IFileHandler handler)
        {
            // Get the file to delete
            handler.FileStatus = handler.Services.DELETE.GetRequestStatus();
            IFileStatusItem file = handler.FileStatus.Files[0];

            using (FilesModel db = new FilesModel())
            {
                Guid id = Guid.Parse(file.FileName);

                File f = db.Files.Find(id);
                db.Files.Remove(f);
                await db.SaveChangesAsync();
            }

            // Create client plugin specific result and return an ActionResult
            IBackloadResult result = handler.Services.Core.CreatePluginResult();

            return(ResultCreator.Create((IFileStatusResult)result));
        }
Exemplo n.º 23
0
        public ActionResult FileHandler()
        {
            try
            {
                // Create and initialize the handler
                IFileHandler handler = Backload.FileHandler.Create();
                handler.Init(HttpContext.Request);


                // Call the execution pipeline and get the result
                IBackloadResult result = handler.Execute();


                // Helper to create an ActionResult object from the IBackloadResult instance
                return(ResultCreator.Create(result));
            }
            catch
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 24
0
        // Executes GET requsts for all files
        private static ActionResult GetHandler(IFileHandler handler)
        {
            IFileStatus status = new FileStatus();

            using (FilesModel db = new FilesModel())
            {
                foreach (var row in db.Files)
                {
                    string url = handler.Context.Request.Url.OriginalString + "?fileName=" + row.Id.ToString();

                    IFileStatusItem file = new FileStatusItem()
                    {
                        ContentType  = row.Type,
                        DeleteType   = "DELETE",
                        FileName     = row.Name,
                        FileSize     = row.Size,
                        OriginalName = row.Original,
                        Progress     = "100",
                        Success      = true,
                        ThumbnailUrl = row.Preview,

                        // Set an identifier for GET and DELETE requests
                        DeleteUrl = url,
                        FileUrl   = url
                    };

                    status.Files.Add(file);
                }
            }

            handler.FileStatus = status;

            // Create client plugin specific result and return an ActionResult
            IBackloadResult result = handler.Services.Core.CreatePluginResult();

            return(ResultCreator.Create((IFileStatusResult)result));
        }
            public void ShouldReturnNullWhenGetSummaryIsNull()
            {
                var result = ResultCreator.CreateResult(1, 0);

                result.Summary.Should().BeNull();
            }
Exemplo n.º 26
0
        private void GenerateDatabase()
        {
            var skippedKeys = new[] { "dtproperties", "sandeslatt_user", "LogItem", "WebStat", "Log", "Song" };

            try
            {
                Cursor         = Cursors.WaitCursor;
                txtResult.Text = string.Empty;
                SaveSettings();

                var count      = 0;
                var tableNames = SqlParser.GetTablesOrderedForInsert(cboConnectionSource.SelectedValue.ToString());

                // DELETE
                txtResult.Text += "-- First clear all tables in reverse order" + Environment.NewLine;
                for (var i = tableNames.Count - 1; i >= 0; i--)
                {
                    var tableName = tableNames[i];
                    if (tableName.ContainsAny(skippedKeys))
                    {
                        txtResult.Text += $"-- Skipped {tableName}" + Environment.NewLine;
                    }
                    else
                    {
                        txtResult.Text += $"DELETE FROM {tableName}" + Environment.NewLine;
                    }
                }
                txtResult.Text += Environment.NewLine + Environment.NewLine;


                // INSERT
                foreach (var tableName in tableNames)
                {
                    var fileRows = SqlParser.GetValues(cboConnectionSource.SelectedValue.ToString(), tableName, "");
                    if (tableName.ContainsAny(skippedKeys))
                    {
                        txtResult.Text += $"-- Table {tableName} skipped" + Environment.NewLine;
                        continue;
                    }

                    // Create column structs to satisfy ResultCreator
                    var sqlColumns    = SqlParser.GetColumns(cboConnectionTarget.SelectedValue.ToString(), tableName);
                    var mappedColumns = sqlColumns.Select((x, i) => new ColumnMap(x, new List <FileColumn>()
                    {
                        new FileColumn {
                            Index = i, Name = x.ColumnName
                        }
                    })).ToList();
                    var hasIdentity = sqlColumns.Any(x => x.IsIdentity);

                    // Print result
                    var result = ResultCreator.GetResult(CommandType.Insert, fileRows, mappedColumns, tableName);
                    if (hasIdentity)
                    {
                        txtResult.Text += $"SET IDENTITY_INSERT {tableName} ON;" + Environment.NewLine;
                        txtResult.Text += result + Environment.NewLine;
                        txtResult.Text += $"SET IDENTITY_INSERT {tableName} OFF;" + Environment.NewLine + Environment.NewLine;
                    }
                    else
                    {
                        txtResult.Text += result + Environment.NewLine + Environment.NewLine;
                    }

                    count += fileRows.Count;
                }
                lblResultCount.Text = $"{count} records generated at {DateTime.Now.ToString("HH:mm:ss")}";
                SetShowState();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Generate", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
                txtResult.Refresh();
            }
        }
Exemplo n.º 27
0
        // Executes POST requsts
        private async Task <ActionResult> PostHandler(IFileHandler handler)
        {
            // Get the posted file with meta data from the request
            handler.FileStatus = await handler.Services.POST.GetPostedFiles();

            if (handler.FileStatus != null)
            {
                Guid            id   = Guid.NewGuid();
                IFileStatusItem file = handler.FileStatus.Files[0];


                // Read the file data (bytes)
                byte[] data = null;
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream((int)file.FileSize))
                {
                    await file.FileStream.CopyToAsync(stream);

                    data = stream.ToArray();
                }


                // Create the thumbnail
                await handler.Services.POST.CreateThumbnail(file);

                // Create a base64 encoded data url for the thumbnail we can return in Json
                await handler.Services.Core.CreateThumbnailDataUrls();


                // This will change the url query parameter fileName to the id of the
                // new table row, so we can identify the file in a DELETE and GET request
                file.FileUrl   = file.DeleteUrl.Replace(file.FileName, id.ToString());
                file.DeleteUrl = file.FileUrl;


                // Store to db
                using (FilesModel db = new FilesModel())
                {
                    // File entity represents a table row
                    File row = new File()
                    {
                        Id         = id,
                        Data       = data,
                        Name       = file.FileName,
                        Original   = file.OriginalName,
                        Size       = file.FileSize,
                        Type       = file.ContentType,
                        UploadTime = DateTime.Now,
                        Preview    = file.ThumbnailUrl
                    };

                    File f = db.Files.Add(row);
                    await db.SaveChangesAsync();
                };
            }


            // Create client plugin specific result and return an ActionResult
            IBackloadResult result = handler.Services.Core.CreatePluginResult();

            return(ResultCreator.Create((IFileStatusResult)result));
        }