Example #1
0
        // POST api/<controller>
        public async Task <IHttpActionResult> Post([FromBody] SaveAttachmentRequest request)
        {
            if (Request.Headers.Contains("Authorization"))
            {
                // Request contains bearer token, validate it
                var scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope");
                if (scopeClaim != null)
                {
                    // Check the allowed scopes
                    string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' ');
                    if (!addinScopes.Contains("access_as_user"))
                    {
                        return(BadRequest("The bearer token is missing the required scope."));
                    }
                }
                else
                {
                    return(BadRequest("The bearer token is invalid."));
                }

                // Passed validation, process the request
                return(await SaveAttachmentsWithSsoToken(request));
            }
            else
            {
                // No bearer token, so this is a request without SSO
                // Access tokens are included in the request
                return(await SaveAttachmentsWithDistinctTokens(request));
            }
        }
Example #2
0
        /// <summary>
        /// Saves the attachment.
        /// </summary>
        /// <param name="filesViewModel">The files view model.</param>
        /// <param name="page">The page.</param>
        /// <param name="StorageSource">The storage source.</param>
        /// <param name="ContactID">The contact identifier.</param>
        /// <param name="OpportunityID">The opportunity identifier.</param>
        /// <returns></returns>
        public JsonResult SaveAttachment(FilesViewModel[] filesViewModel, string page, char StorageSource, int?ContactID, int?OpportunityID)
        {
            SaveAttachmentRequest request = new SaveAttachmentRequest()
            {
                ContactId      = ContactID,
                OpportunityID  = OpportunityID,
                CreatedBy      = this.Identity.ToUserID(),
                filesViewModel = filesViewModel,
                StorageSource  = StorageSource
            };

            return(Json(new { success = attachmentService.SaveAttachment(request), response = "", responseUrl = "" }, JsonRequestBehavior.AllowGet));
        }
        public virtual SubmitResult SaveAttachment(SaveAttachmentRequest req)
        {
            req.AttachmentTypeId = req.AttachmentTypeId == 0 ? DefaultAttachmentType : req.AttachmentTypeId;
            var cat = unit.AttachmentCategoryRepository.FindSingle(req.AttachmentTypeId);

            var path = Path.Combine(_paths.TempFolder, req.TmpPath);
            var dto  = new FileBytes(path);

            if (dto.Bytes == null)
            {
                return(new SubmitResult(1, "MSG_file_is_not_in_tmp"));
            }

            ValidateFiles(cat, new[] { dto });

            var att = new Attachment()
            {
                FileName             = req.Name,
                AttachmentCategoryId = req.AttachmentTypeId
            };

            string url = null;

            if (req.SaveInDb)
            {
                att.BinaryAttachment = new BinaryAttachment(dto.Bytes);
            }
            else
            {
                var root = _paths.RootFolderPath;
                var name = Guid.NewGuid();
                url          = Utils.CombineUrl(cat.FolderPath ?? "default", name.ToString() + dto.Extension);
                att.FullPath = Path.Combine(root, url).Replace("/", "\\");

                Utils.CreateFolderForFile(att.FullPath);
                File.WriteAllBytes(att.FullPath, dto.Bytes);
            }

            unit.AttachmentRepository.Add(att);
            var s = unit.SaveChanges();

            s.Data["FileData"] = new SavedFileDto
            {
                Id   = att.Id.ToString(),
                Path = url
            };
            return(s);
        }
Example #4
0
        // POST api/<controller>
        public async Task <IHttpActionResult> Post([FromBody] SaveAttachmentRequest request)
        {
            if (Request.Headers.Contains("Authorization"))
            {
                // Request contains bearer token, validate it
                var scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope");
                if (scopeClaim != null)
                {
                    // Check the allowed scopes
                    string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' ');
                    if (!addinScopes.Contains("access_as_user"))
                    {
                        return(BadRequest("The bearer token is missing the required scope."));
                    }
                }
                else
                {
                    return(BadRequest("The bearer token is invalid."));
                }

                var issuerClaim   = ClaimsPrincipal.Current.FindFirst("iss");
                var tenantIdClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid");
                if (issuerClaim != null && tenantIdClaim != null)
                {
                    // validate the issuer
                    string expectedIssuer = string.Format("https://login.microsoftonline.com/{0}/v2.0", tenantIdClaim.Value);
                    if (string.Compare(issuerClaim.Value, expectedIssuer, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        return(BadRequest("The token issuer is invalid."));
                    }
                }
                else
                {
                    return(BadRequest("The bearer token is invalid."));
                }

                // Passed validation, process the request
                return(await SaveAttachmentsWithSsoToken(request));
            }
            else
            {
                // No bearer token, so this is a request without SSO
                // Access tokens are included in the request
                return(await SaveAttachmentsWithDistinctTokens(request));
            }
        }
Example #5
0
        public bool SaveAttachment(SaveAttachmentRequest request)
        {
            foreach (var file in request.filesViewModel)
            {
                string storageFileName = System.Guid.NewGuid().ToString();

                int    FileTypeID;
                string Extension = Path.GetExtension(file.Name);
                if (!string.IsNullOrEmpty(Extension))
                {
                    if (Extension.ToLower() == ".jpg" || Extension.ToLower() == ".jpeg" || Extension.ToLower() == ".png" || Extension.ToLower() == ".bmp")
                    {
                        FileTypeID = (int)FileType.image;
                    }
                    else if (Extension.ToLower() == ".doc" || Extension.ToLower() == ".docx")
                    {
                        FileTypeID = (int)FileType.word;
                    }
                    else if (Extension.ToLower() == ".xls" || Extension.ToLower() == ".xlsx")
                    {
                        FileTypeID = (int)FileType.excel;
                    }
                    else if (Extension.ToLower() == ".txt")
                    {
                        FileTypeID = (int)FileType.txt;
                    }
                    else if (Extension.ToLower() == ".pdf")
                    {
                        FileTypeID = (int)FileType.pdf;
                    }
                    else if (Extension.ToLower() == ".csv")
                    {
                        FileTypeID = (int)FileType.csv;
                    }
                    else if (Extension.ToLower() == ".rtf")
                    {
                        FileTypeID = (int)FileType.rtf;
                    }
                    else
                    {
                        FileTypeID = (int)FileType.others;
                    }
                }
                else
                {
                    FileTypeID = (int)FileType.others;
                }

                AttachmentViewModel viewModel = new AttachmentViewModel()
                {
                    ContactID        = request.ContactId,
                    DocumentTypeID   = (int)DocumentType.General,
                    FileTypeID       = FileTypeID,
                    CreatedBy        = request.CreatedBy,
                    CreatedDate      = DateTime.Now.ToUniversalTime(),
                    FilePath         = file.Link,
                    OriginalFileName = file.Name,
                    StorageFileName  = storageFileName,
                    OpportunityID    = request.OpportunityID,
                    StorageSource    = request.StorageSource
                };

                Attachment attachment = Mapper.Map <AttachmentViewModel, Attachment>(viewModel);
                attachmentRepository.Insert(attachment);
                unitOfWork.Commit();
            }
            return(true);
        }
 public virtual SubmitResult SaveAttachment([FromBody] SaveAttachmentRequest req) => service.SaveAttachment(req);
Example #7
0
        public async Task <string> SaveAttachmentOneDrive([FromBody] SaveAttachmentRequest request)
        {
            if (request == null || !request.IsValid() || request.attachmentIds.Length == 0)
            {
                return(null);
            }

            string attachmentsUrl = null;

            using (var client = new HttpClient())
            {
                // Get content bytes
                string baseAttachmentUri = request.outlookRestUrl;
                if (!baseAttachmentUri.EndsWith("/"))
                {
                    baseAttachmentUri += "/";
                }
                baseAttachmentUri += "v2.0/me/messages/" + request.messageId + "/attachments/";

                var i = 0;
                foreach (string attachmentId in request.attachmentIds)
                {
                    var getAttachmentReq = new HttpRequestMessage(HttpMethod.Get, baseAttachmentUri + attachmentId);

                    // Headers
                    getAttachmentReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.outlookToken);
                    getAttachmentReq.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var result = await client.SendAsync(getAttachmentReq);

                    string json = await result.Content.ReadAsStringAsync();

                    OutlookAttachment attachment = JsonConvert.DeserializeObject <OutlookAttachment>(json);

                    // For files, build a stream directly from ContentBytes
                    if (attachment.Size < (4 * 1024 * 1024))
                    {
                        MemoryStream fileStream = new MemoryStream(Convert.FromBase64String(attachment.ContentBytes));


                        // Get access token from SQL database
                        var token = Data.GetUserSessionToken(Settings.GetUserAuthStateId(ControllerContext.HttpContext), Settings.AzureADAuthority);

                        // TODO: Check if the file already exists

                        attachmentsUrl = await GraphApiHelper.saveAttachmentOneDrive(token.AccessToken, Format.MakeFileNameValid(request.filenames[i]), fileStream, Format.MakeFileNameValid(request.subject));

                        // Format
                        string delete = "/" + request.filenames[i];
                        attachmentsUrl = attachmentsUrl.Replace(delete, "");

                        i++;
                    }
                    else
                    {
                        // Functionality to support > 4 MB files
                        // See https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0
                        var token = Data.GetUserSessionToken(Settings.GetUserAuthStateId(ControllerContext.HttpContext), Settings.AzureADAuthority);

                        DriveItem folder = await GraphApiHelper.searchFileOneDrive(token.AccessToken, "Outlook Attachments");


                        var url       = "https://graph.microsoft.com/v1.0" + $"/me/drive/items/{folder.Id}:/{attachment.Name}:/createUploadSession";
                        var uploadReq = new HttpRequestMessage(HttpMethod.Post, url);


                        // Headers
                        uploadReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

                        // Send request
                        var sessionResponse = client.SendAsync(uploadReq).Result.Content.ReadAsStringAsync().Result;


                        var uploadSession = JsonConvert.DeserializeObject <UploadSessionResponse>(sessionResponse);

                        Upload upload = new Upload();

                        HttpResponseMessage response = upload.UploadFileBySession(uploadSession.uploadUrl, Convert.FromBase64String(attachment.ContentBytes));


                        return(folder.WebUrl);
                    }
                }

                return(attachmentsUrl);
            }
        }
Example #8
0
        private async Task <IHttpActionResult> SaveAttachmentsWithSsoToken(SaveAttachmentRequest request)
        {
            // First retrieve the raw access token
            var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext;

            if (bootstrapContext != null)
            {
                // Use MSAL to invoke the on-behalf-of flow to exchange token for a Graph token
                UserAssertion    userAssertion    = new UserAssertion(bootstrapContext.Token);
                ClientCredential clientCred       = new ClientCredential(ConfigurationManager.AppSettings["ida:AppPassword"]);
                ConfidentialClientApplication cca = new ConfidentialClientApplication(
                    ConfigurationManager.AppSettings["ida:AppId"],
                    ConfigurationManager.AppSettings["ida:RedirectUri"],
                    clientCred, null, null);

                string[] graphScopes = { "Files.ReadWrite", "Mail.Read" };

                AuthenticationResult authResult = await cca.AcquireTokenOnBehalfOfAsync(graphScopes, userAssertion);

                // Initialize a Graph client
                GraphServiceClient graphClient = new GraphServiceClient(
                    new DelegateAuthenticationProvider(
                        (requestMessage) => {
                    // Add the OneDrive access token to each outgoing request
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                    return(Task.FromResult(0));
                }));

                foreach (string attachmentId in request.attachmentIds)
                {
                    var attachment = await graphClient.Me.Messages[request.messageId].Attachments[attachmentId].Request().GetAsync();

                    // Is this a file or an Outlook item?
                    if (string.Compare(attachment.ODataType, "#microsoft.graph.itemAttachment") == 0)
                    {
                        // Re-request the attachment with the item expanded
                        var itemAttachment = await graphClient.Me.Messages[request.messageId].Attachments[attachmentId].Request()
                                             .Expand("microsoft.graph.itemAttachment/item").GetAsync() as ItemAttachment;

                        // Serialize the item to JSON and save to OneDrive
                        string       jsonItem   = JsonConvert.SerializeObject(itemAttachment.Item);
                        MemoryStream fileStream = new MemoryStream();
                        StreamWriter sw         = new StreamWriter(fileStream);
                        sw.Write(jsonItem);
                        sw.Flush();
                        fileStream.Position = 0;
                        bool success = await SaveFileToOneDrive(graphClient, itemAttachment.Name + ".json", fileStream);

                        if (!success)
                        {
                            return(BadRequest(string.Format("Could not save {0} to OneDrive", itemAttachment.Name)));
                        }
                    }
                    else
                    {
                        var fileAttachment = attachment as FileAttachment;

                        // For files, we can build a stream directly from ContentBytes
                        if (fileAttachment.Size < (4 * 1024 * 1024))
                        {
                            MemoryStream fileStream = new MemoryStream(fileAttachment.ContentBytes);
                            bool         success    = await SaveFileToOneDrive(graphClient, fileAttachment.Name, fileStream);

                            if (!success)
                            {
                                return(BadRequest(string.Format("Could not save {0} to OneDrive", fileAttachment.Name)));
                            }
                        }
                        else
                        {
                            // TODO: Add code here to handle larger files. See:
                            // https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createuploadsession
                            // and
                            // https://github.com/microsoftgraph/aspnet-snippets-sample/blob/master/Graph-ASPNET-46-Snippets/Microsoft%20Graph%20ASPNET%20Snippets/Models/FilesService.cs
                            return(BadRequest("File is too large for simple upload."));
                        }
                    }
                }

                return(Ok());
            }
            else
            {
                return(BadRequest("Could not retrieve access token from request."));
            }
        }
Example #9
0
        private async Task <IHttpActionResult> SaveAttachmentsWithDistinctTokens(SaveAttachmentRequest request)
        {
            // Validate request
            if (request == null || !request.IsValid())
            {
                return(BadRequest("One or more parameters is missing."));
            }

            // Initialize a Graph client
            GraphServiceClient graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    (requestMessage) => {
                // Add the OneDrive access token to each outgoing request
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.oneDriveToken);
                return(Task.FromResult(0));
            }));

            // First get the attachments from the message
            // The token we get from the add-in is valid for the Outlook API,
            // not the Microsoft Graph API. That means we need to invoke the
            // Outlook endpoint directly, and we can't use the Graph library.
            // Build the request URI to the message attachments collection
            string baseAttachmentsUri = request.outlookRestUrl;

            if (!baseAttachmentsUri.EndsWith("/"))
            {
                baseAttachmentsUri += "/";
            }
            baseAttachmentsUri += "v2.0/me/messages/" + request.messageId + "/attachments/";

            using (var client = new HttpClient())
            {
                foreach (string attachmentId in request.attachmentIds)
                {
                    var getAttachmentReq = new HttpRequestMessage(HttpMethod.Get, baseAttachmentsUri + attachmentId);

                    // Headers
                    getAttachmentReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.outlookToken);
                    getAttachmentReq.Headers.UserAgent.Add(new ProductInfoHeaderValue("AttachmentsDemoOutlookAddin", "1.0"));
                    getAttachmentReq.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var result = await client.SendAsync(getAttachmentReq);

                    string json = await result.Content.ReadAsStringAsync();

                    OutlookAttachment attachment = JsonConvert.DeserializeObject <OutlookAttachment>(json);

                    // Is this a file or an Outlook item?
                    if (attachment.Type.ToLower().Contains("itemattachment"))
                    {
                        // Currently REST API doesn't support access to the MIME stream
                        // So for now, just get the JSON representation of the attached item and save it
                        // as a JSON file
                        var getAttachedItemJsonReq = new HttpRequestMessage(HttpMethod.Get, baseAttachmentsUri +
                                                                            attachmentId + "?$expand=Microsoft.OutlookServices.ItemAttachment/Item");

                        getAttachedItemJsonReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.outlookToken);
                        getAttachedItemJsonReq.Headers.UserAgent.Add(new ProductInfoHeaderValue("AttachmentsDemoOutlookAddin", "1.0"));
                        getAttachedItemJsonReq.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var getAttachedItemResult = await client.SendAsync(getAttachedItemJsonReq);

                        Stream jsonAttachedItem = await getAttachedItemResult.Content.ReadAsStreamAsync();

                        bool success = await SaveFileToOneDrive(graphClient, attachment.Name + ".json", jsonAttachedItem);

                        if (!success)
                        {
                            return(BadRequest(string.Format("Could not save {0} to OneDrive", attachment.Name)));
                        }
                    }
                    else
                    {
                        // For files, we can build a stream directly from ContentBytes
                        if (attachment.Size < (4 * 1024 * 1024))
                        {
                            MemoryStream fileStream = new MemoryStream(Convert.FromBase64String(attachment.ContentBytes));
                            bool         success    = await SaveFileToOneDrive(graphClient, attachment.Name, fileStream);

                            if (!success)
                            {
                                return(BadRequest(string.Format("Could not save {0} to OneDrive", attachment.Name)));
                            }
                        }
                        else
                        {
                            // TODO: Add code here to handle larger files. See:
                            // https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/item_createuploadsession
                            // and
                            // https://github.com/microsoftgraph/aspnet-snippets-sample/blob/master/Graph-ASPNET-46-Snippets/Microsoft%20Graph%20ASPNET%20Snippets/Models/FilesService.cs
                            return(BadRequest("File is too large for simple upload."));
                        }
                    }
                }
            }
            return(Ok());
        }
        public async Task <string> Authorize([FromBody] SaveAttachmentRequest request)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                //string credPath = "token.json";
                var credPath = System.Web.HttpContext.Current.Server.MapPath("/App_Data/MyGoogleStorage");


                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }


            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            FilesResource.CreateMediaUpload uploadRequest;

            string childId;
            string parentId;
            // Google allows folders with same name.
            // If the Outlook Attachments already exists, don't create another one
            var folder = findFolder(service, "Outlook Attachments");

            parentId = folder.Id;
            if (parentId == null)
            {
                parentId = createFolderGoogleDrive(service, "Outlook Attachments", null);
                childId  = createFolderGoogleDrive(service, request.subject, parentId);
            }
            else
            {
                childId = createFolderGoogleDrive(service, request.subject, folder.Id);
            }
            /* Start get attachment */

            using (var client = new HttpClient())
            {
                // Get content bytes
                string baseAttachmentUri = request.outlookRestUrl;
                if (!baseAttachmentUri.EndsWith("/"))
                {
                    baseAttachmentUri += "/";
                }
                baseAttachmentUri += "v2.0/me/messages/" + request.messageId + "/attachments/";


                var i = 0;
                foreach (string attachmentId in request.attachmentIds)
                {
                    var getAttachmentReq = new HttpRequestMessage(HttpMethod.Get, baseAttachmentUri + attachmentId);

                    // Headers
                    getAttachmentReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.outlookToken);
                    getAttachmentReq.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var result = await client.SendAsync(getAttachmentReq);

                    string json = await result.Content.ReadAsStringAsync();

                    OutlookAttachment attachment = JsonConvert.DeserializeObject <OutlookAttachment>(json);

                    Google.Apis.Drive.v3.Data.File fileMetaData = new Google.Apis.Drive.v3.Data.File();
                    fileMetaData.Name    = attachment.Name;
                    fileMetaData.Parents = new List <string>();

                    fileMetaData.Parents.Add(childId); // child folder Id

                    // For files, build a stream directly from ContentBytes
                    if (attachment.Size < (4 * 1024 * 1024))
                    {
                        MemoryStream stream;

                        using (stream = new MemoryStream(Convert.FromBase64String(attachment.ContentBytes)))
                        {
                            uploadRequest = service.Files.Create(
                                fileMetaData, stream, Format.GetMimeType(attachment.Name));
                            uploadRequest.Fields = "id";
                            uploadRequest.Upload();
                        }
                        try
                        {
                            var file = uploadRequest.ResponseBody;
                            Console.WriteLine("File ID: " + file.Id);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }

                        i++;
                    }
                    else
                    {
                        // TODO: Implement functionality to support > 4 MB files
                    }
                }
            }


            /* End get attachment */

            return(parentId);
        }