public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long uploadSize)
        {
            // build the url
            string url = GetResourceUrl(session, fileSystemEntry, null);

            // get the session creds
            ICredentials creds = session.SessionToken as ICredentials;

            // Build the service
            DavService svc = new DavService();

            // get the service config
            WebDavConfiguration conf = (WebDavConfiguration)session.ServiceConfiguration;

            // build the webrequest
            WebRequest networkRequest = svc.CreateWebRequestPUT(url, creds.GetCredential(null, null), conf.UploadDataStreambuffered);

            // get the request stream
            WebRequestStream requestStream = svc.GetRequestStream(networkRequest, uploadSize);

            // add disposal opp
            requestStream.PushPostDisposeOperation(CommitUploadStream, svc, networkRequest, fileSystemEntry, requestStream);

            // go ahead
            return(requestStream);
        }
        private bool CopyResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, String newTargetUrl)
        {
            // cast to webdav configuration
            WebDavConfiguration config = session.ServiceConfiguration as WebDavConfiguration;
            ICredentials        creds  = session.SessionToken as ICredentials;

            // build url
            String uriString = PathHelper.Combine(config.ServiceLocator.ToString(), GenericHelper.GetResourcePath(fsentry));

            Uri uri       = new Uri(uriString);
            Uri uriTarget = new Uri(newTargetUrl);

            // create the service
            DavService svc = new DavService();

            // create the webrequest
            HttpStatusCode errorCode = svc.PerformCopyWebRequest(uri.ToString(), uriTarget.ToString(), creds.GetCredential(null, null));

            if (errorCode != HttpStatusCode.Created)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
        /// <summary>
        /// This method generates a session to a webdav share via username and password
        /// </summary>
        /// <param name="token"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public override IStorageProviderSession CreateSession(ICloudStorageAccessToken token, ICloudStorageConfiguration configuration)
        {
            // cast the creds to the right type
            WebDavConfiguration config = configuration as WebDavConfiguration;

            // build service
            DavService svc = new DavService();

            // check if url available
            int          status = (int)HttpStatusCode.OK;
            WebException e      = null;

            svc.PerformSimpleWebCall(config.ServiceLocator.ToString(), WebRequestMethodsEx.WebDAV.Options, (token as ICredentials).GetCredential(null, null), null, out status, out e);
            if (status == (int)HttpStatusCode.Unauthorized)
            {
                throw new UnauthorizedAccessException();
            }
            else if (HttpUtilityEx.IsSuccessCode(status))
            {
                return(new WebDavStorageProviderSession(token, config, this));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 4
0
        public virtual StorageFileStreamResult Execute(WebDavConfigurationModel model, string filePath)
        {
            model = model.With(m => !string.IsNullOrEmpty(m.ServerUrl))
                    .With(m => !string.IsNullOrEmpty(m.AccountLogin))
                    .With(m => !string.IsNullOrEmpty(m.AccountPassword));

            if (model == null)
            {
                throw new PluginException(PluginErrorCodes.InvalidCredentialsOrConfiguration);
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new PluginException(PluginErrorCodes.InvalidFileOrDirectoryName);
            }
            else
            {
                filePath = filePath.TrimEnd('/').RemoveCharDuplicates('/');
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new PluginException(PluginErrorCodes.InvalidFileOrDirectoryName);
            }

            StorageFileStreamResult result = new StorageFileStreamResult();

            Uri uri = new Uri(model.ServerUrl);
            ICloudStorageConfiguration config = new WebDavConfiguration(uri);
            GenericNetworkCredentials  cred   = new GenericNetworkCredentials();

            cred.UserName = model.AccountLogin;
            cred.Password = model.AccountPassword;

            CloudStorage storage = null;

            try
            {
                storage = new CloudStorage();
                ICloudStorageAccessToken storageToken = storage.Open(config, cred);
                var file = storage.GetFile(filePath, null);
                result.FileName   = file.Name;
                result.FileStream = file.GetDataTransferAccessor().GetDownloadStream();
            }
            finally
            {
                if (storage != null)
                {
                    storage.Close();
                }
            }

            return(result);
        }
Ejemplo n.º 5
0
        public override FileSystem.NetworkFileSystem CreateConnection()
        {
            GenericNetworkCredentials gnc = new GenericNetworkCredentials();

            gnc.UserName = _username;
            gnc.Password = _password;
            WebDavConfiguration webdav = new WebDavConfiguration(new Uri(_server));

            CloudStorage storage = new CloudStorage();

            storage.Open(webdav, gnc);

            return(null);
        }
Ejemplo n.º 6
0
        public void LoadDefaults()
        {
            var defaults = NSUserDefaults.StandardUserDefaults;

            webDav = TestSuite.GetConfiguration <WebDavConfiguration> ();

            autoRedirect                = ((NSNumber)defaults [kAutoRedirect]).BoolValue;
            downloadWithoutLength       = ((NSNumber)defaults [kDownloadWithoutLength]).BoolValue;
            useRelativeURL              = ((NSNumber)defaults [kUseRelativeURL]).BoolValue;
            useAuthentication           = ((NSNumber)defaults [kUseAuthentication]).BoolValue;
            usePersistentAuthentication = ((NSNumber)defaults [kUsePersistentAuthentication]).BoolValue;
            userName           = (NSString)defaults [kUserName];
            password           = (NSString)defaults [kPassword];
            localServerAddress = (NSString)defaults [kLocalServerAddress];

            webDav.IsEnabled = ((NSNumber)defaults [kEnableWebDavTests]).BoolValue;
            webDav.Server    = (NSString)defaults [kWebDavServer];
            webDav.UserName  = (NSString)defaults [kWebDavUserName];
            webDav.Password  = (NSString)defaults [kWebDavPassword];
        }
Ejemplo n.º 7
0
 public WebDavStorageProviderSession(ICloudStorageAccessToken token, WebDavConfiguration config, IStorageProviderService service)
 {
     SessionToken         = token;
     ServiceConfiguration = config;
     Service = service;
 }
Ejemplo n.º 8
0
        public static WebDavRequestResult CreateObjectsFromNetworkStream(Stream data, String targetUrl, IStorageProviderService service, IStorageProviderSession session, NameBaseFilterCallback callback)
        {
            WebDavConfiguration config = session.ServiceConfiguration as WebDavConfiguration;

            WebDavRequestResult results = new WebDavRequestResult();

            try
            {
                String   resourceName             = String.Empty;
                long     resourceLength           = 0;
                DateTime resourceModificationDate = DateTime.Now;
                DateTime resourceCreationDate     = DateTime.Now;
                String   resourceContentType      = String.Empty;
                Boolean  bIsHidden    = false;
                Boolean  bIsDirectory = false;
                Boolean  bIsSelf      = false;

                // build queryless uri
                String queryLessUri = HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator).ToString().TrimEnd('/');

                // work with decoded target url
                String decodedTargetUrl = HttpUtility.UrlDecode(targetUrl);

                XmlTextReader reader = new XmlTextReader(data);
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                    {
                        // we are on an element and we have to handle this elements
                        String currentElement = reader.Name;

                        // we found a resource name
                        if (currentElement.Contains(":href"))
                        {
                            // check if it is an element with valud namespace prefix
                            if (!CheckIfNameSpaceDAVSpace(currentElement, reader))
                            {
                                continue;
                            }

                            // go one more step
                            reader.Read();

                            // get the name
                            String nameBase = reader.Value;

                            // call the filter if needed
                            if (callback != null)
                            {
                                nameBase = callback(targetUrl, service, session, nameBase);
                            }

                            /*
                             * Just for bug fixing
                             *
                             * Console.WriteLine("   SVC Locator: " + config.ServiceLocator.ToString());
                             * Console.WriteLine("SVC Locator QL: " + HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator));
                             * Console.WriteLine("    Target Url: " + targetUrl);
                             * Console.WriteLine("      NameBase: " + nameBase);
                             */

                            // generate namebase for self check
                            String nameBaseForSelfCheck;

                            // remove the base url and build for selfcheck
                            if (nameBase.StartsWith(config.ServiceLocator.ToString()))
                            {
                                nameBaseForSelfCheck = HttpUtility.UrlDecode(nameBase);
                                nameBase             = nameBase.Remove(0, config.ServiceLocator.ToString().Length);
                            }
                            else
                            {
                                nameBaseForSelfCheck = queryLessUri + HttpUtilityEx.PathDecodeUTF8(nameBase);
                            }

                            // trim all trailing slashes
                            nameBase = nameBase.TrimEnd('/');

                            // work with the trailing lsahed
                            nameBaseForSelfCheck = nameBaseForSelfCheck.TrimEnd('/');
                            if (targetUrl.EndsWith("/"))
                            {
                                nameBaseForSelfCheck += "/";
                            }



                            // check if we are self
                            if (nameBaseForSelfCheck.Equals(decodedTargetUrl))
                            {
                                bIsSelf = true;
                            }
                            else
                            {
                                bIsSelf = false;
                            }

                            // get the last file or directory name
                            PathHelper ph = new PathHelper(nameBase);
                            resourceName = ph.GetFileName();

                            // unquote name
                            resourceName = HttpUtility.UrlDecode(resourceName);
                        }
                        else if (currentElement.Contains(":ishidden"))
                        {
                            // check if it is an element with valud namespace prefix
                            if (!CheckIfNameSpaceDAVSpace(currentElement, reader))
                            {
                                continue;
                            }

                            // go one more step
                            reader.Read();

                            // try to parse
                            int iIsHidden = 0;
                            if (!int.TryParse(reader.Value, out iIsHidden))
                            {
                                iIsHidden = 0;
                            }

                            // convert
                            bIsHidden = Convert.ToBoolean(iIsHidden);
                        }
                        else if (currentElement.Contains(":getcontentlength"))
                        {
                            // check if it is an element with valud namespace prefix
                            if (!CheckIfNameSpaceDAVSpace(currentElement, reader))
                            {
                                continue;
                            }

                            // go one more step
                            reader.Read();

                            // read value
                            if (!long.TryParse(reader.Value, out resourceLength))
                            {
                                resourceLength = -1;
                            }
                        }
                        else if (currentElement.Contains(":creationdate"))
                        {
                            // check if it is an element with valud namespace prefix
                            if (!CheckIfNameSpaceDAVSpace(currentElement, reader))
                            {
                                continue;
                            }

                            // go one more step
                            reader.Read();

                            // parse
                            if (!DateTime.TryParse(reader.Value, out resourceCreationDate))
                            {
                                resourceCreationDate = DateTime.Now;
                            }
                        }
                        else if (currentElement.Contains(":getlastmodified"))
                        {
                            // check if it is an element with valud namespace prefix
                            if (!CheckIfNameSpaceDAVSpace(currentElement, reader))
                            {
                                continue;
                            }

                            // go one more step
                            reader.Read();

                            // parse
                            if (!DateTime.TryParse(reader.Value, out resourceModificationDate))
                            {
                                resourceModificationDate = DateTime.Now;
                            }
                        }
                        else if (currentElement.Contains(":getcontenttype"))
                        {
                            // check if it is an element with valud namespace prefix
                            if (!CheckIfNameSpaceDAVSpace(currentElement, reader))
                            {
                                continue;
                            }

                            // go one more step
                            reader.Read();

                            // parse
                            resourceContentType = reader.Value;
                        }
                        else if (currentElement.Contains(":collection"))
                        {
                            // check if it is an element with valud namespace prefix
                            if (!CheckIfNameSpaceDAVSpace(currentElement, reader))
                            {
                                continue;
                            }

                            // set as directory
                            bIsDirectory = true;
                        }

                        // go ahead
                        break;
                    }

                    case XmlNodeType.EndElement:
                    {
                        // handle the end of an response
                        if (!reader.Name.ToLower().Contains(":response"))
                        {
                            break;
                        }

                        // check if it is an element with valud namespace prefix
                        if (!CheckIfNameSpaceDAVSpace(reader.Name, reader))
                        {
                            continue;
                        }

                        // handle the end of an response, this means
                        // create entry
                        BaseFileEntry entry = null;

                        if (bIsDirectory)
                        {
                            entry = new BaseDirectoryEntry(resourceName, resourceLength, resourceModificationDate, service, session);
                        }
                        else
                        {
                            entry = new BaseFileEntry(resourceName, resourceLength, resourceModificationDate, service, session);
                        }

                        entry.SetPropertyValue("CreationDate", resourceCreationDate);
                        entry.SetPropertyValue("ContentType", resourceContentType);

                        if (!bIsHidden)
                        {
                            if (bIsSelf)
                            {
                                results.Self = entry;
                            }
                            else
                            {
                                results.Childs.Add(entry);
                            }
                        }

                        // reset all state properties
                        resourceName             = String.Empty;
                        resourceLength           = 0;
                        resourceModificationDate = DateTime.Now;
                        resourceCreationDate     = DateTime.Now;
                        resourceContentType      = String.Empty;
                        bIsHidden    = false;
                        bIsDirectory = false;

                        // go ahead
                        break;
                    }

                    default:
                    {
                        break;
                    }
                    }
                }
                ;

                if (results.Self == null)
                {
                    throw new Exception("Unknown error in webrequest parser");
                }
            }
            catch (Exception)
            {
            }

            // go ahead
            return(results);
        }
 public WebDavStorageProviderSession(ICloudStorageAccessToken token, WebDavConfiguration config, IStorageProviderService service)
 {
     SessionToken = token;
     ServiceConfiguration = config;
     Service = service;
 }
Ejemplo n.º 10
0
        public StorageFolderResult Execute(WebDavConfigurationModel model, string path, int accountId)
        {
            model = model.With(m => !string.IsNullOrEmpty(m.ServerUrl))
                    .With(m => !string.IsNullOrEmpty(m.AccountLogin))
                    .With(m => !string.IsNullOrEmpty(m.AccountPassword));

            if (model == null)
            {
                throw new PluginException(PluginErrorCodes.InvalidCredentialsOrConfiguration);
            }

            StorageFolderResult result = new StorageFolderResult();

            Uri uri = new Uri(model.ServerUrl);
            ICloudStorageConfiguration config = new WebDavConfiguration(uri);
            GenericNetworkCredentials  cred   = new GenericNetworkCredentials();

            cred.UserName = model.AccountLogin;
            cred.Password = model.AccountPassword;

            if (string.IsNullOrEmpty(path))
            {
                path = "/";
            }
            else
            {
                path = path.RemoveCharDuplicates('/');
            }
            if (!path.Equals("/", StringComparison.OrdinalIgnoreCase))
            {
                path = path.TrimEnd('/');
            }

            CloudStorage storage = null;

            try
            {
                storage = new CloudStorage();
                ICloudStorageAccessToken storageToken = storage.Open(config, cred);
                ICloudDirectoryEntry     directory    = storage.GetFolder(path, true);

                result.CurrentFolderName = directory.Name;
                result.CurrentFolderUrl  = path;
                path = path.TrimEnd('/');
                foreach (var entry in directory)
                {
                    var    dirEntry  = entry as ICloudDirectoryEntry;
                    string entryPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", path, "/", entry.Name);
                    if (dirEntry != null)
                    {
                        result.AddItem(new StorageFolder
                        {
                            Name             = dirEntry.Name,
                            Path             = entryPath,
                            StorageAccountId = accountId
                        });
                    }
                    else
                    {
                        result.AddItem(new StorageFile
                        {
                            Name             = entry.Name,
                            Path             = entryPath,
                            StorageAccountId = accountId
                        });
                    }
                }

                StoragePathItem rootPath = new StoragePathItem
                {
                    Name = "/",
                    Url  = "/"
                };
                string relativePath = path.Trim('/').RemoveCharDuplicates('/');
                if (relativePath.Length > 0)
                {
                    string[]      pathItems       = relativePath.Split('/');
                    StringBuilder pathUrlsBuilder = new StringBuilder("/");
                    foreach (var pathItem in pathItems)
                    {
                        pathUrlsBuilder.Append(pathItem);
                        rootPath.AppendItem(new StoragePathItem
                        {
                            Name = pathItem,
                            Url  = pathUrlsBuilder.ToString()
                        });
                        pathUrlsBuilder.Append("/");
                    }
                }

                result.CurrentPath = rootPath;
            }
            finally
            {
                if (storage != null)
                {
                    storage.Close();
                }
            }

            return(result);
        }