public List <Libro> LeerXML(String nombrearchivo)
        {
            //CREAMOS UN CONTENIDO EN LA MEMORIA PARA LEER EL DOCUMENTO
            MemoryStream contenido = new MemoryStream();
            //ACCEDEMOS AL FICHERO POR SU NOMBRE
            CloudFile archivo = this.directorio.GetFileReference(nombrearchivo);
            //DESCARGAMOS SU CONTENIDO EN UN STRING
            String datos = archivo.DownloadText(System.Text.Encoding.UTF8);
            //CREAMOS UN NUEVO DOCUMENTO XML A PARTIR DEL STREAM DE AZURE
            XDocument doc = XDocument.Parse(datos);

            //HACEMOS LA CONSULTA PARA OBTENER LA LISTA
            var consulta = from d in doc.Descendants("libro")
                           select new Libro {
                Nombre        = (String)d.Element("nombre"),
                Autor         = (String)d.Element("autor"),
                NumeroPaginas = (int)d.Element("numeropaginas"),
                Imagen        = (String)d.Element("img"),
                Capitulos     = new List <Capitulo>(
                    from cap in d.Descendants("capitulo")
                    select new Capitulo {
                    NombreCapitulo = cap.Element("nombre").Value,
                    ImagenCapitulo = cap.Element("imagen").Value
                })
            };

            return(consulta.ToList());
        }
Beispiel #2
0
        public async Task JokeIntent(IDialogContext context, LuisResult result)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                Microsoft.Azure.CloudConfigurationManager.GetSetting("cosmostorageaccount_AzureStorageConnectionString"));
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("files");

            if (share.Exists())
            {
                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("AstroFiles");
                if (sampleDir.Exists())
                {
                    CloudFile sourceFile = sampleDir.GetFileReference("Joke.txt");

                    if (sourceFile.Exists())
                    {
                        if (countjoke == 0)
                        {
                            await context.PostAsync("I've got one for you: ");
                        }
                        countjoke++;
                        var    lines      = string.Format(sourceFile.DownloadText());
                        Random number     = new Random();
                        int    num        = number.Next(1, 64);
                        var    linesArray = lines.Split('.');
                        await context.PostAsync($"{linesArray[num]}");
                    }
                }
            }
        }
Beispiel #3
0
        public async Task FactIntent(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                Microsoft.Azure.CloudConfigurationManager.GetSetting("cosmostorageaccount_AzureStorageConnectionString"));
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("files");

            if (share.Exists())
            {
                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("AstroFiles");
                if (sampleDir.Exists())
                {
                    CloudFile sourceFile = sampleDir.GetFileReference("Facts.txt");

                    if (sourceFile.Exists())
                    {
                        if (countfact == 0)
                        {
                            await context.PostAsync("Here's something interesting:");
                        }
                        countfact++;
                        var    lines      = string.Format(sourceFile.DownloadText());
                        var    linesArray = lines.Split('.');
                        Random number     = new Random();
                        int    num        = number.Next(1, 57);
                        await context.PostAsync($"{linesArray[num]}");
                    }
                }
            }
        }
        public string DownloadFileContentAsString(string fileShareName, string fileName = "")
        {
            CloudFileClient fileClient = new CloudFileClient(fileURI, creds);
            // Create a CloudFileClient object for credentialed access to Azure Files.


            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference(fileShareName);

            // Ensure that the share exists.
            if (share.Exists())
            {
                try
                {
                    // Get a reference to the root directory for the share.
                    CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                    CloudFile          cloudFile = rootDir.GetFileReference(fileName);
                    return(cloudFile.DownloadText());
                }
                catch (Exception e)
                {
                    throw new StorageAccountException("Error while attempting to get contents", e);
                }
            }
            else
            {
                DirectoryNotFoundException e = new DirectoryNotFoundException(string.Format("The file share '{0}' does not exist.", fileShareName));
                throw new StorageAccountException("Error while attempting to get content", e);
            }
        }
    protected void Button3_Click(object sender, EventArgs e)
    {
        CloudStorageAccount account       = CloudStorageAccount.Parse(this.connString);
        CloudFileClient     client        = account.CreateCloudFileClient();
        CloudFileShare      share         = client.GetShareReference("birklasor");
        CloudFileDirectory  rootDirectory = share.GetRootDirectoryReference();
        CloudFile           aCloudFile    = rootDirectory.GetFileReference("deneme.txt");

        Response.Write(aCloudFile.DownloadText());
    }
Beispiel #6
0
        public void Copy_a_file_to_a_blob()
        {
            // Parse the connection string for the storage account.
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Create a new file share, if it does not already exist.
            CloudFileShare share = fileClient.GetShareReference("sample-share");

            share.CreateIfNotExists();

            // Create a new file in the root directory.
            CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("sample-file.txt");

            sourceFile.UploadText("A sample file in the root directory.");

            // Get a reference to the blob to which the file will be copied.
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference("sample-container");

            container.CreateIfNotExists();
            CloudBlockBlob destBlob = container.GetBlockBlobReference("sample-blob.txt");

            // Create a SAS for the file that's valid for 24 hours.
            // Note that when you are copying a file to a blob, or a blob to a file, you must use a SAS
            // to authenticate access to the source object, even if you are copying within the same
            // storage account.
            string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy()
            {
                // Only read permissions are required for the source file.
                Permissions            = SharedAccessFilePermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
            });

            // Construct the URI to the source file, including the SAS token.
            Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas);

            // Copy the file to the blob.
            destBlob.StartCopy(fileSasUri);

            // Write the contents of the file to the console window.
            Console.WriteLine("Source file contents: {0}", sourceFile.DownloadText());
            Console.WriteLine("Destination blob contents: {0}", destBlob.DownloadText());
        }
Beispiel #7
0
        private object GetData(CloudFile file, DownloadDataType downloadDataType)
        {
            switch (downloadDataType)
            {
            case DownloadDataType.Text:
                return(file.DownloadText());

            case DownloadDataType.ByteArray:
                var document = new byte[file.Properties.Length];

                file.DownloadToByteArray(document, 0);

                return(document);

            default:
                throw new ArgumentOutOfRangeException("downloadDataType");
            }
        }
Beispiel #8
0
        public void Generate_a_shared_access_signature_for_a_file_or_file_share()
        {
            // Parse the connection string for the storage account.
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference("logs");

            // Ensure that the share exists.
            if (share.Exists())
            {
                string policyName = "sampleSharePolicy" + DateTime.UtcNow.Ticks;

                // Create a new shared access policy and define its constraints.
                SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy()
                {
                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                    Permissions            = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write
                };

                // Get existing permissions for the share.
                FileSharePermissions permissions = share.GetPermissions();

                // Add the shared access policy to the share's policies. Note that each policy must have a unique name.
                permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);
                share.SetPermissions(permissions);

                // Generate a SAS for a file in the share and associate this access policy with it.
                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");
                CloudFile          file      = sampleDir.GetFileReference("Log1.txt");
                string             sasToken  = file.GetSharedAccessSignature(null, policyName);
                Uri fileSasUri = new Uri(file.StorageUri.PrimaryUri.ToString() + sasToken);

                // Create a new CloudFile object from the SAS, and write some text to the file.
                CloudFile fileSas = new CloudFile(fileSasUri);
                fileSas.UploadText("This write operation is authenticated via SAS.");
                Console.WriteLine(fileSas.DownloadText());
            }
        }
Beispiel #9
0
        public void Copy_file_to_another_file()
        {
            // Parse the connection string for the storage account.
            StorageCredentials  Credentials    = new StorageCredentials(this.Account, this.Key);
            CloudStorageAccount storageAccount = new CloudStorageAccount(Credentials, false);

            // Create a CloudFileClient object for credentialed access to File storage.
            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

            // Get a reference to the file share we created previously.
            CloudFileShare share = fileClient.GetShareReference("logs");

            // Ensure that the share exists.
            if (share.Exists())
            {
                // Get a reference to the root directory for the share.
                CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                // Get a reference to the directory we created previously.
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");

                // Ensure that the directory exists.
                if (sampleDir.Exists())
                {
                    // Get a reference to the file we created previously.
                    CloudFile sourceFile = sampleDir.GetFileReference("Log1.txt");

                    // Ensure that the source file exists.
                    if (sourceFile.Exists())
                    {
                        // Get a reference to the destination file.
                        CloudFile destFile = sampleDir.GetFileReference("Log1Copy.txt");

                        // Start the copy operation.
                        destFile.StartCopy(sourceFile);

                        // Write the contents of the destination file to the console window.
                        Console.WriteLine(destFile.DownloadText());
                    }
                }
            }
        }
Beispiel #10
0
        public static string GetFileAsString(string filename)
        {
            string fileContents = "";

            CloudFileShare share = GetFileShare();

            if (share.Exists())
            {
                CloudFileDirectory directory = share.GetRootDirectoryReference();
                if (directory.Exists())
                {
                    CloudFile file = directory.GetFileReference(filename);
                    if (file.Exists())
                    {
                        fileContents = file.DownloadText();
                    }
                }
            }

            return(fileContents);
        }
Beispiel #11
0
        public List <Motorista> ReadXmlFile(String filename)
        {
            CloudFile xmlfile  = this.root.GetFileReference(filename);
            String    datosxml = xmlfile.DownloadText(System.Text.Encoding.UTF8);
            XDocument document = XDocument.Parse(datosxml);
            var       consulta = from datos in document.Descendants("motorista")
                                 select new Motorista
            {
                Nombre  = (string)datos.Element("nombre"),
                Dorsal  = (string)datos.Element("dorsal"),
                Titulos = (string)datos.Element("titulos"),
                Debut   = (string)datos.Element("debut"),
                Equipo  = new List <Equipo>(from eq in datos.Descendants("equipo")
                                            select new Equipo
                {
                    Nombre = eq.Element("nombre").Value,
                    Imagen = eq.Element("imagen").Value
                })
            };

            return(consulta.ToList());
        }
Beispiel #12
0
        public bool ReadFile(string path, out string text, int?cacheTimeSeconds = null)
        {
            CloudFile file = AzureRootDirectory.GetFileReference(path);

            if (file.Exists())
            {
                bool isExpired = !cacheTimeSeconds.HasValue;
                if (cacheTimeSeconds.HasValue)
                {
                    file.FetchAttributes();
                    var expirationTime = file.Properties.LastModified.Value.LocalDateTime.AddSeconds(cacheTimeSeconds.Value);
                    isExpired = expirationTime < DateTime.Now;
                }
                if (!isExpired)
                {
                    text = file.DownloadText();
                    return(true);
                }
            }
            text = null;
            return(false);
        }
Beispiel #13
0
        public List <Pelicula> GetPeliculasFile(String nombrefichero)
        {
            CloudFile ficheroxml = this.directorio.GetFileReference(nombrefichero);
            String    datosxml   = ficheroxml.DownloadText();
            XDocument docxml     = XDocument.Parse(datosxml);

            var consulta = from datos in docxml.Descendants("pelicula")
                           select new Pelicula
            {
                Titulo      = datos.Element("titulo").Value,
                Descripcion = datos.Element("descripcion").Value,
                Poster      = datos.Element("poster").Value,
                Escenas     = new List <Escena>(           //consulta al subnivel
                    from escena in datos.Descendants("escena")
                    select new Escena
                {
                    TituloEscena = escena.Element("tituloescena").Value,
                    Descripcion  = escena.Element("descripcion").Value,
                    Imagen       = escena.Element("imagen").Value
                })                   //fin consulta subnivel
            };

            return(consulta.ToList());
        }
        public static void NewFileCreate()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connection);

            CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare  share      = fileClient.GetShareReference("doc2020");

            // Ensure that the share exists.
            if (share.Exists())
            {
                string policyName = "FileSharePolicy" + DateTime.UtcNow.Ticks;

                SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy()
                {
                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                    Permissions            = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write
                };

                FileSharePermissions permissions = share.GetPermissions();

                permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);
                share.SetPermissions(permissions);

                CloudFileDirectory rootDir   = share.GetRootDirectoryReference();
                CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("storage");

                CloudFile file       = sampleDir.GetFileReference("Log2.txt");
                string    sasToken   = file.GetSharedAccessSignature(null, policyName);
                Uri       fileSasUri = new Uri(file.StorageUri.PrimaryUri.ToString() + sasToken);

                // Create a new CloudFile object from the SAS, and write some text to the file.
                CloudFile fileSas = new CloudFile(fileSasUri);
                fileSas.UploadText("This file created by the Console App at Runtime");
                Console.WriteLine(fileSas.DownloadText());
            }
        }
        public JsonResult GetSingleUserTaxReturn(string userId, int taxYear)
        {
            bool downloadSuccessful = true;
            var  results            = new List <Tuple <string, string, byte[]> >();

            using (var db = new WorktripEntities())
            {
                try
                {
                    Regex filePattern = new Regex(@"http.*\/.*\/(?<directory>.*)\/(?<filename>.*)");

                    var user      = db.Users.FirstOrDefault(u => u.Id == userId);
                    var taxReturn = db.UserTaxReturns.Where(d => d.UserId == userId && d.Year == taxYear);

                    taxReturn = taxReturn.OrderBy(d => d.Id);

                    var fileUrls = new List <UserTaxReturn>();
                    if (taxReturn.Count() != 0)
                    {
                        fileUrls.Add(taxReturn.AsEnumerable().Last());
                        byte[] bytes = new byte[64000];

                        var parsedFilePaths = new List <Tuple <string, string> >();

                        foreach (var url in fileUrls)
                        {
                            Match match = filePattern.Match(url.Path);

                            if (match.Success)
                            {
                                var newTuple = new Tuple <string, string>(
                                    match.Groups["directory"].Value,
                                    match.Groups["filename"].Value
                                    );

                                parsedFilePaths.Add(newTuple);
                            }
                        }

                        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                            CloudConfigurationManager.GetSetting("StorageConnectionString"));

                        CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

                        CloudFileShare share = fileClient.GetShareReference("worktripdocs");

                        CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                        CloudFileDirectory userDir = null;

                        var userDirName = "";

                        foreach (var parsedPath in parsedFilePaths)
                        {
                            if (userDirName != parsedPath.Item1)
                            {
                                userDir = rootDir.GetDirectoryReference(parsedPath.Item1);

                                if (!userDir.Exists())
                                {
                                    continue;
                                }

                                userDirName = parsedPath.Item1;
                            }

                            var filename = parsedPath.Item2;

                            CloudFile file = userDir.GetFileReference(filename);

                            if (!file.Exists())
                            {
                                continue;
                            }

                            file.FetchAttributes();

                            string fileContents = "";

                            if (file.Properties.ContentType.ToLower() == "application/pdf")
                            {
                                MemoryStream fileStream = new MemoryStream();
                                file.DownloadToStream(fileStream);
                                bytes        = fileStream.ToArray();
                                fileContents = ConvertStreamToBase64String(fileStream);
                            }
                            else
                            {
                                fileContents = file.DownloadText();
                            }

                            results.Add(
                                new Tuple <string, string, byte[]>(filename, file.Properties.ContentType, bytes)
                                );
                        }
                    }
                }
                catch (Exception e)
                {
                    //Do some error logging here..
                    downloadSuccessful = false;
                }
            }

            if (downloadSuccessful && results.Count > 0)
            {
                return(Json(new MyJsonResult
                {
                    status = 0,
                    fileName = results.ElementAtOrDefault(0).Item1,
                    fileContentType = results.ElementAtOrDefault(0).Item2,
                    fileContents = results.ElementAtOrDefault(0).Item3
                }));
            }
            else
            {
                return(Json(new { status = -1, message = "Error in downloading files" }));
            }
        }
        // Retrieves the valid tokens from storage
        private static IReadOnlyCollection <string> GetKeys()
        {
            var data = File.DownloadText();

            return(data.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList());
        }
Beispiel #17
0
        public JsonResult GetUserDocuments(string userId, int taxYear, int?skip, int?amount)
        {
            bool downloadSuccessful = true;
            var  results            = new List <Tuple <string, string, string> >();

            using (var db = new WorktripEntities())
            {
                try
                {
                    Regex filePattern = new Regex(@"http.*\/.*\/(?<directory>.*)\/(?<filename>.*)");

                    var user = db.Users.FirstOrDefault(u => u.Id == userId);

                    var miscDocs  = db.UserMiscDocs.Where(d => d.UserId == userId && d.Year == taxYear);
                    var taxReturn = db.UserTaxReturns.Where(d => d.UserId == userId && d.Year == taxYear);

                    miscDocs  = miscDocs.OrderBy(d => d.Id);
                    taxReturn = taxReturn.OrderBy(d => d.Id);

                    if (skip.HasValue)
                    {
                        miscDocs  = miscDocs.Skip(skip.Value);
                        taxReturn = taxReturn.Skip(skip.Value);
                    }

                    if (amount.HasValue)
                    {
                        miscDocs  = miscDocs.Take(amount.Value);
                        taxReturn = taxReturn.Take(amount.Value);
                    }

                    var fileUrls = miscDocs.Select(d => d.Path).ToList();
                    fileUrls.AddRange(taxReturn.Select(d => d.Path).ToList());

                    var parsedFilePaths = new List <Tuple <string, string> >();

                    foreach (var url in fileUrls)
                    {
                        Match match = filePattern.Match(url);

                        if (match.Success)
                        {
                            var newTuple = new Tuple <string, string>(
                                match.Groups["directory"].Value,
                                match.Groups["filename"].Value
                                );

                            parsedFilePaths.Add(newTuple);
                        }
                    }

                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                        CloudConfigurationManager.GetSetting("StorageConnectionString"));

                    CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

                    CloudFileShare share = fileClient.GetShareReference("worktripdocs");

                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                    CloudFileDirectory userDir = null;

                    var userDirName = "";

                    foreach (var parsedPath in parsedFilePaths)
                    {
                        if (userDirName != parsedPath.Item1)
                        {
                            userDir = rootDir.GetDirectoryReference(parsedPath.Item1);

                            if (!userDir.Exists())
                            {
                                continue;
                            }

                            userDirName = parsedPath.Item1;
                        }

                        var filename = parsedPath.Item2;

                        CloudFile file = userDir.GetFileReference(filename);

                        if (!file.Exists())
                        {
                            continue;
                        }

                        file.FetchAttributes();

                        string fileContents = "";

                        if (file.Properties.ContentType != null &&
                            file.Properties.ContentType.StartsWith("image/"))
                        {
                            MemoryStream fileStream = new MemoryStream();

                            file.DownloadToStream(fileStream);

                            fileContents = ConvertImageStreamToBase64String(fileStream);
                        }
                        else if (file.Properties.ContentType.ToLower() == "application/pdf")
                        {
                            MemoryStream fileStream = new MemoryStream();
                            file.DownloadToStream(fileStream);

                            fileContents = ConvertStreamToBase64String(fileStream);
                        }
                        else
                        {
                            fileContents = file.DownloadText();
                        }

                        results.Add(
                            new Tuple <string, string, string>(filename, file.Properties.ContentType, fileContents)
                            );
                    }
                }
                catch (Exception e)
                {
                    //Do some error logging here..
                    downloadSuccessful = false;
                }
            }

            if (downloadSuccessful)
            {
                return(Json(new {
                    status = 0,
                    files = results
                }));
            }
            else
            {
                return(Json(new { status = -1, message = "Error in downloading files" }));
            }
        }