Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 108,457

HOME > .NET Framework > Forum > C# ขอสอบถามerror Interal Box error, try 5 min later please



 

C# ขอสอบถามerror Interal Box error, try 5 min later please

 



Topic : 126519



โพสกระทู้ ( 5 )
บทความ ( 0 )



สถานะออฟไลน์




Code (C#)
 string endFolder = "";
            var todayFolder = db.Documents.Where(x => x.DateOfUpload == DateTime.Today).FirstOrDefault();
            if (todayFolder != null)
            {
                endFolder = todayFolder.PathInBox;
            }
            else
            {
                string year = DateTime.Now.Year.ToString();
                string month = DateTime.Now.ToString("MMMM");
                string day = DateTime.Now.Day.ToString();


                //search for folder like 2016/02/12 or create a new one path
                // var Items = await _client.FoldersManager.GetFolderItemsAsync("0",100);
                try
                {
                    var Folder = await _client.SearchManager.SearchAsync(keyword: year, type: "folder", ancestorFolderIds: new List<string> { _rootFolder });

                    if (Folder.TotalCount > 0)
                    {
                        endFolder = Folder.Entries[0].Id;
                        Folder = await _client.SearchManager.SearchAsync(keyword: month, type: "folder", ancestorFolderIds: new List<string> { endFolder });
                        if (Folder.TotalCount > 0)
                        {
                            endFolder = Folder.Entries[0].Id;
                            Folder = await _client.SearchManager.SearchAsync(keyword: day, type: "folder", ancestorFolderIds: new List<string> { endFolder });
                            if (Folder.TotalCount > 0)
                            {
                                endFolder = Folder.Entries[0].Id;
                            }
                            else
                            {
                                endFolder = await CreatFolderInBox(endFolder, day);
                            }
                        }
                        else
                        {
                            endFolder = await CreatFolderInBox(endFolder, month);
                            endFolder = await CreatFolderInBox(endFolder, day);
                        }
                    }
                    else
                    {
                        endFolder = await CreatFolderInBox(_rootFolder, year);
                        endFolder = await CreatFolderInBox(endFolder, month);
                        endFolder = await CreatFolderInBox(endFolder, day);
                    }
                }
                catch (BoxException bex)
                {
                    HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Conflict);
                    message.Content = new StringContent("Interal Box error, try 5 min later please...");
                    message.ReasonPhrase = "Interal Box error, try 5 min later please...";
                    return message;
                }
            }




Tag : .NET, Web (ASP.NET), C#, Windows







Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2017-02-22 08:53:14 By : piwpong View : 794 Reply : 1
 

 

No. 1



โพสกระทู้ ( 5 )
บทความ ( 0 )



สถานะออฟไลน์


Code (C#)
        // GET api/Document
        public IEnumerable<LO_DOC> GetDocuments()
        {
            return db.Documents.Select(x=>x);
        }
        public IEnumerable<LO_DOC> GetDocuments(string text, string date)
        {
            
            //IEnumerable<Document> ret = new List<Document> {new Document{ID=1,Name="test"}};
            //return ret;
            if (date == null && text != null)
            {
                var items = db.Documents.Where(x => x.Name.Contains(text));
                return items.AsEnumerable();
            }
            if (date != null && text == null)
            {
                DateTime newDate = DateTime.ParseExact(date,"dd/MM/yyyy",CultureInfo.InvariantCulture);
                var items = db.Documents.Where(x => x.DateOfUpload == newDate).ToList();
                return items;
            }
            if (text != null && date != null)
            {
                DateTime newDate = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                var items = db.Documents.Where(x => x.Name.Contains(text)).Where(x => x.DateOfUpload == newDate);
                return items.AsEnumerable();
            }
            return db.Documents.AsEnumerable();
        }



        private async Task  Login()
        {
          
            string refreshToken="";
            string accessToken="";
            try
            {
                var lastToken = tokenDB.Tokens.Select(x =>x).ToList();
                refreshToken = lastToken.Last<LO_DOC_TOKENS>().Refreshtoken;
                accessToken = lastToken.Last<LO_DOC_TOKENS>().AccessToken;
            }
            catch (Exception e)
            {
                
            }

            

            OAuthSession session = new OAuthSession(accessToken, refreshToken, 3600, "bearer");
            var config = new BoxConfig(_clientKey, _clientSecret, _uri);
            _client = new BoxClient(config, session);
            try
            {
                var Items = await _client.FoldersManager.GetFolderItemsAsync("0", 100);
            }
            catch (BoxException e)
            {
                await _client.Auth.RefreshAccessTokenAsync(_client.Auth.Session.AccessToken);
            }
            if (_client.Auth.Session.AccessToken != accessToken)
            {
                RewriteTokens(_client.Auth.Session.AccessToken, _client.Auth.Session.RefreshToken);
            }
        }
        private void RewriteTokens(string accessToken, string refreshToken)
        {
            LO_DOC_TOKENS newToken = new LO_DOC_TOKENS() { AccessToken = accessToken, Refreshtoken = refreshToken };
            var deleteList = tokenDB.Tokens.Select(x => x);
            foreach (LO_DOC_TOKENS item in deleteList)
            {
                tokenDB.Tokens.Remove(item);
            }
            tokenDB.SaveChanges();
            tokenDB.Tokens.Add(newToken);
            tokenDB.SaveChanges();
        }
        public async Task<string> GetDocument(int id)
        {

            LO_DOC document = db.Documents.Find(id);
            if (document == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            string DownloadUrl ="";
            //connect to box
             await Login();
            try
            {
                DownloadUrl = (await _client.FilesManager.GetDownloadUriAsync(document.IdInBox)).ToString();
            }catch(BoxException e)
            {

            } 
            //inc count of downloads in dbo
            document.CountOfDownloading++;
            db.Entry(document).State = EntityState.Modified;
            db.SaveChanges();

            return DownloadUrl;
        }

        // PUT api/Document/5
        public HttpResponseMessage PutDocument(int id, LO_DOC document)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != document.ID)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(document).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        private async Task<string> CreatFolderInBox(string FolderId, string FolderName)
        {
            BoxFolderRequest folder = new BoxFolderRequest()
            {
                Name = FolderName,
                Parent = new BoxRequestEntity() { Id = FolderId }
            };
            BoxFolder newFolder = await _client.FoldersManager.CreateAsync(folder);
            return newFolder.Id;
        }

        // POST api/Document
        public string username = "";
        public async Task<HttpResponseMessage> PostDocument()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType);
                message.Content = new StringContent("File error");

                return message;
            }
            try
            {
                
                string user = HttpContext.Current.Request.Cookies["user"].Value;
                username = user;
            }
            catch (Exception e)
            { }
            
                //username = User.Identity.Name;
            var provider = new MultipartMemoryStreamProvider();
            // folder on server

                await Request.Content.ReadAsMultipartAsync(provider);

            string fromApp = provider.Contents[0].Headers.ContentDisposition.Name.Replace("\"", string.Empty);
            bool needMerge = false;
            string need = provider.Contents[0].Headers.ContentDisposition.Name.Replace("\"", string.Empty);
            if (need == "1")
            {
                needMerge = true;
            }
            //box part
            await Login();




            string endFolder = "";
            var todayFolder = db.Documents.Where(x => x.DateOfUpload == DateTime.Today).FirstOrDefault();
            if (todayFolder != null)
            {
                endFolder = todayFolder.PathInBox;
            }
            else
            {
                string year = DateTime.Now.Year.ToString();
                string month = DateTime.Now.ToString("MMMM");
                string day = DateTime.Now.Day.ToString();


                //search for folder like 2016/02/12 or create a new one path
                // var Items = await _client.FoldersManager.GetFolderItemsAsync("0",100);
                try
                {
                    var Folder = await _client.SearchManager.SearchAsync(keyword: year, type: "folder", ancestorFolderIds: new List<string> { _rootFolder });

                    if (Folder.TotalCount > 0)
                    {
                        endFolder = Folder.Entries[0].Id;
                        Folder = await _client.SearchManager.SearchAsync(keyword: month, type: "folder", ancestorFolderIds: new List<string> { endFolder });
                        if (Folder.TotalCount > 0)
                        {
                            endFolder = Folder.Entries[0].Id;
                            Folder = await _client.SearchManager.SearchAsync(keyword: day, type: "folder", ancestorFolderIds: new List<string> { endFolder });
                            if (Folder.TotalCount > 0)
                            {
                                endFolder = Folder.Entries[0].Id;
                            }
                            else
                            {
                                endFolder = await CreatFolderInBox(endFolder, day);
                            }
                        }
                        else
                        {
                            endFolder = await CreatFolderInBox(endFolder, month);
                            endFolder = await CreatFolderInBox(endFolder, day);
                        }
                    }
                    else
                    {
                        endFolder = await CreatFolderInBox(_rootFolder, year);
                        endFolder = await CreatFolderInBox(endFolder, month);
                        endFolder = await CreatFolderInBox(endFolder, day);
                    }
                }
                catch (BoxException bex)
                {
                    HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Conflict);
                    message.Content = new StringContent("Internal Box error, try 5 min later please...");
                    message.ReasonPhrase = "Internal Box error, try 5 min later please...";
                    return message;
                }
            }
            var FilesInMap = new Dictionary<string, byte[]>();
            int start = 0;
            int end = 1;
            if(fromApp == "1" || fromApp == "0")
            {
                end = provider.Contents.Count;
                start = 1;
            }

            for (int i = start; i < end; i++)
            { 
                    string filename = provider.Contents[i].Headers.ContentDisposition.FileName.Replace("\"", string.Empty);

                    Regex newReg = new Regex(@"[^\\]*\.pdf$");
                    Match match = newReg.Match(filename);
                    filename = match.ToString();
                    byte[] fileArray = await provider.Contents[i].ReadAsByteArrayAsync();
                FilesInMap[filename] = fileArray;

                }
            HttpResponseMessage Finalmessage;
                if (needMerge)
                {
                Finalmessage = await MergeAndUpload(endFolder, FilesInMap);
                }
                else
                {
                Finalmessage = await Upload(endFolder, FilesInMap);
                }
            return Finalmessage;
        }
        private async Task<HttpResponseMessage> Upload(string endFolder, Dictionary<string,byte[]> Files)
        {
            HttpResponseMessage Finalmessage = null;
            string Response = "";
            foreach(var file in Files)
            {
                BoxFile newFile = null;
                using (Stream stream = new MemoryStream(file.Value))
                {
                    string copypart = "";
                    int NumberOfCopy = 1;
                    bool uploaded = false;

                    while (!uploaded)
                    {

                        //upload on box
                        try
                        {
                            var oldFileReq = new BoxPreflightCheckRequest() { Name = copypart + file.Key, Parent = new BoxRequestEntity() { Id = endFolder } };
                            await _client.FilesManager.PreflightCheck(oldFileReq);
                            uploaded = true;
                        }
                        catch (BoxPreflightCheckConflictException<BoxFile> bex)
                        {
                            if (NumberOfCopy < 10)
                            {
                                copypart = "(" + Convert.ToString(NumberOfCopy++) + ") - ";
                            }
                            else
                            {
                                Response = file.Key + " - already exist 10 copies for today";
                                Finalmessage = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
                                Finalmessage.Content = new StringContent(Response);
                                Finalmessage.ReasonPhrase = Response;
                                break;
                            }
                        }
                    }
                    if (!uploaded)
                        break;
                    BoxFileRequest req = new BoxFileRequest()
                        {
                            Name = copypart + file.Key,
                            Parent = new BoxRequestEntity() { Id = endFolder }
                        };                        
                        newFile = await _client.FilesManager.UploadAsync(req, stream);
                
                    //add a line into local dbo
                    LO_DOC TempDoc = new LO_DOC();
                    TempDoc.IdInBox = newFile.Id;
                    TempDoc.isMerged = false;
                    TempDoc.Name = newFile.Name;
                    TempDoc.Owner = username;
                    TempDoc.PathInBox = endFolder;
                    TempDoc.DateOfUpload = DateTime.Today;
                    TempDoc.CountOfDownloading = 0;
                    try
                    {
                        db.Documents.Add(TempDoc);
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        HttpResponseMessage Errormessage = new HttpResponseMessage(HttpStatusCode.BadGateway);
                        Errormessage.Content = new StringContent("Databese error");
                        Errormessage.ReasonPhrase = "Databese error";
                        return Errormessage;
                    }
                    Response = "File uploaded";

                    //delete temp pdf from server
                }
            }
            if (Finalmessage == null)
            {
                Finalmessage = new HttpResponseMessage(HttpStatusCode.Created);
                Finalmessage.Content = new StringContent(Response);
                Finalmessage.ReasonPhrase = Response;
            }
            return Finalmessage;
        }
        private async Task<HttpResponseMessage> MergeAndUpload(string endFolder, Dictionary<string, byte[]> Files)
        {
            string Name = "";
            Stream memStremTarget = new MemoryStream();
            using (PdfDocument targetDoc = new PdfDocument())
            {
                foreach (var file in Files)
                {
                    Name = Name + "+" + file.Key;
                    Stream memStrem = new MemoryStream(file.Value);
                    PdfDocument pdfDoc = PdfReader.Open(memStrem, PdfDocumentOpenMode.Import);                    
                        for (int i = 0; i < pdfDoc.PageCount; i++)
                        {
                            targetDoc.AddPage(pdfDoc.Pages[i]);
                        }                    
                }
                targetDoc.Save(memStremTarget, false);

            }
            BoxFile newFile;

                BoxFileRequest req = new BoxFileRequest()
                {
                    Name = Name,
                    Parent = new BoxRequestEntity() { Id = endFolder }
                };
                //upload on box
                newFile = await _client.FilesManager.UploadAsync(req, memStremTarget);
                memStremTarget.Dispose();
                //add a line into local dbo
                LO_DOC TempDoc = new LO_DOC();
                TempDoc.IdInBox = newFile.Id;
                TempDoc.isMerged = true;
                TempDoc.Name = newFile.Name;
                TempDoc.Owner = username;
                TempDoc.PathInBox = endFolder;
                TempDoc.DateOfUpload = DateTime.Today;
                TempDoc.CountOfDownloading = 0;
            try
            {
                db.Documents.Add(TempDoc);
                db.SaveChanges();
            }
            catch
            {
                HttpResponseMessage Errormessage = new HttpResponseMessage(HttpStatusCode.Created);
                Errormessage.Content = new StringContent("Databese error");
                Errormessage.ReasonPhrase = "Databese error";
                return Errormessage;
            }

            HttpResponseMessage Finalmessage = new HttpResponseMessage(HttpStatusCode.Created);
            Finalmessage.Content = new StringContent("Files has merged and uploaded");
            Finalmessage.ReasonPhrase = "Files has merged and uploaded";
            return Finalmessage;
            //delete temp file on server
        }
      
        // DELETE api/Document/5
        public async Task<HttpResponseMessage> DeleteDocument(int id)
        {
            LO_DOC document = db.Documents.Find(id);
            if (User.Identity.Name != "TB\\phuripun_w" && User.Identity.Name != "TH\\Pavel_M")
            {
                if(document.Owner != User.Identity.Name)
                return Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            if (document == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            //box part
             await Login();


            await _client.FilesManager.DeleteAsync(document.IdInBox);

            db.Documents.Remove(document);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, document);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            tokenDB.Dispose();
            base.Dispose(disposing);
        }
    }
}







แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2017-02-22 09:05:52 By : piwpong
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : C# ขอสอบถามerror Interal Box error, try 5 min later please
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: Voake, Comcube, รับทำเว็บไซต์ รับเขียนโปรแกรม , รับทำบัญชี , โรงงานผลิตครีม , สำนักงานบัญชี , รับจดทะเบียนบริษัท , Pangpond , รถมือสอง

Load balance : Server 04
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2020 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่