public void CreateTemplate()
        {
            DocumentsService service = new DocumentsService(applicationName);

            DocumentEntry entry = new DocumentEntry();

            // Set the document title
            entry.Title.Text = spreadsheetName;
            entry.IsSpreadsheet = true;

            // Set the media source
            entry.MediaSource = new MediaFileSource(GetStreamWithTemplate(), applicationName, "text/csv");

            // Define the resumable upload link
            Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full");
            AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri);
            link.Rel = ResumableUploader.CreateMediaRelation;
            entry.Links.Add(link);

            // Set the service to be used to parse the returned entry
            entry.Service = service;

            // Instantiate the ResumableUploader component.
            ResumableUploader uploader = new ResumableUploader();

            // Start the upload process
            uploader.Insert(new ClientLoginAuthenticator(applicationName,ServiceNames.Documents,userName,password), entry);
        }
        public static void getSpreadSheet(string _spreadSheetName)
        {
            DocumentsService documentsService = getDocumentsService();

            // Instantiate a DocumentsListQuery object to retrieve documents.
            DocumentsListQuery query = new DocumentsListQuery();

            // Make a request to the API and get all documents.

            DocumentsFeed feed = documentsService.Query(query);
            DocumentEntry documentEntryDefinition = new DocumentEntry();

            // Iterate through all of the documents returned
            foreach (DocumentEntry entry in feed.Entries)
            {
                // Print the title of this document to the screen
                Console.WriteLine(" ---- Found - " + entry.Title.Text + "" + entry.IsSpreadsheet);

            }

            //            documentEntryDefinition.Title.Text = "MyMonitisTestSpreadsheet";

            //            documentEntryDefinition.Categories.Add(DocumentEntry.SPREADSHEET_CATEGORY);

            //            documentEntryHandle = documentsService.Insert(DocumentsListQuery.documentsBaseUri, documentEntryDefinition);
        }
示例#3
0
		public DocItem(DocumentEntry docEntry)
		{
			//Retrieve the type of the document.
			if(docEntry.IsDocument)
				_docType = "[Document] ";
			else if(docEntry.IsPDF)
				_docType = "[PDF] ";
			else if(docEntry.IsSpreadsheet)
				_docType = "[Spreadsheet] ";
			else if(docEntry.IsPresentation)
				_docType = "[Presentation] ";
			else
				_docType = "[Other] ";
			
            //Retrieve the title of the document.
            _docName = docEntry.Title.Text;

            //Retrieve the modified date and time of the document.
            DateTime timeNow = DateTime.Now;
			int timestamp_difference = (int)((TimeSpan)(timeNow - docEntry.Updated.ToLocalTime())).TotalSeconds;
			if(timestamp_difference < 60)
				_modifiedDate = timestamp_difference.ToString() + " seconds ago";
			else if(timestamp_difference < 120)
				_modifiedDate = "1 minute ago";
            else if (timestamp_difference < 3600)
                _modifiedDate = (timestamp_difference / 60).ToString() + " minutes ago";
            else if (timestamp_difference < 7200)
                _modifiedDate = "1 hour ago";
            else if (timestamp_difference < 86400)
                _modifiedDate = (timestamp_difference / 3600).ToString() + " hours ago";
            else
			    _modifiedDate = docEntry.Updated.ToLocalTime().ToString();

            _modifiedDate += " ";

            //Retrieve the name of the person who updated the document.
            _updater = "Updated by: ";
            
            foreach (object obj in docEntry.ExtensionElements)
            {
                //Retrieve the name of the person who updated the document.
                if (obj.GetType().Name.Equals("XmlExtension")
                    && ((XmlExtension)obj).XmlName.Equals("lastModifiedBy"))
                {
                    _updater += ((XmlExtension)obj).Node.FirstChild.InnerText;

                    //Stop iterating through the ExtensionElements because
                    //lastModifiedBy tag is the last tag in the XML feed that
                    //we are interested in.
                    break;
                }
            }

            //Retrieve the URL to the document on the Internet.
            alternateURL = docEntry.AlternateUri.Content.ToString();
		}
        public static DocumentEntry createSpreadSheet(string _spreadSheetName)
        {
            DocumentsService documentsService = getDocumentsService();

            DocumentEntry documentEntryDefinition = new DocumentEntry();
            documentEntryDefinition.Title.Text = _spreadSheetName;

            documentEntryDefinition.Categories.Add(DocumentEntry.SPREADSHEET_CATEGORY);

            documentEntryHandle = documentsService.Insert(DocumentsListQuery.documentsBaseUri, documentEntryDefinition);

            return documentEntryHandle;
        }
        /// <summary>
        /// Simple method to upload an arbitrary file.
        /// </summary>
        /// <param name="fileName">The full path to the file.</param>
        /// <param name="documentName">The desired name of the file on the server.</param>
        /// <param name="contentType">The mime type of the file</param>
        /// <param name="convert">Indiates if the document should be converted to a known type on the server</param>
        /// <returns>A DocumentEntry describing the created document.</returns>
        public DocumentEntry UploadFile(string fileName, string documentName, string contentType, bool convert)
        {
            DocumentEntry entry = null;

            FileInfo   fileInfo = new FileInfo(fileName);
            FileStream stream   = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            try
            {
                Uri postUri;

                if (convert == false)
                {
                    postUri = new Uri(DocumentsListQuery.documentsBaseUri + "?convert=false");
                }
                else
                {
                    postUri = new Uri(DocumentsListQuery.documentsBaseUri);
                }


                if (documentName == null)
                {
                    documentName = fileInfo.Name;
                }

                if (contentType == null)
                {
                    throw new ArgumentException("You need to specify a content type, like text/html");
                }

                entry = this.Insert(postUri, stream, contentType, documentName) as DocumentEntry;
            }
            finally
            {
                stream.Close();
            }

            return(entry);
        }
示例#6
0
        private void MoveGoogleNote(DocumentEntry entry, NoteMatch match, bool create, Exception ex, bool cancelled)
        {
            if (ex != null)
            {
                ErrorHandler.Handle(new Exception("Google Note couldn't be " + (create ? "created" : "updated") + " :" + entry == null ? null : entry.Summary.ToString(), ex));
                return;
            }

            if (cancelled || entry == null)
            {
                ErrorHandler.Handle(new Exception("Google Note " + (create ? "creation" : "update") + " was cancelled: " + entry == null ? null : entry.Summary.ToString()));
                return;
            }

            //Get updated Google Note
            Document newNote = LoadGoogleNotes(null, entry.Id);
            match.GoogleNote = newNote;

            //Doesn't work because My Drive is not listed as parent folder: Remove all parent folders except for the Notes subfolder
            //if (create)
            //{
            //    foreach (string parentFolder in newNote.ParentFolders)
            //        if (parentFolder != googleNotesFolder.Self)
            //            DocumentsRequest.Delete(new Uri(googleNotesFolder.DocumentEntry.Content.AbsoluteUri + "/" + newNote.ResourceId),newNote.ETag);
            //}

            //first delete the note from all categories, the still valid categories are assigned again later
            foreach (string parentFolder in newNote.ParentFolders)
                if (parentFolder != googleNotesFolder.Self) //Except for Notes root folder
                {
                    Document deletedNote = LoadGoogleNotes(parentFolder + "/contents", newNote.DocumentEntry.Id);
                    //DocumentsRequest.Delete(new Uri(parentFolder + "/contents/" + newNote.ResourceId), newNote.ETag);
                    DocumentsRequest.Delete(deletedNote); //Just delete it from this category
                }

            //Move now to Notes subfolder (if not already there)
            if (!IsInFolder(googleNotesFolder, newNote))
                newNote = DocumentsRequest.MoveDocumentTo(googleNotesFolder, newNote);

            //Move now to all categories subfolder (if not already there)
            foreach (string category in Utilities.GetOutlookGroups(match.OutlookNote.Categories))
            {
                Document categoryFolder = GetOrCreateGoogleFolder(googleNotesFolder, category);

                if (!IsInFolder(categoryFolder, newNote))
                    newNote = DocumentsRequest.MoveDocumentTo(categoryFolder, newNote);
            }

            //Then update the match IDs
            UpdateNoteMatchId(match);

            Logger.Log((create ? "Created" : "Updated") + " Google note from Outlook: \"" + match.OutlookNote.Subject + "\".", EventType.Information);
            //Then release this match as completed (to not log the summary already before each single note result has been synced
            match.AsyncUpdateCompleted = true;
        }
 public ListViewUpdatedEventArgs(DocumentEntry entry)
     : base()
 {
     _docEntry = entry;
 }
        /// <summary>
        /// Perform the follwoing actions to those new or unread updated documents:
        /// 1. Check if the document is the newest among all;
        /// 2. Update GUI in order to add the document to the listView;
        /// 3. Increase the count of number of unviewed documents.
        /// </summary>
        /// <param name="entry">The document entry.</param>
        /// <param name="isNewUpdate">Indicator specifying if the documents is the newest among all.</param>
        /// <param name="latestEditedTime">The latest edited time of the newest document.</param>
        /// <param name="latestEditedTitle">The title of the newest document.</param>
        /// <param name="unviewedDocuments">The count of number of unviewed documents.</param>
        private void HandleNewOrUnreadUpdatedDocuments(
            DocumentEntry entry,
            ref bool isNewUpdate, ref DateTime latestEditedTime,
            ref string latestEditedTitle, ref int unviewedDocuments)
        {
            //Check if the document is the newest among all the documents.
            if (CheckIfDocumentIsNewest(entry, ref latestEditedTime, ref latestEditedTitle))
                isNewUpdate = true;

            //Inform the GUI to add the new document entry to the listView.
            AddNewEntryToListView(entry);

            //Count the number of unviewed documents.
            unviewedDocuments++;
        }
        /// <summary>
        /// This part handles the ExtensionElement of the document entry.
        /// It will retrieve the lastEdited time and lastViewed time of the document.
        /// </summary>
        /// <param name="entry">The current document entry.</param>
        /// <param name="lastEditedTime">The latest edited time for this current document entry.</param>
        /// <param name="lastViewedTime">The latest viewed time for this current document entry.</param>
        private void HandleExtensionElements(
            DocumentEntry entry, 
            ref DateTime lastEditedTime, ref DateTime lastViewedTime)
        {
            foreach (object obj in entry.ExtensionElements)
            {
                //Retrieve the lastEdited time of the document.
                if (obj.GetType().Name.Equals("AppEdited")
                    && ((AppEdited)obj).XmlName.Equals("edited"))
                {
                    lastEditedTime = ((AppEdited)obj).DateValue;
                }

                //Retrieve the lastViewed time of the document.
                if (obj.GetType().Name.Equals("XmlExtension")
                    && ((XmlExtension)obj).XmlName.Equals("lastViewed"))
                {
                    lastViewedTime =
                        convertStringToDateTime(((XmlExtension)obj).Node.InnerText);

                    //Stop iterating through the ExtensionElements because
                    //lastViewed tag is the last tag in the XML feed that
                    //we are interested in.
                    break;
                }
            }
        }
 /// <summary>
 /// Inform the GUI to add one new entry to the ListView control.
 /// </summary>
 /// <param name="entry">The document entry that will be added to the ListView.</param>
 private void AddNewEntryToListView(DocumentEntry entry)
 {
     if (ListViewUpdated != null)
         ListViewUpdated(this, new ListViewUpdatedEventArgs(entry));
 }
 /// <summary>
 /// Responsible for verifying if the document is updated and unviewed.
 /// </summary>
 /// <param name="entry">The document entry.</param>
 /// <param name="lastViewedTime">The last viewed time of the document entry.</param>
 /// <returns>True if the document is updated and unviewed.</returns>
 private bool VerifyUnviewedUpdatedDocuments(DocumentEntry entry, DateTime lastViewedTime)
 {
     return timeStampDifference(lastViewedTime.ToLocalTime(), entry.Updated.ToLocalTime()) < 0;
 }
        /// <summary>
        /// Check if the current document is a new document or not.
        /// </summary>
        /// <param name="entry">The current document entry.</param>
        /// <returns>True if the current document is newly created.</returns>
        private static bool VerifyNewDocuments(DocumentEntry entry)
        {
            bool isDocumentNew = true;
            for (int i = 0; i < entry.Categories.Count(); i++)
            {
                //New documents will not be labelled as "viewed" in Google feeds.
                if (entry.Categories[i].Label.Equals("viewed"))
                {
                    isDocumentNew = false;
                    break;
                }
            }

            return isDocumentNew;
        }
示例#13
0
        static GDocsAbstractItem MaybeItemFromEntry(DocumentEntry doc)
        {
            string url = doc.AlternateUri.Content;
            string title = doc.Title.Text;

            if (doc.IsDocument)
                return new GDocsDocumentItem (title, url);
            else if (doc.IsSpreadsheet)
                return new GDocsSpreadsheetItem (title, url);
            else if (doc.IsPresentation)
                return new GDocsPresentationItem (title, url);
            else if (doc.IsPDF)
                return new GDocsPDFItem (title, url);
            return null;
        }
示例#14
0
        // this method creates the spreadsheet, deletes the old one if overwrite is on and there's already on with the same name,
        // and adds the worksheets if they've been specified. Wrapped in a static method so other components (like WriteToSpreadsheet)
        // can make use of it and create new spreadsheets.
        public static SpreadsheetEntry createNewSpreadsheet(GH_ActiveObject activeObj, AuthToken authToken, string sheetName, List<string> worksheets, bool overwrite)
        {
            SpreadsheetEntry matchingEntry = null;
            //setup OAuth Parameters
            OAuth2Parameters parameters = GDriveUtil.GetParameters(authToken);

            // It seems clunky to need both a SpreadsheetService and a DocumentService - but
            // DocumentService is necessary to add/delete spreadsheets, and SpreadsheetService
            // is needed to manipulate the worksheets.

            //setup auth and factory for documentsService

            GOAuth2RequestFactory requestFactory =
              new GOAuth2RequestFactory(null, "MyDocumentsListIntegration-v1", parameters);
            DocumentsService docService = new DocumentsService("MyDocumentsListIntegration-v1");
            docService.RequestFactory = requestFactory;

            //setup SpreadsheetsService
            SpreadsheetsService service = GDriveUtil.GetSpreadsheetsService(parameters);

            //make spreadsheet documentquery
            Google.GData.Documents.SpreadsheetQuery dQuery = new Google.GData.Documents.SpreadsheetQuery();

            DocumentsFeed dFeed = docService.Query(dQuery);

            //if user has opted to overwrite, find first matching spreadsheet and delete. If no matching spreadsheet found, nothing happens.
            if (overwrite)
            {

                foreach (DocumentEntry entry in dFeed.Entries)
                {
                    if (entry.Title.Text.Equals(sheetName))
                    {
                        docService.Delete(entry);
                        break;
                    }
                }
            }

            //create new spreadsheet object
            DocumentEntry dEntry = new DocumentEntry();
            dEntry.Title.Text = sheetName;
            dEntry.Categories.Add(DocumentEntry.SPREADSHEET_CATEGORY);
            docService.Insert(DocumentsListQuery.documentsBaseUri, dEntry);

            //find the spreadsheet we just created as a SpreadsheetEntry

            matchingEntry = GDriveUtil.findSpreadsheetByName(sheetName, service);
            //if worksheets specified, add worksheets
            if (worksheets.Count > 0)
            {

                if (matchingEntry == null) //this shouldn't ever happen, since we just created a new spreadsheet called sheetName.
                {
                    activeObj.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went wrong with spreadsheet creation.");
                    return null;
                }

                WorksheetFeed wsFeed = matchingEntry.Worksheets;

                //first, we find the existing worksheets, store them, add new ones, and then delete the old.

                List<WorksheetEntry> entriesToDelete = new List<WorksheetEntry>();
                foreach (WorksheetEntry entry in wsFeed.Entries)
                {
                    entriesToDelete.Add(entry);
                }

                // find the dimensions of the first worksheet, to use for other worksheet creation
                uint rows = ((WorksheetEntry)wsFeed.Entries[0]).Rows;
                uint cols = ((WorksheetEntry)wsFeed.Entries[0]).Cols;

                for (int i = 0; i < worksheets.Count; i++)
                {
                    {
                        string wsName = worksheets[i];

                        WorksheetEntry entry = new WorksheetEntry(rows, cols, wsName);
                        service.Insert(wsFeed, entry);
                    }
                }

                foreach (WorksheetEntry entryToDelete in entriesToDelete)
                {
                    entryToDelete.Delete();
                }

            }

            //end if worksheets...

            return matchingEntry;
        }
        private WorksheetEntry createSpreadSheet(string sheetName)
        {
            DocumentsService docService = new DocumentsService(this.googleAppName);
            docService.RequestFactory = GoogleOauthAccess.getRequestFactory(this.googleAppName, this.parameters);

            DocumentEntry entry = new DocumentEntry();
            entry.Title.Text = sheetName;
            entry.Categories.Add(DocumentEntry.SPREADSHEET_CATEGORY);

            DocumentEntry newEntry = docService.Insert(DocumentsListQuery.documentsBaseUri, entry);

            return this.searchForSpreadsheet(entry.Title.Text);
        }
 /// <summary>
 /// Uploads the file to Google Docs
 /// </summary>
 /// <param name="fileName">The file with path to upload</param>
 /// <exception cref="ApplicationException">Thrown when user isn't logged in.</exception>
 public void UploadFile(string fileName)
 {
     if (!loggedIn)
     {
         throw new ApplicationException("Need to be logged in to upload documents.");
     }
     else
     {
         lastUploadEntry = service.UploadDocument(fileName, null);
     }
 }
示例#17
0
        public void DoWorkbookUpload(object in_instance)
        {
            var instance = in_instance as Google2uData;
            if (instance == null)
                return;

            if (!string.IsNullOrEmpty(instance.WorkbookUploadPath))
            {
                try
                {
                    // We need a DocumentService
                    var service = new DocumentsService("Google2Unity");
                    var mimeType = Google2uMimeType.GetMimeType(instance.WorkbookUploadPath);

                    var authenticator = new OAuth2Authenticator("Google2Unity", _authParameters);

                    // Instantiate a DocumentEntry object to be inserted.
                    var entry = new DocumentEntry
                    {
                        MediaSource = new MediaFileSource(instance.WorkbookUploadPath, mimeType)
                    };

                    // Define the resumable upload link
                    var createUploadUrl =
                        new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full");
                    var link = new AtomLink(createUploadUrl.AbsoluteUri)
                    {
                        Rel = ResumableUploader.CreateMediaRelation
                    };

                    entry.Links.Add(link);

                    // Set the service to be used to parse the returned entry
                    entry.Service = service;


                    // Instantiate the ResumableUploader component.
                    var uploader = new ResumableUploader();

                    // Set the handlers for the completion and progress events
                    uploader.AsyncOperationCompleted += OnSpreadsheetUploadDone;
                    uploader.AsyncOperationProgress += OnSpreadsheetUploadProgress;

                    // Start the upload process
                    uploader.InsertAsync(authenticator, entry, instance);
                }
                catch (Exception)
                {
                    PushNotification(
                        "There is a problem with your credentials. Clear the credentials and Re-Authorize G2U");
                    //instance.Messages.Add(new G2GUIMessage(GFGUIMessageType.InvalidLogin, ex.Message));
                    instance.Commands.Remove(GFCommand.WaitingForUpload);
                }
            }
        }
 /// <summary>
 /// Verify if the document is the newest document among the updated documents.
 /// </summary>
 /// <param name="entry">The current document entry.</param>
 /// <param name="latestEditedTime">The edited time of the newest document.</param>
 /// <param name="latestEditedTitle">The name of the newest document.</param>
 /// <returns>Returns true if the document is the newest one among all the known documents so far.</returns>
 private bool CheckIfDocumentIsNewest(DocumentEntry entry, ref DateTime latestEditedTime, ref string latestEditedTitle)
 {
     if (timeStampDifference(latestEditedTime.ToLocalTime(), entry.Updated.ToLocalTime()) < 0)
     {
         latestEditedTime = entry.Updated;
         latestEditedTitle = entry.Title.Text;
         return true;
     }
     return false;
 }