Skip to main content

Code Example Zip File Extraction and Download in dotnet core api

using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
using System.Dynamic;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata;
using System.Text;
using System.Runtime.CompilerServices;
using System.Net.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MovejobtoWms.Models;
using System.IO;
using System.Net;
using Microsoft.AspNetCore.Authorization;
using System.IO.Compression;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using System.Text.Json;
using Newtonsoft.Json.Linq;
using MovejobtoWms.Helpers;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
namespace MovejobtoWms.Controllers
{
    // [Authorize(AuthenticationSchemes = "CustomAuthentication")]
    [Route("api/[controller]/{action}")]
    [ApiController]
    public class MoveJobtoWmsController : ControllerBase
    {
        [DllImport("advapi32.dll"SetLastError = trueCharSet = CharSet.Unicode)]
        public static extern bool LogonUser(
      string lpszUsernamestring lpszDomain,
      string lpszPasswordint dwLogonType,
      int dwLogonProviderout SafeAccessTokenHandle phToken
      );
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;


        HttpClient client = new HttpClient();

        int activityid = 0;
        int stageid = 0;
        private readonly MoveJobContext _context;
        //private IUserService _userService;
        private readonly IConfiguration _configuration;
        public MoveJobtoWmsController(MoveJobContext contextIConfiguration configuration)
        {
            _context = context;
            _configuration = configuration;

            //   _userService = userService;

        }


        // POST: api/MoveJobtoWms/
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.

        [HttpPost]
        [Consumes(MediaTypeNames.Application.Json)]
        [ProducesResponseType(201)]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]
        [ProducesResponseType(401)]

        public async Task<IActionResultUpdatingActivityDetail([FromBody]JsonElement id)
        {
            string DownloadDirectory = _configuration.GetSection("DownloadPath").Value.Replace("/""\\");

            var responsedetail = new Response();
            string sCaptureError = "";

            client.BaseAddress = new Uri(_configuration.GetSection("Uri").Value);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("clientid",  _configuration.GetSection("ClientId").Value);
            client.DefaultRequestHeaders.Add("apikey",  _configuration.GetSection("apiKey").Value);
            var data = id.ToString();

            JObject jObject = JObject.Parse(data);
            string value = (string)jObject.SelectToken("id");
            var ids = "{\n\t\"ids\":[" + value + "]\n}".ToString();
            var response = client.PostAsync(_configuration.GetSection("GetActivityFiles").Valuenew StringContent(dataEncoding.UTF8"application/json")).Result;

            if (response.IsSuccessStatusCode)
            {
                responsedetail = await response.Content.ReadAsAsync<Response>();
            }

            if (responsedetail.is_success)
            {
                if (responsedetail.data.CustomerId == 5)

                {
                    //adding Activity and Stage Detail for abovedotne Workflow ID's Enabling Pdf Creation Acitivity in Copy Editing Stage
                    stageid = 796;
                    activityid = 6131;
                    string filename = responsedetail.data.ArticleName.ToString();

                    try
                    {

                        var fileDetail = await _context.FileDetails.FirstOrDefaultAsync(x => x.fileName == filename);


                        if (fileDetail != null)
                        {
                            var recordetailold = await _context.Recorddetails37.FirstOrDefaultAsync(x => x.fileID == fileDetail.fileID && x.activityid == activityid);


                            if (recordetailold != null)
                            {

                                try
                                {

                                    if (recordetailold.status == 0)
                                    {


                                        recordetailold.status = 1;
                                        //  _context.Recorddetails.Attach(recordetailold);
                                        //  _context.Entry(recordetailold).Property(x=>x.status & x.bookid &x.fileID).IsModified=true;
                                        //  _context.SaveChanges();
                                        _context.Recorddetails37.Update(recordetailold);

                                        await _context.SaveChangesAsync();
                                    }
                                    else
                                    {

                                    }
                                }
                                catch (Exception ex)
                                {

                                    return StatusCode(200new { is_success = falsedata = ""message = "Error in Updating Activity Details Error Desc: " + ex.Message.ToString() });
                                }
                            }
                            else
                            {
                                var recordetail = new Recorddetail37
                                {
                                    fileID = fileDetail.fileID,
                                    activityid = (Int16)activityid,
                                    stageId = (Int16)stageid,
                                    bookid = (Int16)fileDetail.bookid,
                                    status = 1,
                                    @lock = "N"


                                };
                                try
                                {
                                    await _context.AddAsync(recordetail);
                                    await _context.SaveChangesAsync();

                                }
                                catch (Exception ex)
                                {

                                    return StatusCode(200new { is_success = falsedata = ""message = "Error in Inserting Activity Details  Error Desc: " + ex.Message.ToString() });

                                }
                            }

                        }


                    }
                    catch (Exception ex)
                    {

                        return StatusCode(200new { is_success = falsedata = ""message = ex.Message.ToString() });
                    }



                }
                else
                {


                    string filename = responsedetail.data.ArticleName.ToString();
                    string FileName = Path.GetFileName(responsedetail.data.path.ToString());
                    DownloadDirectory = DownloadDirectory.Replace("bookname"responsedetail.data.JournalName.ToString());
                    String DownloadPath = DownloadDirectory + filename + "\\" + FileName;

                    // string pdfName = Path.GetFileName(jobinputs.pdfPath);
                    // string xmlFName = Path.GetFileName(jobinputs.xmlPath);
                    // string appFName = Path.GetFileName(jobinputs.ApplicationPath);



                    // if (jobinputs.Wfdid == "23" || jobinputs.Wfdid == "24")
                    if (responsedetail.data.WfdId == 23 || responsedetail.data.WfdId == 24)
                    {
                        //adding Activity and Stage Detail for abovedotne Workflow ID's
                        stageid = 791;
                        activityid = 6075;

                        if (!string.IsNullOrEmpty(responsedetail.data.path.ToString()))
                        {

                            try
                            {

                                var fileDetail = await _context.FileDetails.FirstOrDefaultAsync(x => x.fileName == filename);


                                // if (!Directory.Exists(DownloadDirectory))
                                //     Directory.CreateDirectory(DownloadDirectory);


                                //  client.DownloadFile(new Uri(responsedetail.data.path.ToString()), DownloadPath);


                                // ZipFile.ExtractToDirectory(TempFilePath, TempPath, true);
                                if (Decompress(DownloadPathPath.GetDirectoryName(DownloadPath), responsedetail.data.path.ToString(), ref sCaptureError))
                                {



                                    if (fileDetail != null)
                                    {
                                        var recordetailold = await _context.Recorddetails.FirstOrDefaultAsync(x => x.fileID == fileDetail.fileID && x.activityid == activityid);


                                        if (recordetailold != null)
                                        {

                                            try
                                            {

                                                if (recordetailold.status == 0)
                                                {


                                                    recordetailold.status = 1;
                                                    //  _context.Recorddetails.Attach(recordetailold);
                                                    //  _context.Entry(recordetailold).Property(x=>x.status & x.bookid &x.fileID).IsModified=true;
                                                    //  _context.SaveChanges();
                                                    _context.Recorddetails.Update(recordetailold);

                                                    await _context.SaveChangesAsync();
                                                }
                                                else
                                                {

                                                }
                                            }
                                            catch (Exception ex)
                                            {

                                                return StatusCode(200new { is_success = falsedata = ""message = "Error in Updating Activity Details Error Desc: " + ex.Message.ToString() });
                                            }
                                        }
                                        else
                                        {
                                            var recordetail = new Recorddetail
                                            {
                                                fileID = fileDetail.fileID,
                                                activityid = (Int16)activityid,
                                                stageId = (Int16)stageid,
                                                bookid = (Int16)fileDetail.bookid,
                                                status = 1,
                                                @lock = "N"


                                            };
                                            try
                                            {
                                                await _context.AddAsync(recordetail);
                                                await _context.SaveChangesAsync();

                                            }
                                            catch (Exception ex)
                                            {

                                                return StatusCode(200new { is_success = falsedata = ""message = "Error in Inserting Activity Details  Error Desc: " + ex.Message.ToString() });

                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    return StatusCode(200new { is_success = falsedata = ""message = sCaptureError });
                                }


                            }
                            catch (Exception ex)
                            {

                                return StatusCode(200new { is_success = falsedata = ""message = ex.Message.ToString() });
                            }
                        }
                        else
                        {

                            return StatusCode(200new { is_success = falsedata = ""message = "File Path Should not be empty" });

                        }
                    }
                }

                var updateresponse = client.PostAsync("/integra/ips/ijps/update-journal-job-moved-to-wms"new StringContent(idsEncoding.UTF8"application/json")).Result;
                Response responsenew = null;
                if (response.IsSuccessStatusCode)
                {

                    responsenew = await updateresponse.Content.ReadAsAsync<Response>();
                }

                if (responsenew.is_success)
                {

                    return StatusCode(200new { is_success = truedata = ""message = "Success" });
                }
                else
                {
                    return StatusCode(200new { is_success = truedata = ""message = "Error in Updating Status" });
                }
            }
            else
            {
                return StatusCode(200new { is_success = truedata = ""message = "No Respond from IAuthor URL " });
            }

        }
        [NonAction]
        private static bool Decompress(string zipFilePathstring extractPathstring uriPathref string sError)
        {
            WebClient client = new WebClient();
            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(zipFilePath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(zipFilePath));

                client.DownloadFile(new Uri(uriPath), zipFilePath);
                // using ( objImpersonate = new ImpersonationService("itoolsusers", "Integra-India.com", "hIe6arCh7"))
                // SafeAccessTokenHandle safeAccessTokenHandle;
                // bool returnValue = LogonUser("itoolsusers", "INTEGRA-INDIA","hIe6arCh7",
                // LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                // out safeAccessTokenHandle);

                if (System.IO.File.Exists(zipFilePath) == false)
                {
                    ///sError = zipFilePath + " does not exists";
                    // return false;
                }
                if (Directory.Exists(extractPath) == false)
                {
                    Directory.CreateDirectory(extractPath);
                }

                //not over write
                //ZipFile.ExtractToDirectory(zipFilePath, extractPath);

                //over write
                using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        string ename = string.Empty;
                        if (entry.FullName.EndsWith("/"))
                        {
                            ename = entry.FullName.Substring(0entry.FullName.Length - 1);
                        }
                        else
                        {
                            ename = entry.FullName;
                        }
                        string FullPath = Path.Combine(extractPathename.Replace("/""\\"));
                        FullPath = Path.Combine(extractPathPath.GetFileName(FullPath));
                        if (Regex.IsMatch(FullPath"\\.[a-z]{1,}"RegexOptions.IgnoreCase))
                        {
                            entry.ExtractToFile(FullPathtrue);
                        }
                        else
                        {
                            //if (!Directory.Exists(FullPath))
                            //{
                            //    Directory.CreateDirectory(FullPath);
                            //}
                        }
                    }
                }

                // }
                if (System.IO.File.Exists(zipFilePath))
                    System.IO.File.Delete(zipFilePath);
                return true;



            }
            catch (Exception ex)
            {
                sError = ex.Message.ToString();
                return false;
            }
        }

        private bool FileDetailExists(int id)
        {
            return _context.FileDetails.Any(e => e.fileID == id);
        }
    }
}

Comments

Popular posts from this blog

Vb Net reference for JSon Extraction of String to Json .

 Public Shared Function SupplementaryUpload(ByVal ICMSIntegrationID As String, ByVal CMSActivityID As String, ByVal File As String, ByVal Flag As String, ByRef ErrorResponse As String) As Boolean         Try             'Dim client As New RestSharp.RestClient()             ' Dim BMJ_LinkUpload As String = ConfigurationManager.AppSettings("BMJ_API_Upload")             Dim BMJ_LinkUpload As String = "http://is-s2130:5000/BMJIntegration/SupplementaryUpload"             'client.BaseUrl = New Uri(BMJ_LinkUpload & "?ICMSIntegrationID=" & ICMSIntegrationID & "& CMSActivityID=" & CMSActivityID & "&File=" & File & "&Flag=" & Flag)             '''?ICMSIntegrationID=56445096&CMSActivityID=29&File=D:\admin.JPG&Flag=article_resource")         ...

Hosting multiple Environments

using   System ; using   System . Collections . Generic ; using   System . Linq ; using   System . Threading . Tasks ; using   Microsoft . AspNetCore . Builder ; using   Microsoft . AspNetCore . Hosting ; using   Microsoft . AspNetCore . HttpsPolicy ; using   Microsoft . AspNetCore . Mvc ; using   Microsoft . Extensions . Configuration ; using   Microsoft . Extensions . DependencyInjection ; using   Microsoft . Extensions . Hosting ; using   Microsoft . Extensions . Logging ; using   Microsoft . EntityFrameworkCore ; using   MovejobtoWms . Models ; using   Microsoft . AspNetCore . Authentication . Cookies ; using   Microsoft . AspNetCore . Authentication ; using   Newtonsoft . Json ; using   Microsoft . AspNetCore . Http ; using   System . Net . Http . Headers ; namespace   MovejobtoWms {      public   class   Star...