Parameter applicationName must conform to the pattern (Google Report API) - google-admin-sdk

I neet to get the google hangouts meet data by java code and I am trying the google report api
the following is my code
String userKey = "all";
String applicationName = "meet";
String eventName = "call_ended";
Activities result = service.activities().list(userKey, applicationName).setEventName(eventName).setMaxResults(10).execute();
and the response is
Parameter applicationName must conform to the pattern (admin)|(calendar)|(drive)|(login)|(token)
the api I am trying is this, i can get the data in this link by the same parameters
https://developers.google.com/admin-sdk/reports/v1/reference/activities/list
and I also can get the data by the following java code
public static String getGraph() {
String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?eventName=call_ended&maxResults=10&access_token=";
String graph = "";
try {
URL urUserInfo = new URL(PROTECTED_RESOURCE_URL + "access_token");
HttpURLConnection connObtainUserInfo = (HttpURLConnection) urUserInfo.openConnection();
if (connObtainUserInfo.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuilder sbLines = new StringBuilder("");
BufferedReader reader = new BufferedReader(
new InputStreamReader(connObtainUserInfo.getInputStream(), "utf-8"));
String strLine = "";
while ((strLine = reader.readLine()) != null) {
sbLines.append(strLine);
}
graph = sbLines.toString();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return graph;
}
I think it's not a good solution and what i got is a complex string
Any solution please!?

This is a known bug already referenced on Google Issue Tracker; you can check it here.

Just use an old version of library google-api-services-admin-reports, I tested the following version:
com.google.apis:google-api-services-admin-reports:reports_v1-rev83-1.25.0
My gradle file:
apply plugin: 'java'
apply plugin: 'application'
mainClassName = 'SdkAdminQuickStart'
sourceCompatibility = 1.8
targetCompatibility = 1.8
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.api-client:google-api-client:1.23.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
compile 'com.google.apis:google-api-services-admin-reports:reports_v1-rev83-1.25.0'
}

Related

Armeria HTTP Client - how to add query string parameters

I searched for a bit but couldn't find an "Armeria API" to do this elegantly. I'm familiar with Netty so for the time being I'm using QueryStringEncoder. Is there a better way to do this ? Here I have a dynamic Map of params and I need to build the HTTP client programmatically. The Armeria WebClient and RequestHeaders builders provide ways to add headers and path, but not query string parameters.
HttpMethod httpMethod = HttpMethod.valueOf('GET');
String url = 'http://example.com'
String path = '/foo';
if (params != null) {
QueryStringEncoder qse = new QueryStringEncoder(url + path);
params.forEach((k, v) -> {
if (v != null) {
v.forEach(s -> qse.addParam(k, s));
}
});
try {
URI uri = qse.toUri();
path = path + "?" + uri.getRawQuery();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
WebClient webClient = WebClient.builder(url).decorator(new HttpClientLogger()).build();
RequestHeadersBuilder rhb = RequestHeaders.builder(httpMethod, path);
Armeria has QueryParams for building or parsing a query string:
// You don't really need a Map to build a QueryParams.
// See QueryParams.of() or QueryParamsBuilder.add() for more information.
Map<String, String> paramMap = ...;
QueryParams params =
QueryParams.builder()
.add(paramMap)
.build();
WebClient client =
WebClient.builder("http://example.com")
.decorator(...)
.build();
AggregatedHttpResponse res =
client.get("/foo?" + params.toQueryString()).aggregate().join()
You might also find Cookie useful.

Has anyone got a guide on how to upgrade from PowerBi Embeded v2 to v3? Or a tutorial for v3?

This appears to be a nightmare, sure its easy to upgrade the nuget package to 3.11 I think the latest is, but then nothing at all compiles. So you fix the compile errors, and then it doesn't work. I'm getting an error when it tries to create the PowerBI client.
Getting the token and also creating the client appears to be totally different to v2.
This is my code:
public PowerBiConfig GetPowerBiConfig(string reportId)
{
var result = new PowerBiConfig();
try
{
if (!Guid.TryParse(reportId, out var _))
{
result.ErrorMessage = $"Invalid report guid: {reportId}";
return result;
}
var credential = new UserPasswordCredential(_powerBiProMasterUsername, _powerBiProMasterPassword);
var authenticationContext = new AuthenticationContext(AuthorityUrl);
// Taken from https://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously
var authenticationResult = authenticationContext.AcquireTokenAsync(ResourceUrl, dataArchiverSettings.PowerBiApplicationId, credential).GetAwaiter().GetResult();
if (authenticationResult == null)
{
result.ErrorMessage = "Authentication Failed.";
return result;
}
var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
var report = client.Reports.GetReportInGroup(dataArchiverSettings.PowerBiWorkspaceId, reportId);
if (report == null)
{
result.ErrorMessage = $"No report with the ID {reportId} was found in the workspace.";
return result;
}
var datasets = client.Datasets.GetDatasetById(dataArchiverSettings.PowerBiWorkspaceId, report.DatasetId);
result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
GenerateTokenRequest tokenRequest;
if (datasets.IsEffectiveIdentityRequired == true)
{
var username = UserHelper.GetCurrentUser();
var roles = _userService.GetRolesForUser(username);
tokenRequest = new GenerateTokenRequest(accessLevel: "view",
identities: new List<EffectiveIdentity>
{
new EffectiveIdentity(username: username,
roles: new List<string> (roles.Select(x=> x.RoleName)),
datasets: new List<string> {datasets.Id})
});
}
else
{
tokenRequest = new GenerateTokenRequest(accessLevel: "view");
}
var tokenResponse =
client.Reports.GenerateTokenInGroup(dataArchiverSettings.PowerBiWorkspaceId, report.Id,
tokenRequest);
if (tokenResponse == null)
{
result.ErrorMessage = "Failed to generate embed token.";
return result;
}
// Generate Embed Configuration.
result.EmbedToken = tokenResponse;
result.EmbedUrl = report.EmbedUrl;
result.Id = report.Id.ToString();
result.WorkloadResourceName = dataArchiverSettings.PowerBiWorkloadResourceName.Trim();
}
}
catch (HttpOperationException exc)
{
result.ErrorMessage =
$"Status: {exc.Response.StatusCode} ({(int)exc.Response.StatusCode})\r\n" +
$"Response: {exc.Response.Content}\r\n" +
$"RequestId: {exc.Response.Headers["RequestId"].FirstOrDefault()}";
}
catch (Exception exc)
{
result.ErrorMessage = exc.ToString();
}
return result;
}
The closest to "upgrade guide" is the announcement in Power BI blog. It looks like your code is using v2 (e.g. reportId is string, while in v3 it should be Guid).
Here is a brief summary of the changes:
What you should know about v3
Here are the key changes with this version update:
Namespaces renaming:
Microsoft.PowerBI.Api.V2 was changed to Microsoft.PowerBI.Api
Microsoft.PowerBI.Api.Extensions.V2 was changed to Microsoft.PowerBI.Api.Extensions
Microsoft.PowerBI.Api.V1 namespace was removed.
SetAllConnections and SetAllConnectionsInGroup operations are deprecated and marked as obsolete. You should use UpdateDatasources or UpdateParameters APIs instead.
PowerBI artifacts IDs typing was changed* from string to Guid, we recommend to work with Guid when possible.
*Dataset ID is an exception and it’s typing will remain string.
ODataResponse[List[Object]] types was changed to Objects, thus returning an objects collection on responses. For example, a response of ODataResponse[List[Report]] type will now return Reports collection as the return type.
New credentials classes allow easier build of credentialDetails. The new classes include: BasicCredentials, WindowsCredentials, OAuth2Credentials, and more.
Read Configure credentials article to learn more.
New encryption helper classes for easier encryption when creating CredentialDetails.
For example, using AsymmetricKeyEncryptor class with a gateway public key:
GatewayPublicKey publicKey = new GatewayPublicKey
{
Exponent = "...",
Modulus = "..."
};
CredentialsBase credentials = new BasicCredentials("<USER>", "<PASSWORD>");
var credentialsEncryptor = new AsymmetricKeyEncryptor(publicKey);
var credentialDetails = new CredentialDetails(credentials, PrivacyLevel.None, EncryptedConnection.Encrypted, credentialsEncryptor);
Read Configure credentials article to learn more.
Consistency on field names.
For example, reportKey, datasetKey, dashboardKey and tileKey was changed to reportId, datasetId, dashboardId and tileId.
Consistency on operations names.
For example, use GetDataset instead of GetDatasetById. The effected opertation names are imports, datasets, gateways and datasources.
Use enum class instead of string for enumerated types.
For example, In the generateTokenRequest, we recommend to use TokenAccessLevel.View, and not explicitly use “view” as value.
Required fields was marked – some fields was changed to required fields are not nullable anymore.
Examples
Change in Get Reports call if WorkspaceId is a string:
var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);
var reports = await client.Reports.GetReportsInGroupAsync(new Guid( WorkspaceId ) );
Change in response handling if a string is expected:
report = reports.Value.FirstOrDefault(r => r.Id.Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));
report = reports.Value.FirstOrDefault(r => r.Id .ToString() .Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));
Change in Generate token:
var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);
var tokenResponse = await client.Reports.GenerateTokenInGroupAsync( new Guid( WorkspaceId ), report.Id, generateTokenRequestParameters);
Change in Generate token response handling if a string is expected:
m_embedConfig.Id = report.Id;
m_embedConfig.Id = report.Id .ToString() ;
Required fields are not nullable, i.e. Expiration is not nullable and the Value property should be removed:
var minutesToExpiration = EmbedToken.Expiration .Value – DateTime.UtcNow;
var minutesToExpiration = EmbedToken.Expiration – DateTime.UtcNow;
Consistency on operations names, i.e. use GetDataset instead of GetDatasetById:
var datasets = await client.Datasets.GetDataset ById InGroupAsync(WorkspaceId, report.DatasetId);
var datasets = await client.Datasets.GetDatasetInGroupAsync(new Guid(WorkspaceId), report.DatasetId);

SharePoint Office365 Signin issue using CSOM

I am trying to connect and retrieve a List from my Office365 sharepoint portal through CSOM. In document.ready function of jquery I am calling an ajax call.
I am using the below code and its working fine.
[WebMethod]
public static List<myClass> GetDataOnPageLoad()
{
List<myClass> objmyClass = new List<myClass>();
string strSiteCollection = "<Site Url>";
string login = "<username>";
string password = "<password>";
SecureString securePassword = new SecureString();
foreach (char c in password)
securePassword.AppendChar(c);
try
{
ClientContext Clientcontext = new ClientContext(strSiteCollection);
Clientcontext.Credentials = new SharePointOnlineCredentials(login, securePassword);
DataTable dtData = new DataTable();
dtData.Columns.Add("ID", typeof(string));
dtData.Columns.Add("UserEmail", typeof(string));
dtData.Columns.Add("InstalledVersion", typeof(string));
if (Clientcontext != null)
{
List docList = Clientcontext.Web.Lists.GetByTitle("<List Name>");
Microsoft.SharePoint.Client.ListItemCollection items = docList.GetItems(CamlQuery.CreateAllItemsQuery());
Clientcontext.Load(items);
Clientcontext.ExecuteQuery();
foreach (var item in items)
dtData.Rows.Add(item["ID"].ToString(), item["UserEmail"].ToString(), item["InstalledVersion"].ToString());
}
if (dtData != null && dtData.Rows.Count > 0)
{
for (int i = 0; i < dtData.Rows.Count; i++)
{
//binding list
}
}
}
catch (Exception ex)
{
}
return objmyClass;
}
All good till now.
Now I in another project I need this same code.
So I copied it and pasted in the new project. Included the sharepoint client dll. Calling this from ajax. Now when I am running this new project it gives an exception from Clientcontext.ExecuteQuery();
Exception says : The partner returned a bad sign-in name or password error. For more information, see Federation Error-handling Scenarios.
I searched for this error but it didn't helped. I'm running the two projects side by side. The old one is running perfectly but the new one is getting the above said error.
Please help. Thanks & Regards.

In Sitecore 7.5 how to programmatically create media items with language versioning?

I want to be able to create/update media items in code and also use language versioning. Here are more specifics. I have a Product content item. When that item is saved I want to be able to generate a PDF version of that item and save it to the media library. If the PDF version already exists in the media library I need to be able to update it. In addition this is a multi-language site. So if someone saves the French version of the Product content item I need to be able to generate the French version of the PDF and only save/update the French version of the associated PDF in the media library - not touch any of the other language versions of the PDF. I can't seem to figure out how to do this. The code that I have currently does the following: if I save the English version of the Product then it creates and English version of the PDF. But then if I save the French version of the Product, it creates a French version of the PDF and removes the English version of the PDF.
Anyone know how to do this?
public static Item AddMediaItem(byte[] fileBuffer, string fullMediaPath, string fileNameWithExtension, string title, Language language)
{
try
{
var db = Sitecore.Configuration.Factory.GetDatabase("master");
var options = new MediaCreatorOptions();
options.FileBased = false;
options.IncludeExtensionInItemName = false;
options.KeepExisting = false;
options.Versioned = true;
options.Destination = fullMediaPath;
options.Database = db;
options.Language = language;
var creator = new MediaCreator();
var fileStream = new MemoryStream(fileBuffer);
var pdfItem = db.GetItem(fullMediaPath, language);
if (pdfItem != null)
{
var updatedItem = creator.AttachStreamToMediaItem(fileStream, fullMediaPath, fileNameWithExtension,
options);
updatedItem.Editing.BeginEdit();
updatedItem.Fields["Title"].Value = title;
updatedItem.Editing.EndEdit();
return updatedItem;
}
else
{
//Create a new item
var newItem = creator.CreateFromStream(fileStream, fileNameWithExtension, options);
newItem.Editing.BeginEdit();
newItem.Fields["Title"].Value = title;
newItem.Editing.EndEdit();
return newItem;
}
}
catch (Exception ex)
{
return null;
}
}
Thanks to #JanBluemink for pointing me in the right direction. I found the right approach in the following article: Sitecore.Resources.Media.MediaCreator deletes versions of media. I just had to modify the code to use MediaManager instead of MediaCreator when updating.
public static Item AddMediaItem(byte[] fileBuffer, string fullMediaPath, string fileNameWithExtension, string title, Language language)
{
try
{
var db = Sitecore.Configuration.Factory.GetDatabase("master");
var options = new MediaCreatorOptions();
options.FileBased = false;
options.IncludeExtensionInItemName = false;
options.KeepExisting = false;
options.Versioned = true;
options.Destination = fullMediaPath;
options.Database = db;
options.Language = language;
var creator = new MediaCreator();
var fileStream = new MemoryStream(fileBuffer);
var pdfItem = db.GetItem(fullMediaPath, language);
if (pdfItem != null)
{
var mediaItem = new MediaItem(pdfItem);
var media = MediaManager.GetMedia(mediaItem);
media.SetStream(fileStream, "pdf");
pdfItem.Editing.BeginEdit();
pdfItem.Fields["Title"].Value = title;
pdfItem.Editing.EndEdit();
return pdfItem;
}
else
{
//Create a new item
var newItem = creator.CreateFromStream(fileStream, fileNameWithExtension, options);
newItem.Editing.BeginEdit();
newItem.Fields["Title"].Value = title;
newItem.Editing.EndEdit();
return newItem;
}
}
catch (Exception ex)
{
return null;
}
}
I had to add couple of more lines for updating media item stored in File System with versioning.
if (mediaItem.FileBased)
{
string uniqueFilename = FileUtil.GetUniqueFilename(FileUtil.MakePath(Settings.Media.FileFolder, MediaManager.Creator.GetMediaStorageFolder(mediaItem.ID, fileshortname)));
using (new Sitecore.SecurityModel.SecurityDisabler())
{
mediaItem.BeginEdit();
mediaItem.FilePath = uniqueFilename;
mediaItem.EndEdit();
}
}
Media media = MediaManager.GetMedia(mediaItem);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
media.SetStream(stream, FileUtil.GetExtension(fileshortname));
}`

write web serice for android with C#

i want write a web service with C# to call from an android app
in my web service i wrote HElloWorld() method to calles and ConvertDataTableTojSonString to converted data to Json i downloaded converting fonction from internet , my probleim is ConvertDataTableTojSonString function it's return me some thing like
"[{\"ProId\":1,\"ProcName\":\"لبنیات\"},{\"ProId\":2,\"ProcName\":\"لوازم بهداشتی\"},{\"ProId\":3,\"ProcName\":\"لوازم آرایشی\"},{\"ProId\":4,\"ProcName\":\"خشکبار\"},{\"ProId\":5,\"ProcName\":\"نوشیدنی ها\"},{\"ProId\":6,\"ProcName\":\"سبزیجات\"},{\"ProId\":7,\"ProcName\":\"فرآورده های گوشتی\"}]"
the json format that return is not recognizable for my android app i dont need that '/' befor and after items .
any body can help me to find an fanction to change my data table to JSON format for use in android app , thank you : )
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HelloWorldData data = new HelloWorldData();
data.Message = ConvertDataTableTojSonString(db.Select("select * from ProCategory ",CommandType.Text));
Context.Response.Write(js.Serialize(data.Message));
}
public String ConvertDataTableTojSonString(DataTable dataTable)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();
Dictionary<String, Object> row;
foreach (DataRow dr in dataTable.Rows)
{
row = new Dictionary<String, Object>();
foreach (DataColumn col in dataTable.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
tableRows.Add(row);
}
return serializer.Serialize(tableRows);
}