public static string Get(FileMetaData file)
        {
            if (file.IsInClient)
            {
                return System.IO.File.ReadAllText(file.ClientPath.Path);
            }

            throw new InvalidOperationException("File not in the workspace.");
        }
        private void btnDownload_Click(object sender, EventArgs e)
        {
            string filetodownload = @"C:\ProjectShare\Uploads\" + activeFile.Id.ToString() + "." + lblFIleInfo.Text.Substring(lblFIleInfo.Text.LastIndexOf('.') + 1);

               FileMetaData fmd = new FileMetaData();
            fmd.FullLocalPath = filetodownload;
            FileDownloadMessage fdm = new FileDownloadMessage(fmd);

            IssueDownloadRequest(filetodownload, fdm);
        }
        public int Get(FileMetaData file)
        {
            int output;

            if (!wordCountCache.TryGetValue(file, out output))
            {
                output = UDNFilesHelper.GetWordCount(UDNFilesHelper.Get(file));
                wordCountCache.Add(file, output);
            }

            return output;
        }
Esempio n. 4
0
        public P4FileTreeListViewItem(TreeListViewItem parentItem, string path, FileMetaData fileData)
            : base()
        {
            _fileData  = null; //fileData;
            ParentItem = parentItem;
            Fields     = null;
            Tag        = fileData;

            ImageIndex = (int)CenterImages.Portrait;
            AddSubitem(path, 0);

            this.FullLine = true;
        }
Esempio n. 5
0
        /// <summary>
        ///     Gets meta data of the <paramref name="part" />.
        /// </summary>
        /// <param name="part">The part which meta data should be returned.</param>
        /// <returns>Metadata of the <paramref name="part" />.</returns>
        private FileMetaData GetMetaData(PackagePart part)
        {
            var          metaPart = _archive.GetPart(GetMetaPartUri(part));
            FileMetaData meta     = null;

            using (var metaStream = metaPart.GetStream())
            {
                var binaryFormatter = new BinaryFormatter();
                meta = (FileMetaData)binaryFormatter.Deserialize(metaStream);
            }

            return(meta);
        }
Esempio n. 6
0
        public static FileMetaDataModel SaveFileMetaData(RayimContext context, FileMetaDataModel model)
        {
            bool         isNew      = model.Id == 0;
            FileMetaData dbFileData = context.FileMetaDatas.FirstOrDefault(x => x.Id == model.Id) ?? new FileMetaData();

            CustomMapper.MapEntity(model, dbFileData);
            if (isNew)
            {
                context.FileMetaDatas.Add(dbFileData);
            }
            context.SaveChanges();
            return(CustomMapper.MapEntity <FileMetaDataModel>(dbFileData));
        }
        /// <inheritdoc />
        /// <summary>
        /// Takes a list of IFormFile. Calls to create a string representation of a guid
        /// for each file and writes that as well as other file-related data to an instance
        /// of FileMetaData. Calls the minio service to upload the files, then writes the
        /// metadata to a collection in MongoDB.
        /// </summary>
        /// <param name="filesIn">A list of IFormFile which contains the files to be uploaded.</param>
        /// <returns>A string representation of the GUID which is the filename in storage</returns>
        public async Task <List <string> > StoreFiles(List <IFormFile> filesIn)
        {
            var success       = false;
            var fileMetaDatas = new List <FileMetaData>();

            foreach (var formFile in filesIn)
            {
                if (formFile.Length <= 0)
                {
                    continue;
                }

                Log.Information($"Uploading file: {formFile.FileName}.");

                var fileMetaData = new FileMetaData
                {
                    FileName   = formFile.FileName,
                    FileType   = formFile.ContentType,
                    FileGuid   = CreateFileGuid(),
                    UploadDate = DateTime.Now
                };

                fileMetaDatas.Add(fileMetaData);

                if (string.Equals(_configurationSettings.ServiceType, "default", StringComparison.CurrentCultureIgnoreCase))
                {
                    //Use the LocalFileStorer to write to local disk
                    success = _localFileStorer.WriteFile(formFile, fileMetaData.FileGuid, _configurationSettings.LocalStoragePath);
                }
                else
                {
                    success = await _minioFileStorer.UploadFile(fileMetaData.FileGuid, formFile.OpenReadStream(), fileMetaData.FileType);
                }
            }

            if (!success)
            {
                return(null);
            }
            {
                _mongoDbService.InsertFileDatas(fileMetaDatas);

                var returnGuids = new List <string>();
                foreach (var fileMetaData in fileMetaDatas)
                {
                    returnGuids.Add(fileMetaData.FileGuid);
                }

                return(returnGuids);
            }
        }
Esempio n. 8
0
    private FileMetaData ApplyDefaults(List <string> filters)
    {
        var fileMetaData = new FileMetaData();

        foreach (var filter in filters)
        {
            var meta = _options.Defaults.SingleOrDefault(x => x.Path.Equals(filter));
            if (meta != null)
            {
                OverwriteMetaData(fileMetaData, meta.Values, $"default:{filter}");
            }
        }
        return(fileMetaData);
    }
Esempio n. 9
0
 static void setTarget()
 {
     target = new FileMetaData
                  (movedfile, ismapped, shelved,
                  headaction, headchange, headrev, headtype,
                  headtime, headmodtime, movedrev, haverev,
                  desc, digest, filesize, action, type,
                  actionowner, change, resolved, unresolved,
                  reresolvable, otheropen, otheropenuserclients,
                  otherlock, otherlockuserclients, otheractions,
                  otherchanges, ourlock, resolverecords, attributes,
                  attributedigests, null, null, null, -1, null
                  );
 }
Esempio n. 10
0
        //public void Load(string folderPath)
        //{
        //	FileStream fs = null;
        //	StreamReader sr = null;


        //	try
        //	{
        //		Clear();

        //		fs = new FileStream(folderPath + "/PoseList.lst", FileMode.Open, FileAccess.Read);
        //		sr = new StreamReader(fs);

        //		sr.ReadLine();//"------"
        //		sr.ReadLine();//" Pose List "
        //		sr.ReadLine();//"------"

        //		while(true)
        //		{
        //			//하나씩 돌면서 메타 데이터를 넣자
        //			if(sr.Peek() < 0)
        //			{
        //				break;
        //			}

        //			string strData = sr.ReadLine();

        //			string strFilePath = GetDecodedString(strData);
        //			strData = strData.Substring(3 + strFilePath.Length);

        //			string strPoseName = GetDecodedString(strData);
        //			strData = strData.Substring(3 + strPoseName.Length);

        //			string strDesc = GetDecodedString(strData);
        //			strData = strData.Substring(3 + strDesc.Length);

        //			string strSceneName = GetDecodedString(strData);
        //			strData = strData.Substring(3 + strSceneName.Length);

        //			string strPortraitName = GetDecodedString(strData);
        //			strData = strData.Substring(3 + strPortraitName.Length);

        //			string strMeshGroupName = GetDecodedString(strData);

        //			FileMetaData newMeta = new FileMetaData(strFilePath, strPoseName, strDesc, strSceneName, strPortraitName, strMeshGroupName);

        //			//만약 이름이 겹치는게 있으면 스킵
        //			if(GetMetaData(newMeta._filePath) != null)
        //			{
        //				continue;
        //			}

        //			_metaDataList.Add(newMeta);
        //		}

        //		sr.Close();
        //		fs.Close();

        //		sr = null;
        //		fs = null;
        //	}
        //	catch (Exception ex)
        //	{
        //		if (sr != null)
        //		{
        //			sr.Close();
        //			sr = null;
        //		}

        //		if (fs != null)
        //		{
        //			fs.Close();
        //			fs = null;
        //		}

        //		Save(folderPath);
        //	}
        //}


        //public void Save(string folderPath)
        //{
        //	FileStream fs = null;
        //	StreamWriter sw = null;

        //	try
        //	{
        //		fs = new FileStream(folderPath + "/PoseList.lst", FileMode.Create, FileAccess.Write);
        //		sw = new StreamWriter(fs);

        //		sw.WriteLine("-------------------------------");
        //		sw.WriteLine(" Pose List ");
        //		sw.WriteLine("-------------------------------");
        //		for (int i = 0; i < _metaDataList.Count; i++)
        //		{
        //			FileMetaData metaUnit = _metaDataList[i];

        //			System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //			sb.Append(GetEncodedString(metaUnit._filePath));
        //			sb.Append(GetEncodedString(metaUnit._poseName));
        //			sb.Append(GetEncodedString(metaUnit._description));
        //			sb.Append(GetEncodedString(metaUnit._sceneName));
        //			sb.Append(GetEncodedString(metaUnit._portraitName));
        //			sb.Append(GetEncodedString(metaUnit._meshGroupName));

        //			sw.WriteLine(sb.ToString());
        //		}


        //		sw.Close();
        //		fs.Close();

        //		sw = null;
        //		fs = null;
        //	}
        //	catch (Exception)
        //	{
        //		if (sw != null)
        //		{
        //			sw.Close();
        //			sw = null;
        //		}

        //		if (fs != null)
        //		{
        //			fs.Close();
        //			fs = null;
        //		}

        //	}
        //}


        ///// <summary>
        ///// 실제로 폴더에 있는 데이터를 확인하면서
        ///// </summary>
        //public void RefreshFileInfo(string folderPath)
        //{
        //	DirectoryInfo di = new DirectoryInfo(folderPath);

        //	for (int i = 0; i < _metaDataList.Count; i++)
        //	{
        //		_metaDataList[i]._isExist = false;
        //	}

        //	if(!di.Exists)
        //	{
        //		//존재하지 않는 폴더
        //		return;
        //	}

        //	FileInfo[] fileInfos = di.GetFiles("*.pos");
        //	if(fileInfos == null || fileInfos.Length == 0)
        //	{
        //		return;
        //	}

        //	for (int i = 0; i < fileInfos.Length; i++)
        //	{
        //		FileInfo fi = fileInfos[i];
        //		Debug.Log("[" + i + "] Full Name : " + fi.FullName);//이거 맞는지 체크하자
        //		//TODO

        //	}
        //}
        #endregion


        public void RemoveFile(FileMetaData metaData)
        {
            if (metaData == null)
            {
                return;
            }

            FileInfo fi = new FileInfo(metaData._filePath);

            if (fi.Exists)
            {
                fi.Delete();
            }
        }
Esempio n. 11
0
 private static void ProcessOldData(RayimContext context, FileMetaDataModel model, string fileData)
 {
     if (model.Id > 0)
     {
         FileMetaData dbFileData = context.FileMetaDatas.FirstOrDefault(x => x.Id == model.Id) ?? new FileMetaData();
         if (!string.IsNullOrEmpty(fileData) && !string.IsNullOrEmpty(dbFileData.FilePath))
         {
             IOFileService.DeleteFile(dbFileData.FilePath);
         }
         if (string.IsNullOrEmpty(fileData))
         {
             model.FilePath = dbFileData.FilePath;
         }
     }
 }
Esempio n. 12
0
        public static Boolean DeleteFileData(RayimContext context, int fileId)
        {
            FileMetaData dbFileData = context.FileMetaDatas.FirstOrDefault(x => x.Id == fileId);

            if (dbFileData != null)
            {
                if (!string.IsNullOrEmpty(dbFileData.FilePath))
                {
                    IOFileService.DeleteFile(dbFileData.FilePath);
                }
                context.FileMetaDatas.Remove(dbFileData);
                context.SaveChanges();
            }
            return(dbFileData != null);
        }
Esempio n. 13
0
        public IActionResult Save(string fileName, string fileSize)
        {
            int    curCount = 0;
            string curfilePieceName;
            long   curHashCode;

            try
            {
                if (_inMemoryStorage.Files.ContainsKey(fileName))
                {
                    return(Ok(_inMemoryStorage.Files.GetValueOrDefault(fileName)));
                }
                int  chunkSize       = 20 * 1024;
                long fileTotalSize   = Convert.ToInt64(fileSize);
                int  totalPieceCount = (int)(fileTotalSize / chunkSize);
                if (fileTotalSize % chunkSize != 0)
                {
                    totalPieceCount++;
                }
                FileMetaData fileMetaData = new FileMetaData(fileName, totalPieceCount, chunkSize);
                curCount = totalPieceCount;
                while (curCount > 0)
                {
                    int    pieceIndex    = totalPieceCount - curCount;
                    string filePieceName = Helper.GetFilePieceName(fileName, pieceIndex);
                    long   hashCode      = Helper.GetInt64HashCode(filePieceName);

                    curHashCode      = hashCode;
                    curfilePieceName = filePieceName;
                    //Look for node
                    var keyValuePairs = _serviceNodeMapping.GlobalMappings.SkipWhile(pair => pair.Key < hashCode);
                    if (keyValuePairs.Count() == 0)
                    {
                        hashCode = 0;
                    }
                    int node = _serviceNodeMapping.GlobalMappings.SkipWhile(pair => pair.Key < hashCode).First().Value;
                    fileMetaData.NodeIndexForPieces[pieceIndex] = node;
                    fileMetaData.FilePieceNames[pieceIndex]     = filePieceName;
                    curCount--;
                }
                _inMemoryStorage.Files.Add(fileName, fileMetaData);
                return(Ok(fileMetaData));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Esempio n. 14
0
 public IActionResult Get(string fileName)
 {
     try
     {
         if (!_inMemoryStorage.Files.ContainsKey(fileName))
         {
             return(null);
         }
         FileMetaData fileMetaData = _inMemoryStorage.Files.GetValueOrDefault(fileName);
         return(Ok(fileMetaData));
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
Esempio n. 15
0
        public async Task <Stream> DownLoad(string fileName)
        {
            FileMetaData fileMetaData = await GetFileMetaData(fileName);

            Stream output = new MemoryStream();

            for (int i = 0; i < fileMetaData.FilePieceNames.Length; i++)
            {
                int    nodeIndex       = fileMetaData.NodeIndexForPieces[i];
                string partailFileName = fileMetaData.FilePieceNames[i];
                byte[] buffer          = await RequestPartialFile(partailFileName, nodeIndex);

                output.Write(buffer);
            }
            return(output);
        }
        public ActionResult Edit([Bind(Include = "id,name,description,idCategory")] tbNetVirtualResource tbNetVirtualResource)
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Maestro", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Estudiante", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ViewBag.ControllerName = "tbNetVirtualResources";
            Guid userid = new Guid(AspNetUsers.GetUserId(User.Identity.Name));

            if (ModelState.IsValid)
            {
                var q = (from m in db.tbNetVirtualResource where m.id == tbNetVirtualResource.id select new { m.resource, m.JsonMetadata }).FirstOrDefault();
                if (q != null)
                {
                    tbNetVirtualResource.resource     = q.resource;
                    tbNetVirtualResource.JsonMetadata = q.JsonMetadata;
                }
                List <FileMetaData> mdfiles = JsonConvert.DeserializeObject <List <FileMetaData> >(tbNetVirtualResource.JsonMetadata);
                DateTime            dn      = System.DateTime.Now;
                foreach (string item in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                    int length = file.ContentLength;
                    if (length > 0 && file != null)
                    {
                        byte[] buffer = new byte[length];
                        file.InputStream.Read(buffer, 0, length);
                        PropertyInfo propInfo = typeof(tbNetVirtualResource).GetProperty(item);
                        propInfo.SetValue(tbNetVirtualResource, buffer);
                        FileMetaData fmd = mdfiles.Find(m => m.FileId == item);
                        fmd.ModifiedOn  = System.DateTime.Now;
                        fmd.ContentType = file.ContentType;
                        fmd.Size        = length / 1024;
                    }
                }

                tbNetVirtualResource.JsonMetadata     = JsonConvert.SerializeObject(mdfiles);
                tbNetVirtualResource.idNetVirtualUser = userid;

                db.Entry(tbNetVirtualResource).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.idCategory = new SelectList(db.tbNetVirtualCategoryResource, "id", "name", tbNetVirtualResource.idCategory);
            return(View(tbNetVirtualResource));
        }
        internal CopyFileJob(int chunkIndex, FileMetaData metadata, AdlsClient client) : base(chunkIndex != -1 ? (1 << 32) + ((chunkIndex + 1) * metadata.Transfer.ChunkSize < metadata.TotSize
                    ? metadata.Transfer.ChunkSize
                    : metadata.TotSize - chunkIndex * metadata.Transfer.ChunkSize) : metadata.TotSize)
        {
            ChunkIndex = chunkIndex;
            Metadata   = metadata;
            Client     = client;
            //For upload it is the guid file for that chunk if the file size is greater than 256 mb,
            //for download it is guid file for the whole Destination file if the file is greater than 256mb
            Destination = Metadata.GetChunkFileName(ChunkIndex);
            //If one file then length is whole file length, if chunked and it is not the last chunk then it is 240 MB else it is the last chunk size which might be less than 240 MB
            _lengthToRead = ChunkIndex == -1 ? Metadata.TotSize : (Metadata.Transfer.ChunkSize * (ChunkIndex + 1) < Metadata.TotSize
                    ? Metadata.Transfer.ChunkSize : Metadata.TotSize - (ChunkIndex * Metadata.Transfer.ChunkSize));

            //For a non chunked file offset will always be zero, else it will be multiple of 256MB
            _offset = ChunkIndex <= 0 ? 0 : Metadata.Transfer.ChunkSize * ChunkIndex;
        }
Esempio n. 18
0
        public override string RunTemplate()
        {
            string fileName = FileMetaData.GetFullLocationPathWithFileName();

            if (File.Exists(fileName))
            {
                var result = new StringBuilder();
                result.Append(@"//IntentManaged[configs]" + Environment.NewLine);
                result.Append(string.Join(Environment.NewLine, ConfigItems.Select(x => $"    {x.Key}: \"{x.Value}\",")));
                result.Append(Environment.NewLine + @"//IntentManaged[configs]" + Environment.NewLine);
                return(result.ToString());
            }
            else
            {
                return(TransformText());
            }
        }
Esempio n. 19
0
        public static void Send(string fileName, string path, ChordNode node)
        {
            var key = ChordServer.GetHash(fileName);

            Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);

            var request = new FileUploadMessage();

            var fileMetadata = new FileMetaData(fileName);

            request.Metadata       = fileMetadata;
            request.FileByteStream = fileStream;

            var conteinerNode = ChordServer.CallFindContainerKey(node, key);

            ChordServer.Instance(conteinerNode).AddNewFile(request);
        }
        static public void RasterMapFileUpload()
        {
            string fileName = "TainanFloodZone4_201609271100.nc";
            string filePath = Directory.GetCurrentDirectory();

            FileMetaData fmd = new FileMetaData()
            {
                name        = "TainanFlood",
                description = "MyTest",
                shareLevel  = "private",
            };

            if (_userApiClient.RasterMapFileUpload($"{filePath}\\{fileName}", true, fmd) == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"{fileName}圖資檔案上傳成功");
            }
        }
        public ActionResult Create([Bind(Include = "id,name,description")] tbNetVirtualGroup tbNetVirtualGroup)
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Maestro", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ViewBag.ControllerName = "tbNetVirtualGroups";
            if (ModelState.IsValid)
            {
                List <FileMetaData> mdfiles = new List <FileMetaData>();
                DateTime            dn      = System.DateTime.Now;
                foreach (string item in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                    int length = file.ContentLength;
                    if (length > 0 && file != null)
                    {
                        byte[] buffer = new byte[length];
                        file.InputStream.Read(buffer, 0, length);
                        PropertyInfo propInfo = typeof(tbNetVirtualGroup).GetProperty(item);
                        propInfo.SetValue(tbNetVirtualGroup, buffer);
                        FileMetaData fmd = new FileMetaData()
                        {
                            FileId = item, CreatedOn = dn, ModifiedOn = dn, ContentType = file.ContentType, Size = length / 1024
                        };
                        mdfiles.Add(fmd);
                    }
                }
                tbNetVirtualGroup.state        = false;
                tbNetVirtualGroup.JsonMetadata = JsonConvert.SerializeObject(mdfiles);
                tbNetVirtualGroup.createDate   = System.DateTime.Now;
                db.tbNetVirtualGroup.Add(tbNetVirtualGroup);
                //---------------------------------
                Guid userid = new Guid(AspNetUsers.GetUserId(User.Identity.Name));
                tbNetVirtualUserGroup nvug = new tbNetVirtualUserGroup();
                nvug.idNetVirtualGroup   = tbNetVirtualGroup.id;
                nvug.idNetVirtualUser    = userid;
                nvug.isOwner             = true;
                nvug.StateUserAceptGroup = 0;
                db.tbNetVirtualUserGroup.Add(nvug);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(tbNetVirtualGroup));
        }
Esempio n. 22
0
        public override string RunTemplate()
        {
            string fileName = FileMetaData.GetFullLocationPathWithFileName();

            if (File.Exists(fileName))
            {
                var result = new StringBuilder();
                result.Append(@"//IntentManaged[modules]" + Environment.NewLine);
                result.Append(string.Join(Environment.NewLine, AngularModules.Select(x => $"\t\t\t, \"{x}\"")));
                result.Append(Environment.NewLine + @"//IntentManaged[modules]" + Environment.NewLine);
                return(result.ToString());
            }
            else
            {
                return(TransformText());
            }
        }
Esempio n. 23
0
        public HttpResponseMessage SearchFileInDownloadDirectory(string fileName)
        {
            List <FileMetaData> filesMetaData = new List <FileMetaData>();
            FileMetaData        metaData      = new FileMetaData();

            try
            {
                string[] files = Directory.GetFiles(this.GetDownloadPath(), fileName, SearchOption.AllDirectories);

                if (files != null && files.Count() > 0)
                {
                    foreach (string file in files)
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        metaData = new FileMetaData();
                        metaData.FileResponseMessage.IsExists = true;
                        metaData.FileName      = fileName;
                        metaData.FileExtension = fileInfo.Extension;
                        metaData.FileSize      = fileInfo.Length;
                        metaData.FilePath      = file.Replace(fileInfo.Name, "");
                        filesMetaData.Add(metaData);
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, filesMetaData, new MediaTypeHeaderValue("text/json")));
                }

                filesMetaData.Add(new FileMetaData()
                {
                    FileResponseMessage = new FileResponseMessage
                    {
                        IsExists = false,
                        Content  = string.Format("{0} file is not found !", fileName)
                    }
                });

                return(Request.CreateResponse(HttpStatusCode.NotFound, filesMetaData, new MediaTypeHeaderValue("text/json")));
            }
            catch (Exception exception)
            {
                // Log exception and return gracefully
                metaData = new FileMetaData();
                metaData.FileResponseMessage.Content = ProcessException(exception);
                filesMetaData.Add(metaData);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, filesMetaData, new MediaTypeHeaderValue("text/json")));
            }
        }
Esempio n. 24
0
        public async Task TestFileDownloadStreamAsync()
        {
            // Setup
            if (MockData)
            {
                MockResponses(8);
            }
            await User.LoginAsync(TestSetup.user, TestSetup.pass, kinveyClient);

            // Arrange
            FileMetaData uploadMetaData = new FileMetaData();

            uploadMetaData.fileName = image_name;
            uploadMetaData._public  = true;

            byte[] content     = System.IO.File.ReadAllBytes(image_path);
            int    contentSize = (content.Length) * sizeof(byte);

            uploadMetaData.size = contentSize;
            MemoryStream uploadStreamContent = new MemoryStream(content);
            FileMetaData uploadFMD           = await kinveyClient.File().uploadAsync(uploadMetaData, uploadStreamContent);

            FileMetaData downloadMetaData = new FileMetaData();

            downloadMetaData = await kinveyClient.File().downloadMetadataAsync(uploadFMD.id);

            downloadMetaData.id = uploadFMD.id;
            MemoryStream downloadStreamContent = new MemoryStream();

            // Act
            FileMetaData downloadFMD = await kinveyClient.File().downloadAsync(downloadMetaData, downloadStreamContent);

            FileStream fs = new FileStream(downloadStreamFilePath, FileMode.Create);

            downloadStreamContent.WriteTo(fs);
            downloadStreamContent.Close();
            fs.Close();

            //Teardown
            await kinveyClient.File().delete(uploadFMD.id);

            // Assert
            Assert.IsNotNull(content);
            Assert.IsTrue(content.Length > 0);
        }
Esempio n. 25
0
        /// <summary>
        /// Upload file to cloud
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileMetaData metaData = new FileMetaData()
                {
                    fileName = System.IO.Path.GetFileName(ofd.FileName)
                };
                try
                {
                    FileStream fstream = File.OpenRead(ofd.FileName);
                    if (fstream.Length > Crypto.MaxMessageSize)
                    {
                        throw new MaxSizeException("Velicina fajla prelazi maksimalnu dozvoljednu velicinu.");
                    }

                    Task <bool> uploadTask = Task.Run(() => csClient.UploadFile(metaData, fstream));
                    var         success    = await uploadTask;

                    if (success)
                    {
                        MessageBox.Show(String.Format("Fajl: {0} je uploadovan na server cloud.", metaData.fileName), "Cloud Upload");
                        serviceFiles.Add(metaData.fileName);
                        listBox.DataSource = null;
                        listBox.DataSource = serviceFiles;
                    }
                    else
                    {
                        MessageBox.Show(String.Format("Fajl: {0} nije uspesno uploadovan na server cloud.", metaData.fileName), "Cloud Upload");
                    }
                }

                catch (MaxSizeException me)
                {
                    MessageBox.Show(me.Message);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Greska pri uploadovanju fajla.");
                }
            }
        }
        public static void saveUpdate(UpdateEntity entity, Stream bytes, KinveyDelegate <UpdateEntity> delegates)
        {
            AsyncAppData <UpdateEntity> appData = getClient().AppData <UpdateEntity> (update_collection, typeof(UpdateEntity));

            FileMetaData fm = new FileMetaData();

            fm.acl = new AccessControlList();
            fm.acl.globallyReadable = true;
            fm._public = true;

            getClient().File().upload(fm, bytes, new KinveyDelegate <FileMetaData> {
                onSuccess = (meta) => {
                    entity.attachement = new KinveyFile(meta.id);
                    appData.Save(entity, delegates);
                },
                onError = (error) => {
                }
            });
        }
Esempio n. 27
0
        public List <FileMetaData> GetFilePaths()
        {
            _fileDirectories = Directory.GetFiles(_MusicDirectory, _FileFormat, SearchOption.AllDirectories).ToList();
            _fileList        = new List <FileMetaData>();

            foreach (var item in _fileDirectories)
            {
                _fileInfo = new FileMetaData
                {
                    FileLocation = item,
                };

                _fileList.Add(_fileInfo);
            }

            _directoriesFound = _fileList.Count();

            return(_fileList);
        }
Esempio n. 28
0
        public Boolean DownloadSharingFile(Protocal.SharingInfo si)
        {
            String copyRef  = si.Reference;
            String fileName = si.FileName;

            try
            {
                String dropboxPath = BaseExtension.FileStringHelper.GetNonConflictFileName(Path.Combine(DropBoxController.DropBox_DownloadFolder, fileName));

                UserKey uk      = PreKeyring.UserKey;
                PRE_KEY userKey = new PRE_KEY();
                userKey.PK.PK1 = uk.PK1;
                userKey.PK.PK2 = uk.PK2;
                userKey.SK.X1  = uk.SK1;
                userKey.SK.X2  = uk.SK2;

                PRE_Cipher CKey = new PRE_Cipher();
                CKey.E = si.CKey_E;
                CKey.F = si.CKey_F;
                CKey.U = si.CKey_U;
                CKey.W = si.CKey_W;

                String key = ProxyReEncryption.KeyDecrypt(userKey, CKey);

                FileMetaData fi = new FileMetaData();
                fi.FileName      = fileName;
                fi.FilePath      = this.dropBoxController.DropboxSecuruStikFolder2SecuruStikFolder(dropboxPath);
                fi.Key           = key;
                fi.PlainTextHash = "";
                fi.CryptTextHash = "";
                PreKeyring.FileInfo_Update(fi);

                String dropboxRemotePath = this.dropBoxController.SecuruStikFolder2RemoteDropboxPath(fi.FilePath);
                this.dropBoxController.CopyAsync(copyRef, dropboxRemotePath);
            }
            catch (System.Exception ex)
            {
                log.ErrorFormat("DownloadSharingFile {0}", si.FileName, ex);
                PreKeyring.SharingFile_Delete(si.Reference);
                return(false);
            }
            return(true);
        }
        public ActionResult Create([Bind(Include = "name,description,idCategory")] tbNetVirtualResource tbNetVirtualResource)
        {
            if (!(AspNetUsersRoles.IsUserInRole("Administrator", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Maestro", User.Identity.Name) || AspNetUsersRoles.IsUserInRole("Estudiante", User.Identity.Name)))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ViewBag.ControllerName = "tbNetVirtualResources";
            Guid userid = new Guid(AspNetUsers.GetUserId(User.Identity.Name));

            if (ModelState.IsValid)
            {
                List <FileMetaData> mdfiles = new List <FileMetaData>();
                DateTime            dn      = System.DateTime.Now;
                foreach (string item in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                    int length = file.ContentLength;
                    if (length > 0 && file != null)
                    {
                        byte[] buffer = new byte[length];
                        file.InputStream.Read(buffer, 0, length);
                        PropertyInfo propInfo = typeof(tbNetVirtualResource).GetProperty(item);
                        propInfo.SetValue(tbNetVirtualResource, buffer);
                        FileMetaData fmd = new FileMetaData()
                        {
                            FileId = item, CreatedOn = dn, ModifiedOn = dn, ContentType = file.ContentType, Size = length / 1024
                        };
                        mdfiles.Add(fmd);
                    }
                }

                tbNetVirtualResource.JsonMetadata     = JsonConvert.SerializeObject(mdfiles);
                tbNetVirtualResource.idNetVirtualUser = userid;
                db.tbNetVirtualResource.Add(tbNetVirtualResource);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }


            ViewBag.idCategory = new SelectList(db.tbNetVirtualCategoryResource, "id", "name", tbNetVirtualResource.idCategory);
            return(View(tbNetVirtualResource));
        }
Esempio n. 30
0
        public async Task <FileMetaData> GetFileMetaData(string fileName)
        {
            var client  = new RestClient(_globalVariables.GetFileMatedataURL + $"?fileName={fileName}");
            var request = new RestRequest(Method.GET);

            request.AddHeader("cache-control", "no-cache");
            IRestResponse response = await client.ExecuteTaskAsync(request);

            FileMetaData fileMetaData = null;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                fileMetaData = JsonConvert.DeserializeObject <FileMetaData>(response.Content);
            }
            if (fileMetaData == null)
            {
                throw new Exception("Cannot get split meta data");
            }
            return(fileMetaData);
        }
Esempio n. 31
0
        public override IndexOutput CreateOutput(string name)
        {
            if (0 == _fileContenteCollection.Count(fc => fc.Name == name))
            {
                var fileContent = new FileContent {
                    Name = name
                };
                _fileContenteCollection.Insert(fileContent);
            }
            if (0 == _fileMetaDataCollection.Count(fm => fm.Name == name))
            {
                var fileMetaData = new FileMetaData {
                    Name = name, LastTouchedTimestamp = DateTime.UtcNow
                };
                _fileMetaDataCollection.Insert(fileMetaData);
            }
            GC.Collect();

            return(new LiteDbIndexOutput(_db, name));
        }
Esempio n. 32
0
        public async Task TestFileDeleteAsync()
        {
            // Setup
            if (MockData)
            {
                MockResponses(6);
            }

            await User.LoginAsync(TestSetup.user, TestSetup.pass, kinveyClient);

            // Arrange
            var fileMetaData = new FileMetaData
            {
                fileName = image_name
            };
            var publicAccess = true;

            fileMetaData._public = publicAccess;
            var content     = System.IO.File.ReadAllBytes(image_path);
            int contentSize = (content.Length) * sizeof(byte);

            fileMetaData.size = contentSize;

            var fmd = await kinveyClient.File().uploadAsync(fileMetaData, content);

            // Act
            var deleteResponse = await kinveyClient.File().delete(fmd.id);

            // Assert
            Assert.IsNotNull(deleteResponse);
            Assert.AreEqual(1, deleteResponse.count);

            var exception = await Assert.ThrowsExceptionAsync <KinveyException>(async delegate()
            {
                await kinveyClient.File().downloadMetadataAsync(fmd.id);
            });

            Assert.AreEqual(404, exception.StatusCode);
            Assert.AreEqual(EnumErrorCategory.ERROR_BACKEND, exception.ErrorCategory);
            Assert.AreEqual(EnumErrorCode.ERROR_JSON_RESPONSE, exception.ErrorCode);
        }
Esempio n. 33
0
        public override string TransformText()
        {
            var location = FileMetaData.GetFullLocationPathWithFileName();
            var doc      = LoadOrCreate(location);

            var namespaces = new XmlNamespaceManager(new NameTable());

            namespaces.AddNamespace("ns", doc.Root.GetDefaultNamespace().NamespaceName);

            var generatedNode = doc.XPathSelectElement("/ns:someSchema/ns:generatedSettings", namespaces);

            generatedNode.RemoveNodes();

            foreach (var kvp in Model)
            {
                var setting = new XElement(kvp.Key);
                setting.Value = kvp.Value;
                generatedNode.Add(setting);
            }
            return(doc.ToStringUTF8());
        }
Esempio n. 34
0
    public static void UploadFile(string localFileName,FileTypeEnum fileType)
    {
        eAdDataAccess.ServiceClient service = new ServiceClient("BasicHttpBinding_IService", Constants.ServerAddress);
        try
        {
            using (Stream fileStream = new FileStream(localFileName, FileMode.Open, FileAccess.Read))
            {
                //    var request = new FileUploadMessage();
                string remoteFileName = null;
                if (fileType == FileTypeEnum.Generic)
                {
                    // WE ARE USING THE SERVICE AS A "FTP ON WCF"
                    // GIVE THE REMOTE FILE THE SAME NAME AS THE LOCAL ONE
                    remoteFileName = Path.GetFileName(localFileName);
                }

                var fileMetadata = new FileMetaData { LocalFilename = localFileName, RemoteFilename = remoteFileName,FileType = fileType};
                //     request.MetaData = fileMetadata;
                //     request.FileByteStream = fileStream;

                //service.UploadFile(fileMetadata,fileStream);
                service.Close();

            }
        }
        catch (TimeoutException exception)
        {
            Console.WriteLine("Got {0}", exception.GetType());
            service.Abort();
        }
        catch (CommunicationException exception)
        {
            Console.WriteLine("Got {0}", exception.GetType());
            service.Abort();
        }
    }
 private void lwFiles_ItemActivate(object sender, EventArgs e)
 {
     if (lwFiles.SelectedItems.Count == 1)
     {
         var fileMetaData = new FileMetaData();
         fileMetaData.FileId = Convert.ToInt32(lwFiles.SelectedItems[0].Text);
         GetFileMessage gfm = new GetFileMessage();
         gfm.Metadata = fileMetaData;
         //Library.File activeFile = fileClient.GetFile(gfm).file;
         activeFile = fileClient.GetFile(gfm).file;
         lblFIleInfo.Text = activeFile.Title;
         txtFileDesc.Text = activeFile.Description;
         btnDownload.Visible = true;
         ChatMessage[] messages = chatService.GetLast20MessagesFromFile(activeFile);
         listBox_Filechat.Items.Clear();
         LastDate = DateTime.MinValue;
         UpdateChat(messages);
     }
 }