예제 #1
0
 public static Task UploadFolderToSharePoint(Item item, string projectName)
 {
     return(Task.Run(() =>
     {
         UploadItemtoSharepoint(item, SharepointHelper.ProjectFolder(projectName), _ClientContext);
     }));
 }
예제 #2
0
        public ShareFTPForm()
        {
            InitializeComponent();

            cmbx_projectnames.ItemsSource = SharepointHelper.GetSubFolderNames();
            Object = this;
        }
예제 #3
0
        private async void OnLoginO365(object sender, RoutedEventArgs e)
        {
            if (!SharepointHelper.CheckIfTheUserIsInTheNetwork())
            {
                System.Windows.MessageBox.Show("Sorry you can't use any network outside Archcorp's domain. To use the application, please connect to archcorp network or get in touch with IT admins. Thank you",
                                               "Access Denied", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                button_login.IsEnabled = true;
                return;
            }


            button_login.IsEnabled = false;

            txt_loginerror.Text = string.Empty;
            string email    = txtbx_email.Text;
            string password = txtbx_password.Password;
            string url      = "https://archcorp365.sharepoint.com/sites/archcorpftp/";

            txt_loginerror.Text = await LoginTo365Async(email, password, url);

            button_login.IsEnabled = true;

            // If there is some error then don't return
            if (!String.IsNullOrEmpty(txt_loginerror.Text))
            {
                return;
            }

            Properties.Settings.Default.username = txtbx_email.Text;
            Properties.Settings.Default.password = txtbx_password.Password;
            Properties.Settings.Default.Save();

            new ShareFTPForm().Show();
            this.Close();
        }
예제 #4
0
        private async void OnShareToFTP(object sender, RoutedEventArgs e)
        {
            if ((cmbx_projectnames.SelectedItem == null))
            {
                txt_shareError.Foreground = new SolidColorBrush(Colors.Red);
                txt_shareError.Text       = "Please select the project folder.";
                return;
            }

            button_shareFtp.IsEnabled     = false;
            button_selectFolder.IsEnabled = false;
            img_loading.Visibility        = Visibility.Visible;
            txt_shareError.Text           = string.Empty;
            txt_shareEmail.Visibility     = Visibility.Hidden;

            if ((string.IsNullOrEmpty(txt_folderPath.Text) || string.IsNullOrEmpty(cmbx_projectnames.SelectedItem.ToString())))
            {
                txt_shareError.Foreground = new SolidColorBrush(Colors.Red);
                txt_shareError.Text       = "Please select file and project where you wish to share it.";
                return;
            }

            var selectProject = cmbx_projectnames.SelectedItem.ToString();

            if (SharepointHelper.IsFolderExistSP(cmbx_projectnames.SelectedItem.ToString(), Item.Name))
            {
                var result = System.Windows.MessageBox.Show($"'{Item.Name}' folder already exist. Do you want to override it?", "Important", MessageBoxButton.YesNo, MessageBoxImage.Information);

                if (result == MessageBoxResult.No)
                {
                    return;
                }
            }

            await SharepointHelper.UploadFolderToSharePoint(Item, selectProject);

            var hyperlink = SharepointHelper.GetFolderHyperLink(Item.Folder);;

            SharepointHelper.InsertEnquiryToSharepoint(txt_folderPath.Text, Item.Folder, hyperlink);
            txt_shareHyperlink.Text = hyperlink;

            txt_uploadingsize.Visibility = Visibility.Hidden;
            img_loading.Visibility       = Visibility.Hidden;

            txt_shareEmail.Visibility = Visibility.Visible;
            //txt_folderPath.Text = string.Empty;

            if (!string.IsNullOrEmpty(txt_shareHyperlink.Text))
            {
                txt_shareError.Foreground = new SolidColorBrush(Colors.Green);
                txt_shareError.Text       = "The shared link will get expired after 14 Days.\n\t   Shared Successfully!";
            }

            button_selectFolder.IsEnabled = true;
            btn_copyclipboard.IsEnabled   = true;
        }
예제 #5
0
        private Task <string> LoginTo365Async(string email, string password, string url = "https://archcorp365.sharepoint.com/sites/archcorpftp/")
        {
            return(Task.Run(() =>
            {
                if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
                {
                    return "Please type correct email and password";
                }

                try
                {
                    SharepointHelper.Login(email, password, url);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }


                return "";
            }));
        }
예제 #6
0
        public static string UploadFileSlicePerSlice(ClientContext ctx, Folder selectedSubFolder, string filepath, int fileChunkSizeInMB = 10)
        {
            // Each sliced upload requires a unique ID.
            Guid uploadId = Guid.NewGuid();

            // Get the name of the file.
            string uniqueFileName = Path.GetFileName(filepath);


            // Get the folder to upload into.
            // List docs = ctx.Web.Lists.GetByTitle(libraryName);


            // File object.
            Microsoft.SharePoint.Client.File uploadFile;

            // Calculate block size in bytes.
            int blockSize = fileChunkSizeInMB * 1024 * 1024;

            var expireDateforDownloadLink = DateTime.Now.AddDays(14).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");


            // Get the size of the file.
            long fileSize = new FileInfo(filepath).Length;

            // If file already exist
            if (SharepointHelper.IsFileExistSP(ctx, selectedSubFolder.Name, filepath))
            {
                var result = System.Windows.MessageBox.Show($"file name '{Path.GetFileName(filepath)}' already exist. Do you wish to overwrite it?", "Overwrite Existing File", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Warning);

                if (result == System.Windows.MessageBoxResult.No)
                {
                    return(string.Empty);
                }
            }

            if (fileSize <= blockSize)
            {
                // Use regular approach.
                using (FileStream fs = new FileStream(filepath, FileMode.Open))
                {
                    FileCreationInformation fileInfo = new FileCreationInformation();
                    fileInfo.ContentStream = fs;
                    fileInfo.Url           = uniqueFileName;
                    fileInfo.Overwrite     = true;
                    uploadFile             = selectedSubFolder.Files.Add(fileInfo);
                    ctx.Load(uploadFile);
                    ctx.ExecuteQuery();

                    // Return the file object for the uploaded file.
                    ctx.Load(uploadFile.ListItemAllFields, item => item["EncodedAbsUrl"]);
                    ctx.ExecuteQuery();

                    var sharelink = Microsoft.SharePoint.Client.Web.CreateAnonymousLinkWithExpiration(ctx, uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString(), false, expireDateforDownloadLink);
                    ctx.ExecuteQuery();
                    var val = sharelink.Value;

                    //return uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString();
                    return(val = sharelink.Value);
                }
            }
            else
            {
                // Use large file upload approach.
                ClientResult <long> bytesUploaded = null;

                FileStream fs = null;
                try
                {
                    fs = System.IO.File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        byte[] buffer         = new byte[blockSize];
                        Byte[] lastBuffer     = null;
                        long   fileoffset     = 0;
                        long   totalBytesRead = 0;
                        int    bytesRead      = 0;
                        bool   first          = true;
                        bool   last           = false;
                        string downloadablURL = "";



                        // Display the uploading progress
                        ShareFTPForm.Object.txt_uploadingsize.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                                                                                new Action(() =>
                                                                                           { ShareFTPForm.Object.txt_uploadingsize.Visibility = System.Windows.Visibility.Visible; }));

                        // Read data from file system in blocks.
                        while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            // Display the uploading progress
                            ShareFTPForm.Object.txt_uploadingsize.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                                                                                    new Action(() =>
                                                                                               { ShareFTPForm.Object.txt_uploadingsize.Text = $"{totalBytesRead / 1024 / 1024} MB of {fileSize / 1024 / 1024} MB Uploaded"; }));

                            totalBytesRead = totalBytesRead + bytesRead;

                            // You've reached the end of the file.
                            if (totalBytesRead == fileSize)
                            {
                                last = true;
                                // Copy to a new buffer that has the correct size.
                                lastBuffer = new byte[bytesRead];
                                Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
                            }

                            if (first)
                            {
                                using (MemoryStream contentStream = new MemoryStream())
                                {
                                    // Add an empty file.
                                    FileCreationInformation fileInfo = new FileCreationInformation();
                                    fileInfo.ContentStream = contentStream;
                                    fileInfo.Url           = uniqueFileName;
                                    fileInfo.Overwrite     = true;
                                    uploadFile             = selectedSubFolder.Files.Add(fileInfo);
                                    // Start upload by uploading the first slice.
                                    using (MemoryStream s = new MemoryStream(buffer))
                                    {
                                        // Call the start upload method on the first slice.
                                        bytesUploaded = uploadFile.StartUpload(uploadId, s);
                                        ctx.ExecuteQuery();

                                        // Return the file object for the uploaded file.
                                        ctx.Load(uploadFile.ListItemAllFields, item => item["EncodedAbsUrl"]);
                                        ctx.ExecuteQuery();

                                        // Get the downloadable link
                                        //var sharelink = Microsoft.SharePoint.Client.Web.CreateAnonymousLink(_ClientContext, uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString(), false);
                                        var sharelink = Microsoft.SharePoint.Client.Web.CreateAnonymousLinkWithExpiration(ctx, uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString(), false, expireDateforDownloadLink);
                                        ctx.ExecuteQuery();
                                        var val = sharelink.Value;
                                        downloadablURL = sharelink.Value;

                                        // downloadablURL = uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString();
                                        // fileoffset is the pointer where the next slice will be added.
                                        fileoffset = bytesUploaded.Value;
                                    }

                                    // You can only start the upload once.
                                    first = false;
                                }
                            }
                            else
                            {
                                // Get a reference to your file.
                                uploadFile = ctx.Web.GetFileByServerRelativeUrl(selectedSubFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName);

                                if (last)
                                {
                                    // Is this the last slice of data?
                                    using (MemoryStream s = new MemoryStream(lastBuffer))
                                    {
                                        // End sliced upload by calling FinishUpload.
                                        uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
                                        ctx.ExecuteQuery();


                                        return(downloadablURL);
                                    }
                                }
                                else
                                {
                                    using (MemoryStream s = new MemoryStream(buffer))
                                    {
                                        // Continue sliced upload.
                                        bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
                                        ctx.ExecuteQuery();
                                        // Update fileoffset for the next slice.
                                        fileoffset = bytesUploaded.Value;
                                    }
                                }
                            }
                        } // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                    }
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Dispose();
                    }
                }
            }

            return(null);
        }