My problem is only donwload. Tomorrow I have 2 problem they are download and upload. But I solve upload problem. I can share upload code this questions answer. But now only problem download
P.S =Client application
var authenticator = new ClientLoginAuthenticator("ApplicationName", ServiceNames.Documents, new GDataCredentials("Username", "Password"));
var service = new DocumentsService("ApplicationName");
var entry = new DocumentEntry();
entry.Title.Text = fileName;
entry.MediaSource = new MediaFileSource(filePath, "application/pdf");
var createUploadUrl = new Uri(String.Format(UploadPath, "uploadFileId"));
var link = new AtomLink(createUploadUrl.AbsoluteUri);
link.Rel = ResumableUploader.CreateMediaRelation;
entry.Links.Add(link);
entry.Service = service;
var uploader = new ResumableUploader();
var response = uploader.Insert(authenticator, entry);
return response.ResponseUri.AbsolutePath;
string UploadPath = "https://docs.google.com/feeds/upload/create-session/default/private/full/folder:{0}/contents";
Related
Our code is currently using the old Microsoft.WindowsAzure.Storage libraries for blob storage access in Azure. I am trying to use the new v12 Azure.Storage.Blobs libraries to replace the old ones, however I cannot figure out how to decrypt/encrypt the blobs. The MS docs (https://learn.microsoft.com/en-us/azure/storage/blobs/storage-encrypt-decrypt-blobs-key-vault?tabs=dotnet) helpfully say that the v12 code snippets aren't ready yet, so there are no code examples.
The old code is like this:
var tokenProvider = new AzureServiceTokenProvider();
var cloudResolver = new KeyVaultKeyResolver(
new KeyVaultClient.AuthenticationCallback(_tokenProvider.KeyVaultTokenCallback));
var encryptionThingy = await cloudResolver.ResolveKeyAsync(<Key Vault URL> + "/keys/" + <key name>, CancellationToken.None);
var policy = new BlobEncryptionPolicy(encryptionThingy, cloudResolver);
var options = new BlobRequestOptions() { EncryptionPolicy = policy };
await <ICloudBlob Instance>.DownloadToStreamAsync(<stream>, null, options, null);
So far with the new code I've gotten here:
var azureKeys = new KeyClient(new Uri(<key vault url>), new DefaultAzureCredential());
var encKey = azureKeys.GetKey(<key name>);
ClientSideEncryptionOptions encryptionOptions = new ClientSideEncryptionOptions(ClientSideEncryptionVersion.V1_0)
{
KeyEncryptionKey = (IKeyEncryptionKey)key
};
var bsClient = new BlobServiceClient(cStr, new SpecializedBlobClientOptions() { ClientSideEncryption = encryptionOptions });
var containerClient = new BlobContainerClient(cStr, containerName);
bClient = containerClient.GetBlobClient(<blob name>);
Of course this throws an exception because KeyVaultKey cannot be converted to IKeyEncryptionKey. So my questions are
Can the key be converted to an IKeyEncryptionKey easily, and how?
Can a key resolver be easily retrieved from the Azure SDKs, and how so?
I'm presuming there are ways to do this that don't involve creating our own implementations of the interfaces, but MS in their infinite wisdom didn't see fit to add those few lines to their documentation.
I write a simple demo for you. Just try the C# console app below about azure blob client-encryption with azure KeyVault:
using System;
using Azure.Identity;
using Azure.Security.KeyVault.Keys.Cryptography;
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
namespace BlobEncyptionWithBlob
{
class Program
{
static void Main(string[] args)
{
string keyVaultName = "";
string keyName = "";
string kvUri = "https://" + keyVaultName + ".vault.azure.net/keys/" + keyName;
string storageConnStr = "";
string containerName = "";
string encyptBlob = "encypt.txt";
string localblobPath = #"C:\Users\Administrator\Desktop\123.txt";
string localblobPath2 = #"C:\Users\Administrator\Desktop\123-decode.txt";
//Below is to use recommended OAuth2 approach
//string clientID = "<OAuth Client ID>";
//string clientSecret = "<OAuth Secret>";
//string tenant = "<OAuth Tenant ID>";
//var cred = new ClientSecretCredential(tenant, clientID, clientSecret);
//This is what you use to directly replace older AppAuthentication
var cred = new DefaultAzureCredential();
CryptographyClient cryptoClient = new CryptographyClient(new Uri(kvUri), cred);
KeyResolver keyResolver = new KeyResolver(cred);
ClientSideEncryptionOptions encryptionOptions = new ClientSideEncryptionOptions(ClientSideEncryptionVersion.V1_0)
{
KeyEncryptionKey = cryptoClient,
KeyResolver = keyResolver,
KeyWrapAlgorithm = "RSA-OAEP"
};
BlobClientOptions options = new SpecializedBlobClientOptions() { ClientSideEncryption = encryptionOptions };
var blobClient = new BlobServiceClient(storageConnStr,options).GetBlobContainerClient(containerName).GetBlobClient(encyptBlob);
//upload local blob to container
blobClient.Upload(localblobPath);
//If you want to modify the meta data you have to copy the exisiting meta, think there is a bug in the library that will wipe out the encryptiondata metadata if you write your own meta
var myMeta = new Dictionary<string, string>();
myMeta.Add("comment", "dis file is da shiznit");
foreach (var existingMeta in blobClient.GetProperties().Value.Metadata)
{
if (!myMeta.ContainsKey(existingMeta.Key))
{
myMeta.Add(existingMeta.Key, existingMeta.Value);
}
}
blobClient.SetMetadata(myMeta);
//Download from container to see if it is decided
blobClient.DownloadTo(localblobPath2);
}
}
}
Result:
My local .txt file content:
Upload to blob and its content, it has been encrypted :
Download to local again and its content, it has been decoded:
We have a requirement of sending the jpeg files of a given directory to a Xamarin App.
Following is the code in the Web API.
public HttpResponseMessage DownloadMutipleFiles()
{
name = "DirectoryName";
var content = new MultipartContent();
var ids = new List<int> { 1,2};
var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
content.Add(objectContent);
var file1Content = new StreamContent(new FileStream(#"D:\Photos\" + name+"\\"+ "BL1408037_20191031124058_0.jpg", FileMode.Open));
file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file1Content);
var file2Content = new StreamContent(new FileStream(#"D:\Photos\" + name + "\\" + "BL1408037_20191031124058_1.jpg", FileMode.Open));
file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file2Content);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = content;
return response;
}
Can some one help out with how to read from Xamarin app? Thanks in advance
This is the function I was able to use to send an image as a multi part data file! I just took the byte array given to me by the Xamarin Essentials image picker and passed it into this function:
public async Task SubmitImage(byte[] image, string imageName)
{
using (var client = new HttpClient())
{
string url = $"..."; // URL goes here
var token = Preferences.Get("AccessToken", "");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var stream = new MemoryStream(image);
var content = new StreamContent(stream);
//Without a name we can't actually put the file in IFormFile. We need the equivalent
//"name" value to be "file" (used if you upload via an <input> tag). We could call it
//anything but file is simple
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = imageName,
Name = "file"
};
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(content);
var result = await client.PostAsync(url, multipartContent);
}
}
You can test this using a console application as well and just send over a picture from your computer, instead of doing this through the app
Hello I have created a windows application which uploads image from hdd to google cloud server.
My code was working perfectly but after changing bucket name it is not working.
My both buckets are in the same project and I have given OAuth 2.0 to my project.
even there is no error showing while processing. Please help me.
string bucketForImage = ConfigurationManager.AppSettings["BucketName"];
string projectName = ConfigurationManager.AppSettings["ProjectName"];
string Accountemail = ConfigurationManager.AppSettings["Email"];
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = ConfigurationManager.AppSettings["ClientId"];
clientSecrets.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
string gcpPath = #"D:\mrunal\tst_mrunal.png";
var scopes = new[] { #"https://www.googleapis.com/auth/devstorage.full_control" };
var cts = new CancellationTokenSource();
var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, Accountemail, cts.Token);
var service = new Google.Apis.Storage.v1.StorageService();
var bucketToUpload = bucketForImage;
var newObject = new Google.Apis.Storage.v1.Data.Object()
{
Bucket = bucketToUpload,
Name = "mrunal.png"
};
fileStream = new FileStream(gcpPath, FileMode.Open);
var uploadRequest = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload, fileStream, "image/png");
uploadRequest.OauthToken = userCredential.Token.AccessToken;
await uploadRequest.UploadAsync();
//uploadRequest.UploadAsync();
if (fileStream != null)
{
fileStream.Dispose();
}
Did you try this same code for the older bucket and it worked? It seems to me that there is an issue with line of code, uploadRequest.OauthToken = userCredential.Token.AccessToken. You are calling the Token.AccessToken directly from the userCredentials. These methods should be called from the userCredentials.Result.
I am trying to use the following code to add files to my document library on Sharepoint Office365 using web services.
public void SaveFileToSharePoint(string fileName)
{
try
{
var copyService = new Copy { Url = "https://mydomain.com/_vti_bin/copy.asmx", Credentials = new NetworkCredential("username", "password", "domain") };
var destURL = "https://mydomain.com/Shared%20Documents/" + Path.GetFileName(fileName);
string[] destinationUrl = { destURL };
CopyResult[] cResultArray;
var fFiledInfo = new FieldInformation { DisplayName = "Description", Type = FieldType.Text, Value = Path.GetFileName(fileName) };
FieldInformation[] fFiledInfoArray = {fFiledInfo};
var copyresult = copyService.CopyIntoItems(destURL, destinationUrl, fFiledInfoArray, File.ReadAllBytes(fileName), out cResultArray);
var b = copyresult;
}
catch (Exception ex)
{
}
}
I receive the error "Object Moved". The URL loads the WSDL in the browser though. If there is a better way to upload and get files from SharePoint on Office365 online I would entertain that as well. Thanks.
as the ASMX webservices are deprecated you should check out the "new" rest services of sharepoint. ON MSDN you find information about it
Or you can use the Client object model which would be my favorite way. The following example shows basic usage, to connect to SharePoint online check out the following link
using(ClientContext context = new ClientContext("http://yourURL"))
{
Web web = context.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(#"C:\myfile.txt");
newFile.Url = "file uploaded via client OM.txt";
List docs = web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.ExecuteQuery();
}
Using roqz suggestions above, here is the ultimate solution I came up with to place files in the SharePoint 2013 Office 365 document library and to retrieve them by name:
public void SaveFileToSharePoint(string fileName)
{
using (var context = new ClientContext("https://mydomain.com/"))
{
var passWord = new SecureString();
foreach (var c in "MyPassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("me#mydomain.com", passWord);
var web = context.Web;
var newFile = new FileCreationInformation {Content = File.ReadAllBytes(fileName), Url = Path.GetFileName(fileName)};
var docs = web.Lists.GetByTitle("Documents");
docs.RootFolder.Folders.GetByUrl("Test").Files.Add(newFile);
context.ExecuteQuery();
}
}
public void GetFileFromSharePoint(string fileName, string savePath)
{
using (var context = new ClientContext("https://mydomain.com/"))
{
var passWord = new SecureString();
foreach (var c in "MyPassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("me#mydomain.com", passWord);
var web = context.Web;
var myFile = web.Lists.GetByTitle("Documents").RootFolder.Folders.GetByUrl("Test").Files.GetByUrl(fileName);
context.Load(myFile);
context.ExecuteQuery();
using (var ffl = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, myFile.ServerRelativeUrl))
{
using (var destFile = File.OpenWrite(savePath + fileName))
{
var buffer = new byte[8*1024];
int len;
while ((len = ffl.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
destFile.Write(buffer, 0, len);
}
}
}
}
}
I am using Facebook c# SDK to post status & images on users wall.
I am able to post status but image is not getting posted
Here is my code:
[HttpPost]
public ActionResult PostPhotoOnWall(HttpPostedFileBase file)
{
var client = new FacebookClient();
// Post to user's wall
var postparameters = new Dictionary<string, object>();
postparameters["access_token"] = Session["access_token"].ToString();
postparameters["picture"] = "http://localhost:8691/Content/themes/base/images/12WIPJ50240-2V91.jpg";
var result = client.Post("/me/feed", postparameters);
return View("PostPhoto");
}
On user wall status is posted without image.
Can any one help me .
I Solved It, Bellow is the code
[HttpPost]
public ActionResult PostPhotoOnWall(HttpPostedFileBase file)
{
var filename = Path.GetFileName(file.FileName);
var client = new FacebookClient();
// Post to user's wall
var postparameters = new Dictionary<string, object>();
var media = new FacebookMediaObject
{
FileName = filename,
ContentType = "image/jpeg"
};
var path = Path.Combine(Server.MapPath("~/Content/themes/base/images"),filename);
file.SaveAs(path);
byte[] img = System.IO.File.ReadAllBytes(path);
media.SetValue(img);
postparameters["source"] = media;
postparameters["access_token"] = Session["access_token"].ToString();
// postparameters["picture"] = "http://localhost:8691/Content/themes/base/images/12WIPJ50240-2V91.jpg";
var result = client.Post("/me/photos", postparameters);
return View("PostPhoto");
}