コード例 #1
0
ファイル: Exists.cs プロジェクト: DejanMilicic/MoarUtils
 public static bool Execute(
     string AWSAccessKey,
     string AWSSecretKey,
     string fileKey,
     string bucketName,
     RegionEndpoint re,
     out string url
     )
 {
     url = "";
     try {
         using (var s3c = new AmazonS3Client(
                    awsAccessKeyId: AWSAccessKey,
                    awsSecretAccessKey: AWSSecretKey,
                    region: re
                    )) {
             var s3FileInfo = new Amazon.S3.IO.S3FileInfo(s3c, bucketName, fileKey);
             url = "https://s3.amazonaws.com/" + bucketName + "/" + fileKey;
             return(s3FileInfo.Exists);
         }
     } catch (Exception ex) {
         LogIt.E(ex);
         return(false);
     }
 }
コード例 #2
0
ファイル: FileLength.cs プロジェクト: DejanMilicic/MoarUtils
 public static long Execute(
     string AWSAccessKey,
     string AWSSecretKey,
     string fileKey,
     RegionEndpoint re,
     string bucketName
     )
 {
     try {
         using (var s3c = new AmazonS3Client(AWSAccessKey, AWSSecretKey, re)) {
             var s3FileInfo = new Amazon.S3.IO.S3FileInfo(s3c, bucketName, fileKey);
             return(s3FileInfo.Length);
         }
     } catch (Exception ex) {
         LogIt.E(ex);
         return(0);
     }
 }
コード例 #3
0
        public static Boolean validAmazonUri(String[] urls)
        {
            using (IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.EUCentral1))
            {
                for (int i = 0; i < urls.Length; i++)
                {
                    //check if uri is a public uri from our amazon s3
                    String[] param = urls[i].Split('/');
                    if (param.Length != 5) return false;

                    String filename = param[4];
                    if (filename.IndexOf('?') > 0) filename = filename.Substring(0, filename.IndexOf('?'));
                    var s3FileInfo = new Amazon.S3.IO.S3FileInfo(client, param[3], filename);
                    try
                    {
                        if (!s3FileInfo.Exists) return false;
                    }
                    catch (AmazonS3Exception)
                    {
                        return false;
                    }
                }
                return true;
            }
        }
コード例 #4
0
        public static String ReplaceObject(HttpPostedFileBase file, String name)
        {
            String filename = name + file.FileName;
            String url = server + bucket + "/" + filename; ;

            using (IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.EUCentral1))
            {
                //check if file exists and if so deletes it
                var s3FileInfo = new Amazon.S3.IO.S3FileInfo(client, bucket, filename);
                if (s3FileInfo.Exists)
                {
                    DeleteObjectRequest drequest = new DeleteObjectRequest();
                    drequest.BucketName = bucket;
                    drequest.Key = filename;
                    client.DeleteObject(drequest);
                }

                //update the new file
                int size = file.ContentLength;
                PutObjectRequest request = new PutObjectRequest();
                request.CannedACL = S3CannedACL.PublicRead;
                request.BucketName = bucket;
                request.ContentType = file.ContentType;
                request.Key = filename;
                request.InputStream = file.InputStream;
                client.PutObject(request);

                //update traffic
                PictogramsDb.UpdateTraffic(name, size);

            }

            return url;
        }
コード例 #5
0
        public static String putObject(HttpPostedFileBase file, String name)
        {
            //Create a unique file name with help of the user name that is unique too
            String filename = name + file.FileName;
            String url = server + bucket + "/" + filename;

            using (IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.EUCentral1))
            {

                //Check if file exists
                var s3FileInfo = new Amazon.S3.IO.S3FileInfo(client, bucket, filename);
                if (s3FileInfo.Exists)
                {
                    GetObjectMetadataRequest request = new GetObjectMetadataRequest();
                    request.BucketName = bucket;
                    request.Key = filename;

                    GetObjectMetadataResponse response = client.GetObjectMetadata(request);
                    //Get tag from Amazon file
                    String S3Tag = response.ETag.Replace("/", "").Replace("\"", "");

                    using (var md5 = MD5.Create())
                    {
                        using (var stream = file.InputStream)
                        {
                            //Get tag from local file
                            stream.Position = 0;
                            String fileTag = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
                            //Compare both tags, if they match there´s no need to upload the image
                            if (fileTag == S3Tag) return url;
                            return null;
                        }
                    }

                }
                else
                {
                    int size = file.ContentLength;

                    //Upload image to amazon s3
                    PutObjectRequest request = new PutObjectRequest();
                    request.CannedACL = S3CannedACL.PublicRead;
                    request.BucketName = bucket;
                    request.ContentType = file.ContentType;
                    request.Key = filename;
                    request.InputStream = file.InputStream;
                    client.PutObject(request);

                    //Update traffic after upload
                    PictogramsDb.UpdateTraffic(name, size);

                }
            }

            return url;
        }
コード例 #6
0
        public ActionResult saveDocument(Document document)
        {
            //  if(model.ProjectId=="" || model.MainSection.)
            //    return Redirect("../Document/AddDocument");
            string        result    = "";
            StringBuilder client    = new StringBuilder();                 //client stringBulder is used for holding <ClientSide Type=""> data like wise  server,database,service,
            StringBuilder server    = new StringBuilder();
            StringBuilder database  = new StringBuilder();
            StringBuilder service   = new StringBuilder();
            StringBuilder param     = new StringBuilder();        //param is used for holding client,server, database, service data's
            string        commonRow = Request.Form["common_row"]; //used for store added client,server.database, service data's ex: it store client_row0,server_row0,database_row0,service_row0

            string[] commonArray = commonRow.Split(',');
            string   clients, servers, databases, services;

            document.created_by = Request.Form["CreatedBy"];
            string created_by  = document.created_by;
            int    document_id = 0;

            document.docFunList = new List <DocumentFunction>();
            DocumentDao docDao = new DocumentDao();

            try {
                if (document.Image != null)
                {
                    List <project>  projctList           = doctDto.GetProject();
                    string          projectname          = projctList.Where(w => w.Id == document.ProjectId).Select(s => s.ProjectName).First();
                    string          AWSAccessKey         = ConfigurationManager.AppSettings["AWSAccessKey"].ToString();
                    string          AWSSecretKey         = ConfigurationManager.AppSettings["AWSSecretKey"].ToString();
                    var             s3client             = new AmazonS3Client(AWSAccessKey, AWSSecretKey, Amazon.RegionEndpoint.USEast1);
                    TransferUtility utility              = new TransferUtility(s3client);
                    TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
                    Stream inputstream = document.Image.InputStream != null ? document.Image.InputStream : null;
                    string contenttype = "image/jpeg";
                    string FileName    = document.MainSection;
                    string Extension   = document.Image.FileName.Split('.')[1];
                    string bucket      = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["imagebucket"]) ? ConfigurationManager.AppSettings["imagebucket"] : string.Empty;

                    FileName            = FileName + "." + Extension;
                    request.BucketName  = bucket + projectname;
                    request.CannedACL   = S3CannedACL.PublicRead;
                    request.Key         = FileName;
                    request.InputStream = inputstream;
                    request.ContentType = contenttype;
                    utility.Upload(request);
                    Amazon.S3.IO.S3FileInfo fileinfo = new Amazon.S3.IO.S3FileInfo(s3client, bucket + projectname, Path.GetFileName(FileName));
                    if (fileinfo.Exists)
                    {
                        document.ImageName = FileName;
                        var res = "success";
                    }
                }

                string root = "<Root>"
                              + "<Document  ProjectId=\"" + document.ProjectId + "\" MainSection=\"" + document.MainSection + "\"  Controller=\"" + document.Controller + "\" Action=\"" + document.Action + "\" Url=\"" + document.Url + "\" SubSection=\"" + document.SubSection + "\" FunctionalityDescription=\"" + document.FunctionalityDescription + "\" Image=\"" + document.ImageName + "\"    >";
                clients   = "<ClientSide Type=\"" + "Client" + "\">";
                servers   = "<ServerSide Type =\"" + "server" + "\">";
                databases = "<Database  Type=\"" + "Database" + "\">";
                services  = "<Service  Type=\"" + "service" + "\"> ";
                param.Append(root);
                client.Append(clients);
                server.Append(servers);
                database.Append(databases);
                service.Append(services);
                foreach (string str in commonArray)
                {
                    if (string.IsNullOrEmpty(str))
                    {
                        continue;
                    }
                    DocumentFunction docFun = new DocumentFunction();
                    docFun.FunctionName = Request.Form[str + "Name"];
                    if (!string.IsNullOrEmpty(docFun.FunctionName))
                    {
                        docFun.Input  = Request.Form[str + "input"];
                        docFun.Output = Request.Form[str + "output"];
                        docFun.FunctionDescription = Request.Form[str + "dDescription"];

                        docFun.ServerSideScripting = Request.Form[str + "server"];
                        docFun.Database            = Request.Form[str + "database"];
                        docFun.Service             = Request.Form[str + "service"];
                        docFun.LinkingMethod       = Request.Form[str + "linkmethod"];

                        docFun.Procedure       = Request.Form[str + "procedure"];
                        docFun.TableorViewUsed = Request.Form[str + "tables"];

                        docFun.CreatedBy = Request.Form["CreatedBy"];
                        docFun.Type      = str.Substring(0, str.IndexOf('_')); //get the function type whether it is client or server or database or service
                        document.docFunList.Add(docFun);
                        string source = "<Source  FunctionName=\"" + docFun.FunctionName + "\" FunctionDescription =\"" + docFun.FunctionDescription + "\" Input=\"" + docFun.Input + "\"" + " Output =\"" + docFun.Output + "\" ServerSideScripting =\"" + docFun.ServerSideScripting + "\" Database =\"" + docFun.Database + "\" Service =\"" + docFun.Service + "\" LinkingMethod =\"" + docFun.LinkingMethod + "\" Procedure =\"" + docFun.Procedure + "\" TableorViewUsed =\"" + docFun.TableorViewUsed + "\"  />";
                        if (docFun.Type.ToString() == "client")
                        {
                            client.Append(source);
                        }
                        else if (docFun.Type.ToString() == "server")
                        {
                            server.Append(source);
                        }
                        else if (docFun.Type.ToString() == "database")
                        {
                            database.Append(source);
                        }
                        else if (docFun.Type.ToString() == "service")
                        {
                            service.Append(source);
                        }
                    }
                }
                client.Append("</ClientSide>");
                server.Append("</ServerSide>");
                database.Append("</Database>");
                service.Append("</Service>");
                param.Append(client);
                param.Append(server);
                param.Append(database);
                param.Append(service);
                param.Append("</Document></Root>");
                result = docDao.InsertNewDocument(param, document.Id, created_by);
            }
            catch (Exception e)
            {
            }
            //if (result == "success")
            //    return "success";
            //else
            //    return "failed";
            if (document != null && document.Id != 0)
            {
                return(RedirectToAction("EditDocument", "Document", new { docid = document.Id, from = "update" }));
            }
            else
            {
                return(RedirectToAction("AddDocument", "Document"));
            }
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: wse/AWS
        bool S3FileExists(string bucketName, string keyName)
        {
            var s3FileInfo = new Amazon.S3.IO.S3FileInfo(client, bucketName, keyName);

            return(s3FileInfo.Exists);
        }
コード例 #8
0
        public Transaccion <bool> CargarArchivo(string bucketName, string keyName, Stream data)
        {
            Transaccion <bool> resultado = ManejoTransaccion <bool> .Instancia.InicializarTransaccion(DLL);

            string regionAws  = Condai.Tools.Configuracion.RegionAws;
            string usuarioAws = Condai.Tools.Configuracion.UsuarioAws;
            string accessKey  = Condai.Tools.Configuracion.AccessKey;
            string secretKey  = Condai.Tools.Configuracion.SecretKey;

            Amazon.Util.ProfileManager.RegisterProfile(usuarioAws, accessKey, secretKey);
            Amazon.RegionEndpoint         region      = Amazon.RegionEndpoint.GetBySystemName(regionAws);
            Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.StoredProfileAWSCredentials(usuarioAws);

            string checkSum = Condai.Tools.Seguridad.Cryptography.Instancia.LeerCheckSum(data);

            using (IAmazonS3 s3Client = new AmazonS3Client(credentials, region))
            {
                string tagCheckSum = "x-amz-meta-checksum";

                var fileInfo = new Amazon.S3.IO.S3FileInfo(s3Client, bucketName, keyName);

                if (fileInfo.Exists)
                {
                    var respGet = s3Client.GetObjectMetadata(bucketName, keyName);

                    if (respGet.Metadata[tagCheckSum] == checkSum)
                    {
                        resultado = ManejoTransaccion <bool> .Instancia.Resultado(Estado.Correcto, resultado, true, "Hay un archivo con la misma ruta en el servidor y tiene el checksum igual.");
                    }
                    else
                    {
                        resultado = ManejoTransaccion <bool> .Instancia.Resultado(Estado.Error, resultado, false, "Hay un archivo con la misma ruta en el servidor, pero tienen checksum diferente.");
                    }
                }
                else
                {
                    var request = new PutObjectRequest()
                    {
                        BucketName  = bucketName,
                        Key         = keyName,
                        CannedACL   = S3CannedACL.Private,
                        InputStream = data
                    };

                    request.Metadata.Add(tagCheckSum, checkSum);

                    s3Client.PutObject(request);

                    var fileInfo2 = new Amazon.S3.IO.S3FileInfo(s3Client, bucketName, keyName);

                    if (fileInfo2.Exists)
                    {
                        resultado = ManejoTransaccion <bool> .Instancia.Resultado(Estado.Correcto, resultado, true, "Cargado");
                    }
                    else
                    {
                        resultado = ManejoTransaccion <bool> .Instancia.Resultado(Estado.Error, resultado, false, "Error cargando el archivo al Aws S3");
                    }
                }
            }

            return(resultado);
        }