Beispiel #1
0
        /// <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);
            }
        }
Beispiel #2
0
        /// <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);
        }
Beispiel #3
0
        /// <summary>
        /// This removeRights() method revoke the user right by deleting the record from CLIST table
        /// </summary>
        /// <param name="otheruserID"></param>
        /// <param name="containerID"></param>
        public void removeRights(int otheruserID, int containerID)
        {
            DBManager.CListM cmgr = new DBManager.CListM();

            try
            {
                cmgr.deleteUserEntryFromCLIST(connection, otheruserID, containerID);

                //CHECK if no user exists in cLIST corresponding to given container
                //if so delete container and omit record form RESOURCE table as well
                Console.WriteLine("ress" + cmgr.isRecordExistsForContainerID(connection, containerID));
                if (!cmgr.isRecordExistsForContainerID(connection, containerID)) //if no other user is sharing this container
                {
                    DBManager.ResourceM rmgr = new DBManager.ResourceM();

                    if (deleteSharedContainer(containerID))
                    {
                        //delete container and entry
                        rmgr.deleteContainerEntryFromCONTAINERS(connection, containerID.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Resource class removeRights method Exception->" + e.Message);
            }
        }
Beispiel #4
0
        /// <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);
            }
        }
Beispiel #5
0
 /// <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);
 }
Beispiel #6
0
        /// <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);
        }
Beispiel #7
0
        /// <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);
        }
        public string getDownloadKey(UPLOAD_INFO f)
        {
            string key;

            lock (pendingUploads)
            {
                while (true)
                {
                    string random1 = Path.GetRandomFileName().Substring(0, 8);
                    string random2 = Path.GetRandomFileName().Substring(0, 8);
                    key = random1 + random2;
                    try
                    {
                        //ADD TIMEOUT NOT SUPPORTED
                        pendingUploads.Add(key, f);
                        break;
                    } catch (ArgumentException) { /* keep trying */ }
                }
            }
            String containerName, blobName, containerAzureName;

            String[] arr = f.path.Split(':');
            containerName = arr[0];
            blobName      = arr[1];

            if (containerName.Equals(f.username))
            {
                containerAzureName = azureLink.findUserId(f.username).ToString();
            }
            else
            {
                int             uid = azureLink.findUserId(f.username);
                IResourceManage r   = new Resource();
                int             rid = r.getContainerID(uid, containerName);
                if (rid == -1)
                {
                    pendingUploads.Remove(key);
                    throw new DBLikeExceptions.CloudContainerNotFoundException();
                }
                if (!r.canWrite(uid, rid))
                {
                    pendingUploads.Remove(key);
                    throw new DBLikeExceptions.UnauthorizedAccessException();
                }
                /* TODO: improve this */
                containerAzureName = new DBManager.ResourceM()
                                     .getResourceById(new DBManager.DBAccess().getDBAccess(), rid)
                                     .getContainerName();
            }
            if (VALIDATE_OLD_HASH)
            {
                try
                {
                    var    blobMgr = new BlobStorageManager.BlobFileHandler();
                    String oldHash = blobMgr.getBlobMD5HashValue(containerAzureName, blobName);
                    if (oldHash != null && !oldHash.Equals(f.prevHash))
                    {
                        throw new DBLikeExceptions.HashConflictException();
                    }
                } catch (DBLikeExceptions.CloudBlobNotFoundException) { /* new file, no old hash */ }
            }
            return(key);
        }
Beispiel #9
0
        /// <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);
            }
        }
Beispiel #10
0
        /// <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;
            }
        }
Beispiel #11
0
        /// <summary>
        /// This downloadWithSAS() method returns URI for downloading file
        /// </summary>
        /// <param name="username"></param>
        /// <param name="path"></param>
        /// <returns></returns>

        public string downloadWithSAS(String username, String path) //containerID:filepath
        {
            string sasUri  = null;
            string sasBUri = null;

            try
            {
                //Break the path <containerID:filepath>
                String[] usercont = path.Split(':');

                DBManager.UserM user = new DBManager.UserM();
                Model.UserModel u;
                u = user.getUserRecord(connection, username);

                String blobname = usercont[1];
                //String blobName = fullpath.Substring(fullpath.IndexOf('/') + 1);
                //String container = fullpath.Substring(0, fullpath.IndexOf('/'));
                String containerGivenName = usercont[0];
                string containerAzureName;
                if (containerGivenName.Equals(username))
                {
                    Console.WriteLine("File.cs#downloadSas: Download from private container");
                    containerAzureName = u.getUid().ToString();
                }
                else
                {
                    Console.WriteLine("File.cs#downloadSas: Download from shared container");
                    Resource            r          = new Resource();
                    int                 rid        = r.getContainerID(u.getUid(), containerGivenName);
                    DBManager.ResourceM contDetail = new DBManager.ResourceM();
                    var                 container  = contDetail.getResourceById(connection, rid);
                    if (container == null)
                    {
                        throw new DBLikeExceptions.CloudContainerNotFoundException();
                    }
                    containerAzureName = container.getContainerName();
                }


                Console.WriteLine("ResourceID:" + containerAzureName);

                /*
                 * Model.AzureContainerModel cont = contDetail.getResourceById(connection, con);
                 *
                 * Resource res = new Resource();
                 * if(cont.getOwner() != u.getUid())
                 * {
                 *  if (!res.canRead(u.getUid(), Int32.Parse(container)))   //not having read permission
                 *  {
                 *      throw new DBLikeExceptions.UnauthorizedAccessException();
                 *  }
                 * }
                 * container = cont.getContainerName();
                 *
                 * Console.WriteLine("blobname: " + blobname);
                 * Console.WriteLine("container: " + container);
                 */
                //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();
                }
                CloudBlockBlob myblob;
                //Check if blob exists
                try
                {
                    myblob = BlobStorageManager.BlobStorage.getCloudBlob(containerAzureName + '/' + blobname); //Get reference to blob
                }
                catch (Microsoft.WindowsAzure.Storage.StorageException)
                {
                    throw new DBLikeExceptions.CloudBlobNotFoundException();
                }

                /*
                 * Boolean isBlobexists = BlobStorageManager.BlobStorage.isBlobExists(myblob);
                 *
                 * if (isBlobexists == false)
                 * {
                 *  Console.WriteLine("Blob not found");
                 *  throw new DBLikeExceptions.CloudBlobNotFoundException();
                 * }*/

                BlobStorageManager.SASGenerator sas = new BlobStorageManager.SASGenerator();
                sasUri  = sas.getContainerSASURI(myContainer);
                sasBUri = sas.getBlobSASURI(myblob);

                Console.WriteLine("Download SAS String: \n" + sasBUri);
            }
            catch (Microsoft.WindowsAzure.Storage.StorageException ex)
            {
                //throw new Microsoft.WindowsAzure.Storage.StorageException();
                Console.WriteLine("sasdownload method in User class says->" + ex.Message);
            }
            return(sasBUri);
        }
Beispiel #12
0
        /// <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);
        }
Beispiel #13
0
        /// <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;
            }
        }
Beispiel #14
0
        /// <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);
            }
        }
Beispiel #15
0
        /// <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);
            }
        }