Adding a new permission for google document content - c#

I use google docs API(.net, c#) to share my document for other google user (ex: abc#gmail.com). Here's my code:
AclEntry entry = new AclEntry();
entry.Scope = new AclScope();
entry.Scope.Type = AclScope.SCOPE_USER;
entry.Scope.Value = "abc#gmail.com";
entry.Role = new AclRole();
entry.Role = AclRole.ACL_CALENDAR_READ;
Service service = createService(szUserName, szPassword);
string szAclUrl = ((DocumentEntry)contentEntry).AccessControlList;
Uri AclUri = new Uri(szAclUrl);
AtomEntry newAcl = service.Insert(AclUri, entry);
Note: service and contentEntry was created successfully.
But i get an error: (400) Bad Request when execute service.Insert(AclUri, entry) function.
What's i doing wrong? How can i add a new permission using google docs API(.net, c#)?

I think edit
entry.Role = new AclRole();
entry.Role = AclRole.ACL_CALENDAR_READ;
to :
entry.Role = new AclRole("reader"); or entry.Role = new AclRole("writer");

Related

PowerBI embed token with RLS through C# API

We want to provide embedded PowerBI reports to our customers. Initially, we're looking at using one report with a dataset that contains data for all customers. I have created a service principal (app only auth) that has access to a workspace where I've published the report. I've also created a role "business_customer" with a DAX expression ([CustomerNumber] = USERNAME()) on this report.
I'm trying to get an embed token for the report with row level security through the C# API (Microsoft.PowerBI.Api):
var tenantId = "<tenantId>";
var datasetId = "<datasetId>";
var reportId = "<reportId>";
var groupId = "<groupId>";
var applicationPassword = "<applicationPassword>";
var context = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}/");
var clientCredential = new ClientCredential(applicationId, applicationPassword);
var result = context.AcquireTokenAsync("https://analysis.windows.net/powerbi/api",
clientCredential).Result;
var authHeader = new TokenCredentials(result.AccessToken, "Bearer");
var client = new PowerBIClient(new Uri("https://api.powerbi.com"), authHeader);
var groups = client.Groups.GetGroups();
var tokenRequest = new GenerateTokenRequest(TokenAccessLevel.View, datasetId,
new EffectiveIdentity("username", new List<string> { datasetId },
new List<string> { "business_customer" }));
var embedToken = client.Reports.GenerateTokenInGroupAsync(new Guid(groupId), new Guid(reportId),
tokenRequest, cancellationToken: CancellationToken.None).Result;
This fails on the GenerateTokenInGroupsAsync call:
"Invalid request: Creating embed token for accessing dataset <datasetId> shouldn't have effective identity"
I've tried with different usernames and I've tried leaving the username blank, but all of my attempts have failed.
Is there a way of getting an embed token this way or am I on the wrong path? What would be the "correct" way of solving this case?
Thanks in advance

C# Authentication error in google dialogflow API

How do i fix this. I want to set my authentication in my code and not on the machine.
I have checked almost every answer on stackoverflow and github, but none has a good explanation.
How do i pass the credentials to the create intent, it throws this error.
InvalidOperationException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
GoogleCredential credential =
GoogleCredential.FromFile(file);
//var credential = GoogleCredential.FromStream(
// Assembly.GetExecutingAssembly().GetManifestResourceStream("chatbot-a90a9-8f2fb910202d.json"))
// .CreateScoped(IntentsClient.DefaultScopes);
var storage = StorageClient.Create(credential);
var client = IntentsClient.Create();
var text = new Intent.Types.Message.Types.Text();
text.Text_.Add("Message Text");
var message = new Intent.Types.Message()
{
Text = text
};
var trainingPhrasesParts = new List<string>
{
"Book a fligt",
"check cheap flights"
};
var phraseParts = new List<Intent.Types.TrainingPhrase.Types.Part>();
foreach (var part in trainingPhrasesParts)
{
phraseParts.Add(new Intent.Types.TrainingPhrase.Types.Part()
{
Text = part
});
}
var trainingPhrase = new Intent.Types.TrainingPhrase();
trainingPhrase.Parts.AddRange(phraseParts);
var intent = new Intent();
intent.DisplayName = "test";
intent.Messages.Add(message);
intent.TrainingPhrases.Add(trainingPhrase);
var newIntent = client.CreateIntent(
parent: new AgentName("chatbot-a90a9"),
intent: intent
);
SOLVED.
I change
var client = IntentsClient.Create();
To
IntentsClientBuilder builder = new IntentsClientBuilder
{
CredentialsPath = file, // Relative to where the code is executing or absolute path.
// Scopes = IntentsClient.DefaultScopes // Commented out because there's no need to specify this since you are using the defaults and all default values will be automatically used for values not specified in the builder.
};
IntentsClient client = builder.Build();

Microsoft.Web.Deployment: How to take the target offline before syncing the new version?

I have a problem with the Microsoft.Web.Deployment package. someone here could tell me, how i must write / configure the sync-process, that the target will be shutdown, before updating it with the new version?
here is my snippet:
var publishSettings = GetPublishSettings(subscriptionId, resourcegroupName, websiteName);
var sourceBaseOptions = new DeploymentBaseOptions();
var targetBaseOptions = new DeploymentBaseOptions
{
ComputerName = publishSettings.ComputerName,
UserName = publishSettings.Username,
Password = publishSettings.Password,
AuthenticationType = "basic",
TraceLevel = Verbose
};
targetBaseOptions.Trace += TargetBaseOptions_Trace;
var syncOptions = new DeploymentSyncOptions
{
DoNotDelete = false,
WhatIf = false,
UseChecksum = true
};
using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, Path.GetFullPath(websitePath), sourceBaseOptions))
{
var summary = deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, publishSettings.SiteName, targetBaseOptions, syncOptions);
if (summary.Errors > 0) throw new Exception("Website Deployment failed");
if (summary.Errors == 0)
{
Console.WriteLine($"{publishSettings.SiteName}: erfolgreich");
}
}
i could imagine that it is something in the DeploymentSyncOptions
thank you guys
From Microsoft.Web.Deployment, I could not find it provides method or option to manage (stop, restart etc) Azure web site. If you’d like to stop your Azure web site before you do deployment, you could try to use Microsoft.Azure.Management.WebSites that provides website management capabilities for Microsoft Azure.
WebSiteManagementClient websiteManagementClient = new WebSiteManagementClient(cred);
websiteManagementClient.SubscriptionId = "your subscription id here";
websiteManagementClient.Sites.StopSite(AzureResourceGroup, siteName);
and you could use websiteManagementClient.Sites.GetSite(AzureResourceGroup, siteName).State to check the site state.

Is it possible to call Dynamics CRM 2011 late-bound WCF Organization service without the SDK - straight customized binding?

I'm trying to implement a pure WCF scenario where I want to call Dynamics CRM WCF service without relying on the SDK helper classes. Basically, I would like to implement federated authentication against Dynamics CRM 2011 using only native WCF support from the .net framework.
The reason I'm doing this is that I would like to port this scenario later-on to BizTalk.
I've successfully generated proxy classes with SvcUtil, but the part of the policies and security assertions are not compatible with the configuration schema. SvcUtil suggests to build the binding from code instead, which is what I'm trying to do.
The resulting code is here:
private static void CallWcf()
{
OrganizationServiceClient client = null;
try
{
// Login Live.com Issuer Binding
var wsHttpBinding = new WSHttpBinding();
wsHttpBinding.Security = new WSHttpSecurity();
wsHttpBinding.Security.Mode = SecurityMode.Transport;
// Endpoint Binding Elements
var securityElement = new TransportSecurityBindingElement();
securityElement.DefaultAlgorithmSuite = SecurityAlgorithmSuite.TripleDes;
securityElement.IncludeTimestamp = true;
securityElement.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
securityElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
securityElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
var securityTokenParameters = new IssuedSecurityTokenParameters();
securityTokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
securityTokenParameters.ReferenceStyle = SecurityTokenReferenceStyle.Internal;
securityTokenParameters.RequireDerivedKeys = false;
securityTokenParameters.TokenType = null;
securityTokenParameters.KeyType = SecurityKeyType.SymmetricKey;
securityTokenParameters.KeySize = 192;
securityTokenParameters.IssuerAddress = new EndpointAddress("https://login.live.com/extSTS.srf");
securityTokenParameters.IssuerMetadataAddress = null;
securityTokenParameters.DefaultMessageSecurityVersion = null;
securityTokenParameters.IssuerBinding = wsHttpBinding;
securityElement.EndpointSupportingTokenParameters.Signed.Add(securityTokenParameters);
var textMessageEncodingElement = new TextMessageEncodingBindingElement();
textMessageEncodingElement.MaxReadPoolSize = 64;
textMessageEncodingElement.MaxWritePoolSize = 16;
textMessageEncodingElement.MessageVersion = MessageVersion.Default;
textMessageEncodingElement.WriteEncoding = System.Text.Encoding.UTF8;
textMessageEncodingElement.ReaderQuotas.MaxStringContentLength = 8192;
textMessageEncodingElement.ReaderQuotas.MaxArrayLength = 16384;
textMessageEncodingElement.ReaderQuotas.MaxBytesPerRead = 4096;
textMessageEncodingElement.ReaderQuotas.MaxNameTableCharCount = 16384;
var httpsTransportElement = new HttpsTransportBindingElement();
httpsTransportElement.ManualAddressing = false;
httpsTransportElement.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
CustomBinding binding = new CustomBinding();
binding.Elements.Add(securityElement);
binding.Elements.Add(textMessageEncodingElement);
binding.Elements.Add(httpsTransportElement);
client = new OrganizationServiceClient(binding, new EndpointAddress(EndpointUri));
client.ClientCredentials.UserName.UserName = Username;
client.ClientCredentials.UserName.Password = Password;
client.Open();
var columnSet = new schemas.microsoft.com.xrm._2011.Contracts.ColumnSet();
var identifier = new Guid("fbf8240e-2c85-e011-ad55-1cc1de0878eb");
columnSet.Columns = new string[] { "name" };
var entity = client.Retrieve("account", identifier, columnSet);
}
finally
{
if (client != null)
client.Close();
}
}
I'm new to federated authentication and am having a hard time figuring out the potential differences between the many available bindings, so I would be grateful for any help in this regard.
It is probably possible, but hugely complicated. We had a project using Dynamics which moved to ADFS, and required adding lots of extra code around refreshing tokens (code form autorefreshsecuritytoken.cs, deviceidmanager.cs and toolserviceproxies.cs from the SDK) and that was still using the SDK for everything.
Bare in mind you also need windows.identification installed in the OS which is another load of functionality to copy.
In the end you can always just use JustDecompile or similar to see what the SDK is doing.

SearchByKeywordsKbArticleRequest in CRM 4.0 SDK C#

I am using CRM 4.0 SDK to query kbarticles by keyword entered from a textbox on an asp.net webpage. I am using the SearchByKeywordsKbArticleRequest message to do this. Single keywords work fine, but if more than one word is entered a server error occurs. Here is my code:
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "omitted";
CrmService service = new CrmService();
service.Url = "omitted"
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
//RetrieveMultipleResponse allArticlesResponse = getAllArticles();
SearchByKeywordsKbArticleRequest kb = new SearchByKeywordsKbArticleRequest();
String rawSearchText = keyword;
ColumnSet col = new ColumnSet();
col.Attributes = new string[] { "title", "kbarticleid" };
kb.ColumnSet = col;
kb.SearchText = rawSearchText.Trim();
kb.ReturnDynamicEntities = false;
SearchByKeywordsKbArticleResponse response =
(SearchByKeywordsKbArticleResponse)service.Execute(kb);
return response.BusinessEntityCollection;
Any clues?
That method uses the SQL Full-Text indexing service, so you would need to have full-text indexing setup in your database. You should be able to get more information about what's going wrong by enabling tracing in CRM. See:
http://social.microsoft.com/forums/en-us/crmdevelopment/thread/6A4CE7A3-29F3-4E5A-9A89-8E35D6FD05B9

Categories

Resources