Thứ Ba, 22 tháng 12, 2020

List Anime - Manga hay

 Anime-Manga

======

Gamble fish

Danganronpa

Rainbow

Erased

Higurashi no Naku Koro ni

Alice In Borderland – Imawa No Kuni No Alice

tenkuu shinpan

Cage Of Eden

Kamisama no iuutori – As the Gods Will

Battle Royale

Kakegurui

Code geass

Trigun

Clannad

Psycho Pass

Monster

Gantz

ichigo 100

The dragon next door

Shut Hell

nozoki Ana

20th Century Boys

Pandora Heart

ReLIFE

Billy Bat

boy on the run

I AM A HERO

Ushiro and Tora

Claymore

Pluto

jujutsu kaisen

Ganbare Genki

Người bà tài giỏi vùng Saga


==

nhạc:

Egoist Guilty Crown


Gọi upload Multipart C#

 public void UploadMultiFilesTest()

        {

            var message = new HttpRequestMessage();

            var content = new MultipartFormDataContent();


            string[] fileUploadPaths = { @"C:\Users\Acer\Pictures\photo_2020-12-16_10-25-16.jpg" };


            int count = 0;

            foreach (string fileUploadPath in fileUploadPaths)

            {

                var filestream = new FileStream(fileUploadPath, FileMode.Open);

                var fileName = Path.GetFileName(fileUploadPath);

                content.Add(new StreamContent(filestream), "file_" + (++count), fileName);

            }


            content.Add(new StringContent("this is value"), "json_key");


            var client = new HttpClient();


            client.PostAsync("http://localhost:6764/MediaUpload", content).ContinueWith(task =>

            {

                if (task.Result.IsSuccessStatusCode)

                {

                    //

                }

            });

        }

Web api upload C#

 + Tạo class: InMemoryMultipartFormDataStreamProvider

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Collections.Specialized;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;

using System.Web;


// Nếu thiếu System.Net.Http thì vào C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5

// copy vào thư mục bin của project


namespace WebAPIUpload.App_Code

{

    public class InMemoryMultipartFormDataStreamProvider : MultipartStreamProvider

    {

        private NameValueCollection _formData = new NameValueCollection();

        private List<HttpContent> _fileContents = new List<HttpContent>();


        // Set of indexes of which HttpContents we designate as form data  

        private Collection<bool> _isFormData = new Collection<bool>();


        /// <summary>  

        /// Gets a <see cref="NameValueCollection"/> of form data passed as part of the multipart form data.  

        /// </summary>  

        public NameValueCollection FormData

        {

            get { return _formData; }

        }


        /// <summary>  

        /// Gets list of <see cref="HttpContent"/>s which contain uploaded files as in-memory representation.  

        /// </summary>  

        public List<HttpContent> Files

        {

            get { return _fileContents; }

        }


        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)

        {

            // For form data, Content-Disposition header is a requirement  

            ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;

            if (contentDisposition != null)

            {

                // We will post process this as form data  

                _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));


                return new MemoryStream();

            }


            // If no Content-Disposition header was present.  

            throw new InvalidOperationException(string.Format("Did not find required '{0}' header field in MIME multipart body part..", "Content-Disposition"));

        }


        /// <summary>  

        /// Read the non-file contents as form data.  

        /// </summary>  

        /// <returns></returns>  

        public override async Task ExecutePostProcessingAsync()

        {

            // Find instances of non-file HttpContents and read them asynchronously  

            // to get the string content and then add that as form data  

            for (int index = 0; index < Contents.Count; index++)

            {

                if (_isFormData[index])

                {

                    HttpContent formContent = Contents[index];

                    // Extract name from Content-Disposition header. We know from earlier that the header is present.  

                    ContentDispositionHeaderValue contentDisposition = formContent.Headers.ContentDisposition;

                    string formFieldName = UnquoteToken(contentDisposition.Name) ?? String.Empty;


                    // Read the contents as string data and add to form data  

                    string formFieldValue = await formContent.ReadAsStringAsync();

                    FormData.Add(formFieldName, formFieldValue);

                }

                else

                {

                    _fileContents.Add(Contents[index]);

                }

            }

        }


        /// <summary>  

        /// Remove bounding quotes on a token if present  

        /// </summary>  

        /// <param name="token">Token to unquote.</param>  

        /// <returns>Unquoted token.</returns>  

        private static string UnquoteToken(string token)

        {

            if (String.IsNullOrWhiteSpace(token))

            {

                return token;

            }


            if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)

            {

                return token.Substring(1, token.Length - 2);

            }


            return token;

        }

    }

}

+ API Upload:

/// <summary>  

        /// Upload Document.....  

        /// </summary>        

        /// <returns></returns>  

        [HttpPost]

        [Route("MediaUpload")]

        public async Task<HttpResponseMessage> MediaUpload()

        {

            // Check if the request contains multipart/form-data.  

            //if (!Request.Content.IsMimeMultipartContent())

            //{

            //    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

            //}


            var x = Request.Content.Headers.ContentLength; // kích thước Body: = 0 body rỗng 


            var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());


            //access form data  

            NameValueCollection formData = provider.FormData;


            //Get body headers info: json key

            string json = "";

            if (formData["json"] != null)

            {

                json = formData["json"];

            }


            //access files  

            IList<HttpContent> files = provider.Files;

            int dem = 0;


            foreach (HttpContent fileContent in files)

            {

                // body key

                string key = fileContent.Headers.ContentDisposition.Name.Trim('\"');


                string thisFileName = fileContent.Headers.ContentDisposition.FileName.Trim('\"');


                // stream

                Stream input = await fileContent.ReadAsStreamAsync();


                //folder path

                DateTime dt = DateTime.Now;

                string sPath = Static.GetPath() + "/PhanAnh/" + DateTime.Now.ToString("yyyy/MM") + "/";

                sPath = HttpContext.Current.Server.MapPath(sPath);


                //create folder if not Exists

                if (!Directory.Exists(sPath))

                    Directory.CreateDirectory(sPath);


                //file path

                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");

                var fileExtension = Path.GetExtension(thisFileName);

                var filePath = System.IO.Path.Combine(sPath, fileName + fileExtension);


                using (Stream file = File.OpenWrite(filePath))

                {

                    input.CopyTo(file);

                    file.Close();

                }


                dem++;

            }


            var response = Request.CreateResponse(HttpStatusCode.OK);

            //response.Headers.Add("DocsUrl", URL);

            //response.Content = new StringContent("Upload thành công file: " + thisFileName + ". Lưuvào thư mục ClientDocument", Encoding.UTF8);

            if (dem > 0)

                response.Content = new StringContent("Upload thành công " + dem + " file  - Chuoi json = " + json);

            return response;

        }

Thứ Hai, 30 tháng 11, 2020

Tìm các số trùng trong mảng sắp xếp C#

 int N = arr.Length - 1;

            for (int i = 0; i < N; i++)

            {

                if (arr[i] == arr[i + 1])

                {

                    Console.WriteLine(arr[i]);

                    i++;

                }

            }

Find Missing number in sorted array C#

  static void find(int[] a)

        {

            /// if a.leng >= 3

            int N = a.Length - 1;

            for (int i = 0; i < N; i++)

            {

                Console.WriteLine(string.Format("Step {0}: {1} - {2}", i, a[i], a[i + 1]));


                int begin = a[i];

                int end = a[i + 1];


                int diff = end - begin;


                if (diff > 1)

                {

                    for (int k = 1; k < diff; k++)

                    {

                        Console.WriteLine("    >> " + (begin + k));

                    }

                }

            }

        }

Thứ Ba, 24 tháng 11, 2020

Các loại design patterns

 

Các loại design patterns.

  • Về cơ bản thì design pattern sẽ được chia làm 3 dạng chính và mỗi dạng chính và có tổng cộng 32 mẫu design:

Creational Pattern ( nhóm khởi tạo):

Nhóm này sẽ giúp bạn rất nhiều trong việc khởi tạo đối tượng, mà bạn khó có thể nhận ra (nó sẽ không dùng từ khóa new như bình thường). Nhóm này gồm 9 mẫu design là:

  • Abstract Factory.
  • Builder.
  • Factory Method.
  • Multiton.
  • Pool.
  • Prototype.
  • Simple Factory.
  • Singleton.
  • Static Factory.

Structural (nhóm cấu trúc):

Nhóm này sẽ giúp chúng ta thiết lập, định nghĩa quan hệ giữa các đối tượng. Nhóm này gồm có 11 mẫu design là:

  • Adapter/ Wrapper.
  • Bridge.
  • Composite.
  • Data Mapper.
  • Decorator.
  • Dependency Injection.
  • Facade.
  • Fluent Interface.
  • Flyweight.
  • Registry.
  • Proxy

Behavioral patterns (nhóm ứng xử):

Nhóm này sẽ tập trung thực hiện các hành vi của đối tượng. Gồm 12 mẫu design là:

Thứ Bảy, 7 tháng 11, 2020

Web API C#

 using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Text;

using System.Web;

using System.Web.Http;


//https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing

namespace LogFileWeb

{

    [RoutePrefix("api/books")]

    public class LogController : ApiController

    {

        // GET api/<controller>

        [Route("get1")]

        public IEnumerable<string> Get1()

        {

            WriteLog("Hêlo");

            WriteLog("World");

            return new string[] { "value1", "value2" };

        }


        // GET get2?id=5

        [Route("get2")]

        public IHttpActionResult Get2(int id)

        {

            string val = "value";

            return Ok(new { V = val });

        }


        [Route("get3")]

        public IHttpActionResult Get3(int id)

        {

            string val = "value";

            return Ok(val);

        }


        [Route("get4")]

        public string Get4(int id)

        {

            string val = "value";

            return val;

        }


        //get5/1/2

        [Route("get5/{one}/{two}")]

        public string Get5(int paramOne, int paramTwo)

        {

            return "The [Route] with multiple params worked";

        }


        //with type: get6/1/2

        [Route("get6/{one:int}/{two}")]

        public string Get6(int paramOne, int paramTwo)

        {

            return "The [Route] with multiple params worked";

        }


        // POST api/<controller>

        public void Post([FromBody]string value)

        {

        }


        // PUT api/<controller>/5

        public void Put(int id, [FromBody]string value)

        {

        }


        // DELETE api/<controller>/5

        public void Delete(int id)

        {

        }


        protected void WriteLog(string log)

        {

            try

            {

                string logFile = HttpContext.Current.Server.MapPath("~/api/log.txt");

                using (StreamWriter writetext = new StreamWriter(logFile, true, Encoding.UTF8))

                {

                    writetext.WriteLine(log);

                }

            }

            catch (Exception e)

            {

            }

        }

    }

}