I want to share a file that exists in Google Drive with a specified user. The file is not public.
Firstly, I want to show a file in a WebBrowser control.
Secondly, I want that when I share an URL to a different user, they can then show the file in their Google Drive.
Here is my code, I already can do the first step but for the second step, I don't know how I can do it.
Public Sub A(fichier As String)
CreateService()
Dim url As String = ""
Dim list = Service.Files.List()
Dim count = list.Execute()
For Each fich In count.Items
If (fich.Title) = fichier Then
url = fich.WebContentLink
Exit For
End If
Next
affich_image.img.Navigate(url)
affich_image.Show()
You can use the permissions.insert method.
Inserts a permission for a file or Team Drive.
To see the parameters and further details, try to visit the documentation.
Here, I provide you the sample code for .NET that was introduced in the said documentation.
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using System.Net;
// ...
public class MyClass {
// ...
/// <summary>
/// Insert a new permission.
/// </summary>
/// <param name="service">Drive API service instance.</param>
/// <param name="fileId">ID of the file to insert permission for.</param>
/// <param name="value">
/// User or group e-mail address, domain name or null for "default" type.
/// </param>
/// <param name="type">The value "user", "group", "domain" or "default".</param>
/// <param name="role">The value "owner", "writer" or "reader".</param>
/// <returns>The inserted permission, null is returned if an API error occurred</returns>
public static Permission InsertPermission(DriveService service, String fileId, String value,
String type, String role) {
Permission newPermission = new Permission();
newPermission.Value = value;
newPermission.Type = type;
newPermission.Role = role;
try {
return service.Permissions.Insert(newPermission, fileId).Execute();
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
// ...
}
You may also visit this SO post for further discussion.
Related
I update my app's metrics a lot in registry, and want to know which method of writing to system registry is significantly faster.
If you use a .NET decompiler to peek into the source code of the Interaction class/module under the Microsoft.VisualBasic namespace, you'll find that the SaveSetting() method actually uses SetValue() under the hood:*
/// <summary>Saves or creates an application entry in the Windows registry. The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more information, see <see cref="P:Microsoft.VisualBasic.Devices.ServerComputer.Registry" />.</summary>
/// <param name="AppName">Required. String expression containing the name of the application or project to which the setting applies.</param>
/// <param name="Section">Required. String expression containing the name of the section in which the key setting is being saved.</param>
/// <param name="Key">Required. String expression containing the name of the key setting being saved.</param>
/// <param name="Setting">Required. Expression containing the value to which <paramref name="Key" /> is being set.</param>
/// <exception cref="T:System.ArgumentException">Key registry could not be created, or user is not logged in.</exception>
/// <filterpriority>1</filterpriority>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.RegistryPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public static void SaveSetting(string AppName, string Section, string Key, string Setting)
{
Interaction.CheckPathComponent(AppName);
Interaction.CheckPathComponent(Section);
Interaction.CheckPathComponent(Key);
string text = Interaction.FormRegKey(AppName, Section);
RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(text);
if (registryKey == null)
{
throw new ArgumentException(Utils.GetResourceString("Interaction_ResKeyNotCreated1", new string[]
{
text
}));
}
try
{
registryKey.SetValue(Key, Setting);
}
catch (Exception ex)
{
throw ex;
}
finally
{
registryKey.Close();
}
}
Or in VB, if you prefer:
''' <summary>Saves or creates an application entry in the Windows registry. The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more information, see <see cref="P:Microsoft.VisualBasic.Devices.ServerComputer.Registry" />.</summary>
''' <param name="AppName">Required. String expression containing the name of the application or project to which the setting applies.</param>
''' <param name="Section">Required. String expression containing the name of the section in which the key setting is being saved.</param>
''' <param name="Key">Required. String expression containing the name of the key setting being saved.</param>
''' <param name="Setting">Required. Expression containing the value to which <paramref name="Key" /> is being set.</param>
''' <exception cref="T:System.ArgumentException">Key registry could not be created, or user is not logged in.</exception>
''' <filterpriority>1</filterpriority>
''' <PermissionSet>
''' <IPermission class="System.Security.Permissions.RegistryPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
''' </PermissionSet>
Public Sub SaveSetting(AppName As String, Section As String, Key As String, Setting As String)
Interaction.CheckPathComponent(AppName)
Interaction.CheckPathComponent(Section)
Interaction.CheckPathComponent(Key)
Dim text As String = Interaction.FormRegKey(AppName, Section)
Dim registryKey As RegistryKey = Registry.CurrentUser.CreateSubKey(text)
If registryKey Is Nothing Then
Throw New ArgumentException(Utils.GetResourceString("Interaction_ResKeyNotCreated1", New String() { text }))
End If
Try
registryKey.SetValue(Key, Setting)
Catch ex As Exception
Throw ex
Finally
registryKey.Close()
End Try
End Sub
Therefore, I would expect them to have the same performance in this particular case (assuming you will be basically replicating the same behavior). However, the Microsoft.Win32.Registry class (or the My.Computer.Registry property, which is just a wrapper for the said class) is going to be more flexible and provides more options as noted in the documentation (thanks, Jimi!) and in the XML comments shown above.
As to the performance, to be 100% certain (assuming you actually need to), then you should always measure.
* This code was extracted using ILSpy.
i am trying merge and compress PDF files using bitmiracle.docotic.pdf library(trial version) and for a merged file of size 700MB i am facing "out of memory exception", below is my code
/// <summary>
/// Open file for copy.
/// </summary>
/// <param name="file">File name.</param>
/// <param name="outputDocument">Output pdf document.</param>
private void OpenFileForCopy(string file, PdfDocument outputDocument)
{
if (isFirstFile)
{
outputDocument.Open(file);
}
else {
outputDocument.Append(file);
}
}
/// <summary>
/// Saves PDF merged pdf file to location specified.
/// </summary>
/// <param name="outputDocument">Merged pdf document.</param>
/// <param name="path">Path to be stored.</param>
/// <param name="source">Source of file.</param>
/// <param name="Number">Number.</param>
private string[] SavePDF(PdfDocument outputDocument, string path, string source, string Number)
{
string[] result = new string[2];
outputDocument.PageLayout = PdfPageLayout.SinglePage;
string newPath = path + "_" + "Merged";
string nor= Number.Substring(1);
Directory.CreateDirectory(newPath);
newPath += "\\Stmt" + source + nor+ ".pdf";
outputDocument.SaveOptions.Compression = BitMiracle.Docotic.Pdf.PdfCompression.Flate;
outputDocument.SaveOptions.UseObjectStreams = true;
outputDocument.SaveOptions.RemoveUnusedObjects = true;
outputDocument.SaveOptions.OptimizeIndirectObjects = false;
outputDocument.SaveOptions.WriteWithoutFormatting = true;
outputDocument.Save(newPath);
outputDocument.Dispose();
isFirstFile = true;
result[0] = source ;
result[1] = Convert.ToString(fileCount);
fileCount = 0;
return result;
}
The instance of PdfDocument happens to be used across methods
Kindly let me know if anything needs to modified
Thanks,
Kirankumar
Your code is ok. Jut please note that amount of memory the library consumes is proportional to total size and number of appended documents.
I would recommend you to save and re-open documents once in a while to reduce amount of memory consumed by the library. You can also use the following setting for intermediate saves.
outputDocument.SaveOptions.UseObjectStreams = false;
So, I propose you to try the following process:
Open document
Append no more than 10 (or other number) documents
Save document (intermediate save)
Open the document you just saved
Append next batch of documents
...
Please note that current version of the library can lead to out of memory exceptions even when the proposed process is used.
I know there's a lot of information about this subject, but I just can't seem to find an answer suitable to my specific needs:
I opened a new MVC 4.0 basic application (meaning, no "AuthConfig.cs" file exist).
I have already successfully implemented Facebook sign-in.
I can't seem to find any way to do the same with Google.
I already have a custom "Connect with google" button. I need a very simple code to authenticate using google. Please bare in mind, that after authentication, I need to get user information, and also get a hold of the user's calendar.
Please help
Thank you.
Some Code to help you get started
In AuthConfig file
OAuthWebSecurity.RegisterClient(new Mvc.GoogleCustomClient(), "Google", null);
In GoogleCustomClient.cs
public class GoogleCustomClient : OpenIdClient
{
public GoogleCustomClient()
: base("google", WellKnownProviders.Google) { }
/// <summary>
/// Gets the extra data obtained from the response message when authentication is successful.
/// </summary>
/// <param name="response">
/// The response message.
/// </param>
/// <returns>A dictionary of profile data; or null if no data is available.</returns>
protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response)
{
FetchResponse fetchResponse = response.GetExtension<FetchResponse>();
if (fetchResponse != null)
{
var extraData = new Dictionary<string, string>();
extraData.Add("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
extraData.Add("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country));
extraData.Add("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First));
extraData.Add("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last));
return extraData;
}
return null;
}
/// <summary>
/// Called just before the authentication request is sent to service provider.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
{
// Attribute Exchange extensions
var fetchRequest = new FetchRequest();
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
request.AddExtension(fetchRequest);
}
}
You can Use this Code to retrieve the User Information from google.
I am trying to downgrade a document using VSTO.
I have a webservice, that receive a byte array. This byte is from the current active document.
The webservice can only handle a 2007/2003 word doc file.
So I want to use the
document.DowngradeDocument();
But the webservice report an error, when sending the byte array.
If a do a SaveAs and force word to save as 2007/2003 doc format, then there is no problem.
So my question is:
1) Why is DowngradeDocument() function not working. Why is it not doing a proper downgrade.
2) Do I need to do something else when I have called DowngradeDocument()
This must be in memory, since the file a happen to be working on, is not saved on disk.
// Dennis
Thank you for taking the time to read this
--- edit d. 20120904 ---
I cant use the webservice error, since it does not make sense of the error.
It says that it can finde the file, and this is an error within and application at the other side.
So I have tryed, to save a document in the right format, and one that was downgraded.
Used the same code. One work and the other did not.
But here is how I save the file as a temp. Before I call this function I have done a document.DowngradeDocument();
So I need, when it save to also change the format, while calling the downgrade function.
In the documentation for this function, it is clear that all previous version of office can read it, if the function is called.
/// <summary>
/// Make a copy of ActiveDocument in current user temp folder, and get a byte[].
/// </summary>
/// <param name="filename"></param>
/// <param name="document"></param>
/// <param name="file"></param>
/// <returns></returns>
private byte[] MakeCopy(string filename, Document document, out FileInfo file)
{
// http://blogs.msdn.com/b/pranavwagh/archive/2008/04/03/how-to-do-a-save-copy-as-in-word.aspx
// http://stackoverflow.com/questions/12175273/serialize-current-activedocument-from-office-2007-add-in
Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
wdApp.Visible = false;
{
// make a fil i Current user temp folder
// http://stackoverflow.com/questions/944483/how-to-get-temporary-folder-for-current-user
string tempPath = System.IO.Path.GetTempPath();
string fileName = Path.Combine(tempPath, GenerateValidFileName(filename)) + ".doc";
IPersistFile compoundDocument = document as IPersistFile;
compoundDocument.Save(fileName, false);
byte[] content = File.ReadAllBytes(fileName);
file = new FileInfo(fileName);
wdApp.Quit();
return content;
}
}
I have an event receiver (WebAdding and WebProvisioned) which works just fine for sites created off the root of the site collection. However, subsites (for example, teamsites created within other areas) do not trigger the code at all.
Does anyone have any idea as to why?
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Text;
namespace TestEventReceiver.EventReceiver1
{
/// <summary>
/// Web Events
/// </summary>
public class EventReceiver1 : SPWebEventReceiver
{
/// <summary>
/// A site is being provisioned.
/// </summary>
public override void WebAdding(SPWebEventProperties properties)
{
base.WebAdding(properties);
using (SPWeb web = properties.Web)
{
StringBuilder output = new StringBuilder();
output.AppendFormat("Web Adding");
output.AppendFormat("<br>Web title: {0}",web.Title);
SendMyEmail(web, "SendItToMe#MyTestAddress.com", "Web Adding", output.ToString());
}
}
/// <summary>
/// A site was provisioned.
/// </summary>
public override void WebProvisioned(SPWebEventProperties properties)
{
base.WebProvisioned(properties);
using (SPWeb web = properties.Web)
{
StringBuilder output = new StringBuilder();
output.AppendFormat("Web Provisioned");
output.AppendFormat("<br>Web title: {0}", web.Title);
SendMyEmail(web, "SendItToMe#MyTestAddress.com", "Web Provisioned", output.ToString());
}
}
private void SendMyEmail(SPWeb Web, String toAddress, String subject, String message)
{
bool appendHtmlTag = false;
bool htmlEncode = true;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.SendEmail(Web, appendHtmlTag, htmlEncode, toAddress, subject, message);
});
}
}
}
Thanks in advance,
Matt
I think you should not be using 'Using' .
The SPWeb object reference you get is from properties.Web which is being passed to the WebAdding method. You will run into issues because of this.
Have a look at how your event receiver is provisioned - it may be the scope needs to be changed to Site rather than Web. Perhaps you could post here so we can see.
On my site I had the same issue. Still figuring out the xml files, but in my Elements.xml file for the Receivers, each receiver had the same sequence number. Once I made them unique within the Elements.xml file, the WebProvisioned event started firing. Don't know if this is the same issue you were having.
This code is showing the WebAdding event and that event is occurring on the parent Web.
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spwebeventreceiver.webadding.aspx
Try to change scope of your receiver (in Elements.xml file add attribute ). Also, make sure that the feature of your Event receiver is activated in you site features in the subsite.