/// <summary> /// This canWrite() method return true if user has write permission /// </summary> /// <param name="userID"></param> /// <param name="containerID"></param> /// <returns></returns> public Boolean canWrite(int userID, int containerID) { if (isOwner(userID, containerID)) { return(true); } DBManager.CListM cmgr = new DBManager.CListM(); DBManager.ResourceM resmgr = new DBManager.ResourceM(); Model.AzureContainerModel rmodel = new Model.AzureContainerModel(); try { rmodel = resmgr.getResourceById(connection, containerID); String permission = cmgr.checkResourcePermission(connection, userID, rmodel.getContainerName()); if (permission.Equals("WRITE")) { return(true); } } catch (DBLikeExceptions.CloudContainerNotFoundException) { return(false); } return(false); }
/// <summary> /// This method inserts record to the CONTAINERS table. /// </summary> /// <param name="connection"></param> /// <param name="uid"></param> /// <param name="containerName"></param> /// <returns>true/false</returns> public Boolean insertIntoResources(SqlConnection connection, Model.AzureContainerModel resource) { try { //---Should have used auto-increment command = new SqlCommand("SELECT MAX(RID) FROM CONTAINERS", connection); reader = command.ExecuteReader(); int rid = 10000; //starting resource id from 10001 if (!reader.HasRows) { rid = rid + 1; } else { while (reader.Read()) { rid = reader.GetInt32(0); } rid = rid + 1; } Console.WriteLine("Resource ID" + rid); command = new SqlCommand("INSERT INTO CONTAINERS (RID, GIVENNAME, OWNER, CONTAINERNAME) VALUES (@RID, @GIVENNAME, @OWNER, @CONTAINERNAME)"); command.CommandType = CommandType.Text; command.Connection = connection; command.Parameters.AddWithValue("@RID", rid); command.Parameters.AddWithValue("@GIVENNAME", resource.getGivenName()); command.Parameters.AddWithValue("@OWNER", resource.getOwner()); command.Parameters.AddWithValue("@CONTAINERNAME", resource.getContainerName()); command.ExecuteNonQuery(); /* Following table retains the entry of user-resource which is sharing * Model.CListModel cm = new Model.CListModel(); * cm.setRid(rid); * cm.setUid(uid); * cm.setReadwrite(1); * reader.Close(); * CListM c = new CListM(); * * //on adding resource, the default will be given to resource {DEFAULT(READ, READWRITE) = True} * return c.insertIntoCList(connection, cm); */ } catch (Exception e) { Console.WriteLine("insertIntoResources in class User says->" + e.Message); return(false); } reader.Close(); return(true); }
/// <summary> /// This method returns the list of containers which are shared with given user /// each element seems like "CONTAINERNAME:OWNERFULLNAME:GIVENCONTAINERNAME" //User friendly manner /// </summary> /// <param name="connection"></param> /// <param name="userid"></param> /// <returns>null/string array contains the name of containers</returns> public String[] getSharedContainersWithUser(SqlConnection connection, int userid) { String[] sharedContainers = null; try { command = new SqlCommand("SELECT RID, OWNER FROM CLIST WHERE UID = @UID"); command.CommandType = CommandType.Text; command.Connection = connection; command.Parameters.AddWithValue("@UID", userid); reader = command.ExecuteReader(); //no containers shared with user if (!reader.HasRows) { return(null); } ResourceM r = new ResourceM(); UserM u = new UserM(); int currRid = 0; String ownerName = null; Model.AzureContainerModel cont = new Model.AzureContainerModel(); List <String> containersString = new List <String>(); while (reader.Read()) { currRid = reader.GetInt32(0); cont = r.getResourceById(connection, currRid); Console.WriteLine("Owner: " + reader.GetInt32(1)); ownerName = (u.getUserRecordByID(connection, (reader.GetInt32(1)))).getFullName(); containersString.Add((cont.getContainerName()) + ":" + ownerName + ":" + (cont.getGivenName())); } reader.Close(); sharedContainers = containersString.ToArray(); return(sharedContainers); } catch (SqlException ex) { Console.WriteLine("CListM class: getSharedContainersWithUser method Exception->" + ex.Message); } return(null); }
/// <summary> /// This renameFile() method renames the file /// </summary> /// <param name="username"></param> /// <param name="path"></param> public void renameFile(String username, String path, String newname) //path> containerID:filepath { try { //Break the path <containerID:filepath> String[] pathTokens = path.Split(':'); DBManager.UserM user = new DBManager.UserM(); Model.UserModel u; u = user.getUserRecord(connection, username); String container = pathTokens[0]; String blobfile = pathTokens[1]; DBManager.ResourceM contDetail = new DBManager.ResourceM(); Console.WriteLine("ResourceID:" + container); Model.AzureContainerModel cont = contDetail.getResourceById(connection, Int32.Parse(container)); if (cont.getOwner() != u.getUid()) //user is not owner { Resource res = new Resource(); if (!res.canWrite(u.getUid(), Int32.Parse(container))) //not having write permission { throw new DBLikeExceptions.UnauthorizedAccessException(); } } container = cont.getContainerName(); //Check if container exists CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(container); //Container ref Boolean isContainerexists = BlobStorageManager.BlobStorage.isContainerExists(myContainer); if (isContainerexists == false) { Console.WriteLine("Container not found"); throw new DBLikeExceptions.CloudContainerNotFoundException(); } //Check if blob exists CloudBlockBlob oldblob = BlobStorageManager.BlobStorage.getCloudBlob(container + '/' + blobfile); //Get reference to blob Boolean isBlobexists = BlobStorageManager.BlobStorage.isBlobExists(oldblob); if (isBlobexists == false) { Console.WriteLine("Blob not found"); throw new DBLikeExceptions.CloudBlobNotFoundException(); } ICloudBlob newblob = null; if (oldblob is CloudBlockBlob) { newblob = myContainer.GetBlockBlobReference(newname); } else { newblob = myContainer.GetPageBlobReference(newname); } //CloudBlockBlob newblob = BlobStorageManager.BlobStorage.getCloudBlob(container + '/' + newname); //Get reference to blob //copy the blob newblob.StartCopyFromBlob(oldblob.Uri); while (true) { newblob.FetchAttributes(); if (newblob.CopyState.Status != CopyStatus.Pending) //check the copying status { break; } System.Threading.Thread.Sleep(1000); //sleep for a second } //delete old blobfile oldblob.Delete(); } catch (Microsoft.WindowsAzure.Storage.StorageException e) { Console.WriteLine("File:renameFile says->>" + e.Message); } }
/// <summary> /// This deleteFileFromContainer() methd deletes the given file from the given container /// It may throw exceptions like UnauthorizedAccessException, CloudContainerNotFoundException, CloudBlobNotFoundException /// </summary> /// <param name="username"></param> /// <param name="path"></param> public void deleteFileFromContainer(String username, String path) //path>> containerID:filepath { try { //Break the path <containerID:filepath> String[] pathTokens = path.Split(':'); DBManager.UserM user = new DBManager.UserM(); Model.UserModel u; u = user.getUserRecord(connection, username); if (u == null) { Console.WriteLine("No user found"); return; } String container = pathTokens[0]; String blobfile = pathTokens[1]; String containerAzureName; if (username.Equals(container)) { containerAzureName = u.getUid().ToString(); } else { Resource res = new Resource(); int containerID = res.getContainerID(u.getUid(), container); if (containerID == -1) { throw new DBLikeExceptions.CloudContainerNotFoundException(); } if (!res.canWrite(u.getUid(), containerID)) { throw new DBLikeExceptions.UnauthorizedAccessException(); } DBManager.ResourceM contDetail = new DBManager.ResourceM(); //Console.WriteLine("ResourceID:" + container); Model.AzureContainerModel cont = contDetail.getResourceById(connection, containerID); if (cont == null) { throw new DBLikeExceptions.CloudContainerNotFoundException(); } containerAzureName = cont.getContainerName(); } //if (cont.getOwner() != u.getUid()) //user is not owner //{ // Resource res = new Resource(); // if (!res.canWrite(u.getUid(), Int32.Parse(container))) //not having write permission // { // throw new DBLikeExceptions.UnauthorizedAccessException(); // } //} //Check if container exists CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(containerAzureName); //Container ref Boolean isContainerexists = BlobStorageManager.BlobStorage.isContainerExists(myContainer); if (isContainerexists == false) { throw new DBLikeExceptions.CloudContainerNotFoundException(); } //Check if blob exists try { CloudBlockBlob myblob = BlobStorageManager.BlobStorage.getCloudBlob(containerAzureName + '/' + blobfile); //Get reference to blob Boolean isBlobexists = BlobStorageManager.BlobStorage.isBlobExists(myblob); if (isBlobexists == false || myblob.Properties.ContentType.Equals("file/deleted")) { Console.WriteLine("Blob not found or deleted"); throw new DBLikeExceptions.CloudBlobNotFoundException(); } myblob.DeleteIfExists(); myblob.UploadFromByteArray(new byte[0], 0, 0); myblob.Properties.ContentType = "file/deleted"; myblob.SetProperties(); } catch (Microsoft.WindowsAzure.Storage.StorageException e) { Console.WriteLine("File:deleteFileFromContainer says->>" + e.Message); throw new DBLikeExceptions.CloudBlobNotFoundException(); } } catch (Exception) { throw; } }
/// <summary> /// This method returns a list of strings as follows: /// > if 'path' is empty, a list of all containers that username can access /// > else path format userid:containername, it will list all files in given container /// THROW UNAUTHORIZEDACCESSEXCEPTION IF USER HAS NO RIGHT TO ACCESS THE MENTIONED PATH /// </summary> /// <param name="username"></param> /// <param name="path"></param> /// <returns></returns> public String[] list(String emailID, String givencontainerName) //path containerName { DBManager.ResourceM resource = new DBManager.ResourceM(); DBManager.UserM user = new DBManager.UserM(); Model.UserModel u = new Model.UserModel(); u = user.getUserRecord(connection, emailID); if (String.IsNullOrEmpty(givencontainerName)) { Console.WriteLine("LIST ALL CONTAINERS FOR {0}", u.getUid()); DBManager.CListM cl = new DBManager.CListM(); String[] sharedContainers = null; sharedContainers = cl.getSharedContainersWithUser(connection, u.getUid());//CONTAINERNAME:OWNERFULLNAME:GIVENCONTAINERNAME //Get the list of containers user owns String[] containers = null; containers = resource.getContainersOwnedByUser(connection, u.getUid()); //<CONTAINERNAME:GIVENNAME> Console.WriteLine("Total containers OWNED BY user : {0}", (containers.Length)); //Console.WriteLine("Total containers SHARED WITH user: {0}", sharedContainers.Length); //sometimes cause problem no share container exists String[] allContainers; if (sharedContainers == null) { allContainers = new String[containers.Length]; containers.CopyTo(allContainers, 0); } else { allContainers = new String[containers.Length + sharedContainers.Length]; containers.CopyTo(allContainers, 0); sharedContainers.CopyTo(allContainers, containers.Length); } return(allContainers); } Console.WriteLine("GIVEN CONT: " + givencontainerName + " uid: " + u.getUid()); string containerName; if (givencontainerName.Equals(emailID)) //Considering this new change, I'm going to map containername with user email id { containerName = u.getUid().ToString(); } else { Resource r = new Resource(); int containerID = r.getContainerID(u.getUid(), givencontainerName); if (containerID == -1) { throw new DBLikeExceptions.CloudContainerNotFoundException(); } DBManager.ResourceM rmgr = new DBManager.ResourceM(); Model.AzureContainerModel cont = rmgr.getResourceById(connection, containerID); if (cont == null) { return(new String[0]); } containerName = cont.getContainerName(); } Console.WriteLine(containerName); //Obtain reference of user's blob container CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(containerName); List <String> blobs = new List <String>(); //List the files(or blobs) contained by folder(or container) foreach (var blobItem in myContainer.ListBlobs()) { //Console.WriteLine(blobItem.Uri+","); if (blobItem is CloudBlobDirectory) { addRecursive((CloudBlobDirectory)blobItem, blobs); } else { addFile(blobItem.Uri.LocalPath, blobs); } } String[] blobnames = blobs.ToArray(); return(blobnames); }
/// <summary> /// This method takes (username, path{containerid:path}, local path) and download file from blob storage /// to given local path /// THROW UNAUTHORIZEDACCESSEXCEPTION IF USER HAS NO RIGHT TO ACCESS THE MENTIONED PATH /// THROW CLOUDBLOBNOTFOUNDEXCEPTION or CLOUDBLOBNOTFOUNDEXCEPTION IF GIVEN FILEPATH DOESN'T EXISTS /// </summary> /// <param name="username"></param> /// <param name="path"></param> /// <param name="data"></param> public void download(String username, String path, Stream targetStream) //containerid:filepath { try { //Break the path <containerid> String[] usercont = path.Split(':'); DBManager.UserM user = new DBManager.UserM(); Model.UserModel u; u = user.getUserRecord(connection, username); String containerP = usercont[0]; String blobname = usercont[1]; /* * Model.UserModel u2; * u2 = user.getUserRecord(connection, srcUser); * * String userid = u2.getUid().ToString(); * String fullpath = usercont[1]; * String blobName = fullpath.Substring(fullpath.IndexOf('/')+1); * //String container = fullpath.Substring(0, fullpath.IndexOf('/')); */ String container = containerP; DBManager.ResourceM contDetail = new DBManager.ResourceM(); Console.WriteLine("ResourceID:" + containerP); Model.AzureContainerModel cont = contDetail.getResourceById(connection, Int32.Parse(containerP)); Resource res = new Resource(); if (cont.getOwner() != u.getUid()) //user isn't owner { if (!res.canRead(u.getUid(), Int32.Parse(containerP))) //not having read permission { throw new DBLikeExceptions.UnauthorizedAccessException(); } } container = cont.getContainerName(); //Check if container exists CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(container); Boolean isContainerexists = BlobStorageManager.BlobStorage.isContainerExists(myContainer); if (isContainerexists == false) { throw new DBLikeExceptions.CloudContainerNotFoundException(); } //Check if blob exists CloudBlockBlob myblob = BlobStorageManager.BlobStorage.getCloudBlob(container + '/' + blobname); //Get reference to blob Boolean isBlobexists = BlobStorageManager.BlobStorage.isBlobExists(myblob); if (isBlobexists == false) { Console.WriteLine("Container not found"); throw new DBLikeExceptions.CloudBlobNotFoundException(); } Console.WriteLine(myblob); myblob.DownloadToStream(targetStream); } catch (Microsoft.WindowsAzure.Storage.StorageException ex) { //throw new Microsoft.WindowsAzure.Storage.StorageException(); Console.WriteLine("download method in User class says->" + ex.Message); return; } }
/// <summary> /// This method takes (path{containerID:path}, local path) and uploads the file to blob storage /// THROW UNAUTHORIZEDACCESSEXCEPTION IF USER HAS NO RIGHT TO ACCESS THE MENTIONED PATH /// NOTE---------------->>>>>>>>>> /// For uploading, first need to pass the containerID in path which can be obtained by using Resource:getContainerID() /// then check for write permission using Resource:canWrite() then call this operation /// For example : /// Path <9043: bar/foo.txt> means we want to create a folder named bar and save foo.txt file in container 9043 /// </summary> /// <param name="username"></param> /// <param name="path"></param> /// <param name="data"></param> public void upload(UPLOAD_INFO info, String localpath) { try { String username = info.username; String path = info.path; DBManager.UserM umgr = new DBManager.UserM(); Model.UserModel user = new Model.UserModel(); user = umgr.getUserRecord(connection, username); //Break the path <containerid:path> String[] pathTokens = path.Split(':'); String destinationCont = pathTokens[0]; String destinationPath = pathTokens[1]; String mycontainer = destinationCont; CloudBlobContainer destContainer; if (username.Equals(destinationCont)) { Console.WriteLine("File.cs#upload(): Writing to user private area."); destContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(user.getUid().ToString()); } else { DBManager.ResourceM contDetail = new DBManager.ResourceM(); Resource res = new Resource(); int containerId = res.getContainerID(user.getUid(), destinationCont); if (containerId == -1) { throw new DBLikeExceptions.CloudContainerNotFoundException("File.cs#upload: no container"); } Model.AzureContainerModel container = contDetail.getResourceById(connection, containerId); Console.WriteLine("File.cs#upload(): Writing to shared container {0}", container.getContainerName()); destContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(container.getContainerName()); } /* * Console.WriteLine("ResourceID:" + destinationCont); * * Resource res = new Resource(); * * if (container.getOwner() != user.getUid()) //user is not owner * { * if (!res.canWrite(user.getUid(), Int32.Parse(destinationCont))) //not having write permission * { * throw new DBLikeExceptions.UnauthorizedAccessException(); * } * } * mycontainer = container.getContainerName(); * */ //CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(mycontainer); String blobName = String.Format(destinationPath); CloudBlockBlob file = destContainer.GetBlockBlobReference(blobName); using (FileStream fstream = new FileStream(localpath, FileMode.Open)) { file.UploadFromStream(fstream); } BlobStorageManager.BlobFileHandler bhandler = new BlobStorageManager.BlobFileHandler(); //fstream = new FileStream(localpath, FileMode.Open); //file.Properties. file.Metadata["HashValue"] = info.curHash; file.Metadata["ClientModifyTime"] = info.utcTime.Ticks.ToString(); file.SetMetadata(); file.Properties.ContentType = "file/active"; file.SetProperties(); } catch (Microsoft.WindowsAzure.Storage.StorageException ex) { Console.WriteLine("upload method in User class says-> " + ex); } }
/// <summary> /// This deleteSharedContainer() method just deletes container as per given containerID /// which means pre-check is required to call this method /// </summary> /// <param name="containerID"></param> /// <returns>true/false/exception</returns> public Boolean deleteSharedContainer(int containerID) { //throw new NotImplementedException(); //Console.WriteLine("DeleteSharedCOntainer NYI"); try { Model.AzureContainerModel res = new Model.AzureContainerModel(); DBManager.ResourceM rmgr = new DBManager.ResourceM(); res = rmgr.getResourceById(connection, containerID); CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(res.getContainerName()); //Container ref Boolean isContainerexists = BlobStorageManager.BlobStorage.isContainerExists(myContainer); if (isContainerexists == false) { throw new DBLikeExceptions.CloudContainerNotFoundException(); } if (myContainer.ListBlobs().GetEnumerator().MoveNext()) { throw new ArgumentException("container not empty"); } myContainer.Delete(); //Delete from database DBManager.CListM cmgr = new DBManager.CListM(); if (cmgr.deleteUserEntryFromCLIST(connection, 0, containerID)) //delete all records from CLIST { if (rmgr.deleteContainerEntryFromCONTAINERS(connection, containerID.ToString())) //delete from CONTAINERS { return(true); } } } catch (Microsoft.WindowsAzure.Storage.StorageException e) { Console.WriteLine("Resource:deleteSharedContainer Exception:" + e.Message); } return(false); }