Skip to content

Commit

Permalink
Merge pull request #44 from RemmSoft/feature/Core-43
Browse files Browse the repository at this point in the history
#43 : File service done.
  • Loading branch information
tanser authored Oct 7, 2017
2 parents cfb8f8c + 08762aa commit d6b1281
Show file tree
Hide file tree
Showing 18 changed files with 589 additions and 13 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ bld/
[Oo]bj/
[Ll]og/

# Upload folder has been removed from the git directory.
/RS.Core.Api/App_Data/Upload

# VS Code Workspace config file
.vscode/settings.json

Expand Down
154 changes: 154 additions & 0 deletions RS.Core.Api/Controllers/File/FileController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
using RS.Core.Const;
using RS.Core.Service;
using RS.Core.Service.DTOs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Hosting;
using System.Web.Http;
using System.Web.Http.Description;

namespace RS.Core.Controllers
{
[Authorize]
[RoutePrefix("api/File")]
public class FileController : ApiController
{
IFileService fileService = null;
public FileController(IFileService _fileService)
{
fileService = _fileService;
}

[Route("Upload"), HttpPost]
public async Task<IHttpActionResult> Upload(Guid refID,string screenCode)
{
#region Condition

/// Checks whether the parameters are null.
if (refID == null || screenCode == null)
return BadRequest(Messages.FUE0002);

/// Controls whether the screen code is in the <see cref="ScreenCodes"/> class.
if (!typeof(ScreenCodes).GetFields().Any(x => x.Name == screenCode))
return BadRequest(Messages.GNW0002);

/// Checks the media type for the file-s to be uploaded.
if (!Request.Content.IsMimeMultipartContent())
return Content(HttpStatusCode.UnsupportedMediaType, Messages.FUW0001);
#endregion

/// `localPath` and `useCloud` is get from Web.Config.
string localPath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["fileServiceLocalPath"]);
bool useCloud = Convert.ToBoolean(ConfigurationManager.AppSettings["useCloud"]);

var provider = new MultipartFormDataStreamProvider(localPath);

try
{
/// Loads the files into the local storage.
await Request.Content.ReadAsMultipartAsync(provider);

/// Check is exist valid file.
if (provider.FileData.Count == 0)
return BadRequest(Messages.FUE0001);

IList<FileDto> modelList = new List<FileDto>();

foreach (MultipartFileData file in provider.FileData)
{
string originalName = file.Headers.ContentDisposition.FileName;
if (originalName.StartsWith("\"") && originalName.EndsWith("\""))
{
originalName = originalName.Trim('"');
}
if (originalName.Contains(@"/") || originalName.Contains(@"\"))
{
originalName = Path.GetFileName(originalName);
}

FileDto fileDto = new FileDto
{
RefID = refID,
ScreenCode = screenCode,
OriginalName = Path.GetFileNameWithoutExtension(originalName),
StorageName = Path.GetFileName(file.LocalFileName),
Extension = Path.GetExtension(originalName).ToLower(),
Size = new FileInfo(file.LocalFileName).Length
};

modelList.Add(fileDto);
}

if (useCloud)
await fileService.SendCloud(modelList,localPath);

await fileService.Add(modelList, IdentityClaimsValues.UserID<Guid>());

return Ok(Messages.Ok);
}
catch (Exception exMessage)
{
return Content(HttpStatusCode.InternalServerError, exMessage);
}
}

[Route("Download"), HttpGet]
public async Task<IHttpActionResult> Download(Guid id)
{
var model = await fileService.GetByID(id);

if (model == null)
return BadRequest(Messages.GNE0001);

/// `localPath` is get from Web.Config.
string localPath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["fileServiceLocalPath"]);

string root = localPath + "\\" + model.StorageName;

byte[] fileData = File.ReadAllBytes(root);
var stream = new MemoryStream(fileData, 0, fileData.Length);

var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};

response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = model.OriginalName + "." + model.Extension,
Size=model.Size
};

response.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");

IHttpActionResult result = ResponseMessage(response);
return result;
}

[Route("Get"), HttpGet]
[ResponseType(typeof(IEnumerable<FileListDto>))]
public async Task<IHttpActionResult> GetList(Guid refID, string screenCode)
{
/// Controls whether the screen code is in the <see cref="ScreenCodes"/> class.
if (!typeof(ScreenCodes).GetFields().Any(x => x.Name == screenCode))
return BadRequest(Messages.GNW0002);

var result = await fileService.GetList(refID,screenCode);

if (result == null || result.Count <= 0)
result = new List<FileListDto>();

return Ok(result);
}

}
}
3 changes: 2 additions & 1 deletion RS.Core.Api/RS.Core.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@
<Compile Include="Areas\HelpPage\SampleGeneration\TextSample.cs" />
<Compile Include="Areas\HelpPage\XmlDocumentationProvider.cs" />
<Compile Include="Base\Controller\BaseController.cs" />
<Compile Include="Controllers\File\FileController.cs" />
<Compile Include="Controllers\Account\AccountController.cs" />
<Compile Include="Base\Identity\IdentityClaimsValues.cs" />
<Compile Include="Controllers\AutoCode\AutoCodeController.cs" />
Expand Down Expand Up @@ -360,7 +361,7 @@
<Content Include="Scripts\jquery-3.1.1.min.map" />
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
<Folder Include="App_Data\Upload\" />
</ItemGroup>
<ItemGroup>
<Content Include="packages.config" />
Expand Down
10 changes: 10 additions & 0 deletions RS.Core.Api/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,17 @@
<add name="RSCoreDBContext" connectionString="Data Source=.;Initial Catalog=RSCore_Develop;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<!--User Service-->
<add key="resetPasswordUrl" value="http://MyProject/Account/ResetPasswordScreen.com"/>

<!--FileController-->
<add key="fileServiceLocalPath" value="~/App_Data/Upload"/>
<add key="fileServiceStoragePath" value="fooFtpAddress"/>
<add key="useCloud" value="false"/>

<!--FileService-->
<add key="ftpUserName" value="fooUserName"/>
<add key="ftpPassword" value="fooPass"/>
</appSettings>
<!--
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.
Expand Down
42 changes: 36 additions & 6 deletions RS.Core.Const/Messages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ public static class Messages
/// - Status Code: Unauthorized
/// </summary>
public static string GNW0001 = "GNW0001";

/// <summary>
/// İlgili ekran kodu bulunamadı.
/// - Status Code: NotFound
/// </summary>
public static string GNW0002 = "GNW0002";
#endregion Warning

#endregion General
Expand All @@ -72,19 +78,43 @@ public static class Messages
#region AutoCode

#region Warning
/// <summary>
/// İlgili ekran kodu bulunamadı.
/// - Status Code: NotFound
/// </summary>
public static string ACW0001 = "ACW0001";

/// <summary>
/// Kod formatının içine, otomatik artan kod numarasının eklenebilmesi için {0} yazılmalıdır.
/// - Status Code: NotAcceptable
/// </summary>
public static string ACW0002 = "ACW0002";
public static string ACW0001 = "ACW0001";
#endregion Warning

#endregion AutoCode

///Modul kodu : 'FU'
#region FileUpload

#region Error
/// <summary>
/// Dosya bulunamadı.
/// - Status Code: NotFound
/// </summary>
public static string FUE0001 = "FUE0001";

/// <summary>
/// screenCode ve refID alanı boş geçilemez.
/// - Status Code: BadRequest
/// </summary>
public static string FUE0002 = "FUE0002";

#endregion Error

#region Warning
/// <summary>
/// Desteklenmeyen dosya türü.
/// - Status Code: UnsupportedMediaType
/// </summary>
public static string FUW0001 = "FUW0001";

#endregion Warning

#endregion
}
}
29 changes: 29 additions & 0 deletions RS.Core.Data/Migrations/201710060826502_File-Migration.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions RS.Core.Data/Migrations/201710060826502_File-Migration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
namespace RS.Core.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;

public partial class FileMigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.File",
c => new
{
ID = c.Guid(nullable: false),
RefID = c.Guid(nullable: false),
ScreenCode = c.String(nullable: false, maxLength: 5),
OriginalName = c.String(nullable: false, maxLength: 30),
StorageName = c.String(nullable: false, maxLength: 50),
Extension = c.String(nullable: false, maxLength: 10),
Size = c.Long(),
CreateDT = c.DateTime(nullable: false),
UpdateDT = c.DateTime(),
CreateBy = c.Guid(nullable: false),
UpdateBy = c.Guid(),
IsDeleted = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.ID);

}

public override void Down()
{
DropTable("dbo.File");
}
}
}
Loading

0 comments on commit d6b1281

Please sign in to comment.