/// <summary> /// This getResourceByContainerName() method returns the resourcemodel of given container name(unique) /// </summary> /// <param name="connection"></param> /// <param name="containerName"></param> /// <returns>resource id</returns> public Model.AzureContainerModel getResourceByContainerName(SqlConnection connection, String containerName) { Model.AzureContainerModel resource = new Model.AzureContainerModel(); try { command = new SqlCommand("SELECT RID, GIVENNAME, OWNER, CONTAINERNAME FROM CONTAINERS WHERE CONTAINERNAME = @CONTAINERNAME"); command.CommandType = CommandType.Text; command.Connection = connection; command.Parameters.AddWithValue("@CONTAINERNAME", containerName); reader = command.ExecuteReader(); //If no container is owned by user or we can say user has deleted his container if (!reader.HasRows) { throw new DBLikeExceptions.CloudContainerNotFoundException(); } while (reader.Read()) { resource.setRid(reader.GetInt32(0)); resource.setGivenName(reader.GetString(1)); resource.setOwner(reader.GetInt32(2)); resource.setContainerName(reader.GetString(3)); } reader.Close(); return(resource); } catch (Exception e) { Console.WriteLine("getResourceByContainerName in ResourceM class says->" + e.Message); } return(null); }
/// <summary> /// This getResourceByGivenName() method returns the resourcemodel by given container name and its owner /// </summary> /// <param name="connection"></param> /// <param name="uid"></param> /// <param name="givenName"></param> /// <returns>Model.ResourceModel</returns> public Model.AzureContainerModel getResourceByGivenName(SqlConnection connection, int uid, String givenName) { Model.AzureContainerModel resource = new Model.AzureContainerModel(); try { command = new SqlCommand("SELECT RID, GIVENNAME, OWNER, CONTAINERNAME FROM CONTAINERS WHERE OWNER = @OWNER AND GIVENNAME = @GIVENNAME"); command.CommandType = CommandType.Text; command.Connection = connection; command.Parameters.AddWithValue("@OWNER", uid); command.Parameters.AddWithValue("@GIVENNAME", givenName); reader = command.ExecuteReader(); //If no container is owned by user or we can say user has deleted his container if (!reader.HasRows) { return(null); } while (reader.Read()) { resource.setRid(reader.GetInt32(0)); resource.setGivenName(reader.GetString(1)); resource.setOwner(reader.GetInt32(2)); resource.setContainerName(reader.GetString(3)); } reader.Close(); return(resource); } catch (SqlException ex) { Console.WriteLine("ResourceM class: getResourceByGivenname method Exception->" + ex.Message); } return(null); }
/// <summary> /// This method return the containerID by givenname and uid /// returns rid only when uid is listed corresponding to given container name /// else it is considered that there exists no such container for userid /// </summary> /// <param name="userid"></param> /// <param name="givenname"></param> /// <returns>rid/-1</returns> public int getContainerID(int userid, String givenname) { DBManager.ResourceM resmgr = new DBManager.ResourceM(); try { Model.AzureContainerModel resource = new Model.AzureContainerModel(); resource = resmgr.getResourceByGivenName(connection, userid, givenname); if (resource == null) { Model.CListModel cl = new Model.CListModel(); DBManager.CListM cmgr = new DBManager.CListM(); cl = cmgr.getSharedResourceByGivenName(connection, userid, givenname); if (cl == null) { return(-1); } return(cl.getRid()); } else { return(resource.getRid()); } } catch (DBLikeExceptions.CloudContainerNotFoundException) { return(-1); } }
/// <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 grantRights() method set the rights to the otheruserID /// </summary> /// <param name="otheruserID"></param> /// <param name="containerID"></param> /// <param name="writeAccess"></param> /// <returns>true/false</returns> public Boolean grantRights(int otheruserID, int containerID, Boolean writeAccess) { DBManager.ResourceM resmgr = new DBManager.ResourceM(); Model.AzureContainerModel rmodel = new Model.AzureContainerModel(); Model.CListModel cmodel = new Model.CListModel(); try { rmodel = resmgr.getResourceById(connection, containerID); DBManager.CListM cmgr = new DBManager.CListM(); Model.CListModel cmodel1 = new Model.CListModel(); cmodel1 = cmgr.getSharedResourceByGivenName(connection, otheruserID, rmodel.getGivenName()); if (cmodel1 != null) { //If permission already granted to otheruser, then check if requested permission is same Boolean test = false; if (cmodel1.getReadwrite() == 1) { test = true; } if (test == writeAccess) { return(true); //already exist with same permission } else { cmgr.deleteUserEntryFromCLIST(connection, otheruserID, containerID); //delete the record and re-enter } } cmodel.setRid(containerID); cmodel.setUid(otheruserID); cmodel.setOwner(rmodel.getOwner()); if (writeAccess) { cmodel.setReadwrite(1); } else { cmodel.setReadwrite(0); } //Insert into CLIST table bool success = cmgr.insertIntoCList(connection, cmodel); return(success); } catch (DBLikeExceptions.CloudContainerNotFoundException) { 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 checks the user's permission on particular container /// </summary> /// <param name="connection"></param> /// <param name="containerName"></param> /// <returns>NIL/READ/WRITE</returns> public String checkResourcePermission(SqlConnection connection, int uid, String containerName) { ResourceM resource = new ResourceM(); Model.AzureContainerModel r = new Model.AzureContainerModel(); r = resource.getResourceByContainerName(connection, containerName); int resourceID = r.getRid(); try { command = new SqlCommand("SELECT READWRITE FROM CLIST WHERE RID = @RID AND UID = @UID"); command.CommandType = CommandType.Text; command.Connection = connection; command.Parameters.AddWithValue("@UID", uid); command.Parameters.AddWithValue("@RID", resourceID); reader = command.ExecuteReader(); //If no record is available; it means no permission is granted to given user on given container if (!reader.HasRows) { return("NIL"); } int permission = 0; while (reader.Read()) { permission = reader.GetInt32(0); } reader.Close(); if (permission == 0) { return("READ"); } else { return("WRITE"); } } catch (SqlException ex) { Console.WriteLine("CListM class: checkResourcePermission method exception->" + ex.Message); } return("NIL"); }
/// <summary> /// This isOwner() method returns true if given user is owner otherwise false /// FALSE: if container doesn't exit or user is not owner /// </summary> /// <param name="userID"></param> /// <param name="containerID"></param> /// <returns></returns> public Boolean isOwner(int userID, int containerID) { DBManager.ResourceM resmgr = new DBManager.ResourceM(); Model.AzureContainerModel rmodel = new Model.AzureContainerModel(); try { rmodel = resmgr.getResourceById(connection, containerID); if (userID == rmodel.getOwner()) { return(true); } } catch (DBLikeExceptions.CloudContainerNotFoundException) { return(false); } return(false); }
/// <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 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); }
/// <summary> /// This method should return TRUE if user account created successfully /// FALSE if user record already exist in database /// THE CONTAINER IS NAMED AS USERID [unique identifier] /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public Boolean createUser(String fullname, String username, String password) { Model.UserModel user = new Model.UserModel(); DBManager.UserM u = new DBManager.UserM(); user = u.getUserRecord(connection, username); //if user already exist, false if (!(user == null)) { return(false); } //Insert record into USERS table u.insertIntoUsers(connection, fullname, username, password); user = u.getUserRecord(connection, username); //default private container created //Container get created by the unique user id Console.WriteLine("Container created with " + user.getUid() + " name"); Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer((user.getUid()).ToString()); myContainer.CreateIfNotExists(); String containerName = (user.getUid()).ToString(); //Insert record into CONTAINERS table DBManager.ResourceM r = new DBManager.ResourceM(); Console.WriteLine(containerName + "////" + user.getUid()); Model.AzureContainerModel re = new Model.AzureContainerModel(); re.setOwner(user.getUid()); re.setContainerName(containerName); re.setGivenName(user.getEmailId()); //Changed here since server front end is considering private container name as user email id Boolean res = r.insertIntoResources(connection, re); return(res); }
/// <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 createSharedContainer() method creates the shared container which is owned by given userid /// CloudContainerAlreadyExistException if already exists /// </summary> /// <param name="userid"></param> /// <param name="givenname"></param> /// <returns>id for new container on success, else -1</returns> public int createSharedContainer(int userid, String givenname) { DBManager.ResourceM resmgr = new DBManager.ResourceM(); Model.AzureContainerModel resource = new Model.AzureContainerModel(); try { resource = resmgr.getResourceByGivenName(connection, userid, givenname); Model.UserModel user = new Model.UserModel(); DBManager.UserM umgr = new DBManager.UserM(); user = umgr.getUserRecordByID(connection, userid); File f = new File(); String[] list = f.list(user.getEmailId(), ""); for (int i = 0; i < list.Length; i++) { String[] tokens = list[i].Split(':'); if (tokens.Length == 3) { if (tokens[2].Equals(givenname)) //there exist the container with same name { throw new DBLikeExceptions.CloudContainerAlreadyExistException(); } } else if (tokens.Length == 2) { if (tokens[1].Equals(givenname)) //there exist the container with same name { throw new DBLikeExceptions.CloudContainerAlreadyExistException(); } } } if (resource != null) { throw new DBLikeExceptions.CloudContainerAlreadyExistException(); } DBManager.CListM cmgr = new DBManager.CListM(); //cmgr.insertIntoCList(); String[] sharedContainers = cmgr.getSharedContainersOwnedByUser(connection, userid); int counter = 001; //Console.WriteLine("shareddddddddd"+sharedContainers.Length); if (sharedContainers != null) { int size = sharedContainers.Length; String[] containerSuffix = new String[size]; String[] temp; //SHOULD NOT ALLOW USER TO GIVE SAME NAME TO DIFFERENT SHARED CONTAINER for (int i = 0; i < size; i++) { temp = sharedContainers[i].Split(':'); int pos = temp[0].IndexOf("d") + 1; Console.WriteLine("Position" + pos); String scnt = temp[0].Substring(pos); containerSuffix[i] = new string(scnt.Where(char.IsDigit).ToArray()); //no need but leaving as it is } var result = (from m in containerSuffix select m).Max(); Console.WriteLine("result" + result); counter = Int32.Parse(result) + 1; Console.WriteLine("New counter--" + counter); } String containerName = userid + "shared" + counter; CloudBlobContainer myContainer = BlobStorageManager.BlobStorage.getCloudBlobContainer(containerName); myContainer.CreateIfNotExists(); Model.AzureContainerModel resource1 = new Model.AzureContainerModel(); //Insert record into CONTAINERS table resource1.setOwner(userid); resource1.setContainerName(containerName); resource1.setGivenName(givenname); Boolean res = resmgr.insertIntoResources(connection, resource1); if (res) { int rid1 = getContainerID(userid, givenname); return(rid1); } return(-1); } catch (SqlException) { return(-1); } }