Google AdWords v201206 DotNet Client GetClientReport trouble - c#

Here's what I'm doing:
Selector selector = new Selector();
selector.fields = new string[] {"CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria", "CriteriaDestinationUrl", "Clicks", "Impressions", "Cost"};
Predicate predicate = new Predicate();
predicate.field = "Status";
predicate.#operator = PredicateOperator.IN;
predicate.values = new string[] { "ACTIVE", "PAUSED" };
selector.predicates = new Predicate[] { predicate };
ReportDefinition definition = new ReportDefinition();
definition.reportName = "criteria report";
definition.reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT;
definition.downloadFormat = DownloadFormat.XML;
definition.dateRangeType = ReportDefinitionDateRangeType.YESTERDAY;
definition.selector = selector;
definition.includeZeroImpressions = true;
_handler.RunReport(new AdWordsUser(), definition);
And here's my handler method:
public void RunReport(AdWordsUser user, ReportDefinition definition)
{
if (definition != null)
{
string reportContents = string.Empty;
try
{
ReportUtilities utilities = new ReportUtilities(user);
utilities.ReportVersion = "v201206";
ClientReport report = utilities.GetClientReport(definition);
reportContents = report.Contents.ToString();
}
catch (Exception ex)
{
_errorHandler.AddError(ex);
}
}
}
Where I step through I get this error:
Report contents are invalid. - !!!2|||-1|||[ReportDefinitionError.CUSTOMER_SERVING_TYPE_REPORT_MISMATCH # selector]???
Been searching for hours trying to find a solution. Any hints?

It appears that the issue is indeed needing to pass in the customerClientID.
This document helped me picture what was going on.
I ended up modifying my code like this:
var configOptions = new Dictionary<string,string>();
configOptions.Add("clientCustomerID", customerID.ToString());
_handler.RunReport(new AdWordsUser(configOptions), definition);

Related

How to create k8s deployment using kubernetes-client in c#?

I'm getting Microsoft.Rest.HttpOperationException: 'Operation returned an invalid status code 'BadRequest'' on this line.
var result = client.CreateNamespacedDeployment(deployment, namespace);
Kubernetes-client has a small number of good resources and most of them is written in other language such as java and python. So i'm referring to these documentations.
this is my implementation so far.
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "extensions/v1beta1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "...",
NamespaceProperty = env,
Labels = new Dictionary<string, string>()
{
{ "app", "..." }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "...",
Image = "...",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
var result = client.CreateNamespacedDeployment(deployment, namespace);
I want to know the proper way on how to create kubernetes deployment using kubernetes-client, and also i want to know the cause of this issue.
For the full clarity and future visitors, it's worth to mention, what is exactly behind this bad request error (code: 400) returned from API server, when using your code sample:
"the API version in the data (extensions/v1beta1) does not match the expected API version (apps/v1)"
Solution:
ApiVersion = "extensions/v1beta1" -> ApiVersion = "apps/v1"
Full code sample:
private static void Main(string[] args)
{
var k8SClientConfig = new KubernetesClientConfiguration { Host = "http://127.0.0.1:8080" };
IKubernetes client = new Kubernetes(k8SClientConfig);
ListDeployments(client);
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "apps/v1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "nepomucen",
NamespaceProperty = null,
Labels = new Dictionary<string, string>()
{
{ "app", "nepomucen" }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "nginx",
Image = "nginx:1.7.9",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
Closing this issue (Resolved)
Reference: https://github.com/Azure/autorest/issues/931
Cause of issue: incorrect version of Kubernetes ApiVersion.
Solution: get and replace ApiVersion from kubernetes api.
Can also handle the exception using:
try
{
var result = client.CreateNamespacedDeployment(deployment, namespace);
}
catch (Microsoft.Rest.HttpOperationException httpOperationException)
{
var phase = httpOperationException.Response.ReasonPhrase;
var content = httpOperationException.Response.Content;
}

How to inject a variable into every class or method in c#

I have the following code.
[HttpGet]
public async Task<List<TenantManagementWebApi.Entities.SiteCollection>> Get()
{
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant(tenantAdminUrl, tenant.Email, keyVaultHelper.SecretValue))
{
Tenant tenantOnline = new Tenant(context);
SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
context.Load(siteProps);
context.ExecuteQuery();
List<TenantManagementWebApi.Entities.SiteCollection> sites = new List<TenantManagementWebApi.Entities.SiteCollection>();
foreach (var site in siteProps)
{
if(site.Template.Contains("SITEPAGEPUBLISHING#0") || site.Template.Contains("GROUP#0"))
{
string strTemplate= default(string);
if(site.Template.Contains("SITEPAGEPUBLISHING#0"))
{
strTemplate = "CommunicationSite";
};
if (site.Template.Contains("GROUP#0"))
{
strTemplate = "Modern Team Site";
};
try
{
Guid id = Guid.NewGuid();
Entities.SiteCollection sc = new Entities.SiteCollection()
{
Id = id.ToString(),
Owner = site.Owner,
Template = strTemplate,
Title = site.Title,
Active = false,
Url = site.Url
};
var added = await siteCollectionStore.AddAsync(sc);
sites.Add(sc);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
return sites;
};
}
However the following lines, I am repeating them on every method:
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
I will have lots of API controllers on my project
Is there an easy way (not refactor as a method), to make my code cleaner and inject the variables I need without copying and pasting every single time?

POST data using POSTMAN

so I've been having trouble using the POST method with C# and POSTMAN.
The GET works pretty fine but I'm getting an error on the POST method.
Here's my code:
public SaveProfileResponseDTO SaveProfileQuery(SaveProfileRequestDTO objProfileRequest)
{
SaveProfileResponseDTO objSaveProfileResponse;
try
{
XElement xElement = XElement.Load(Path);
XElement Student = (from u in xElement.Elements("Student")
where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
select (u)).FirstOrDefault();
Student.Element("Name").Value = objProfileRequest.Name;
Student.Element("Gender").Value = objProfileRequest.Gender;
xElement.Save(Path);
objSaveProfileResponse = new SaveProfileResponseDTO()
{
Status = new ResponseCode()
{
Code = StatusCodes.Success,
Message = StatusMessages.Success
}
};
}
catch (Exception ex)
{
objSaveProfileResponse = new SaveProfileResponseDTO()
{
Status = new ResponseCode()
{
Code = StatusCodes.Error,
Message = StatusMessages.Error
}
};
}
return objSaveProfileResponse;
}
This is my Controller:
[Route("Profile")]
[HttpPost]
public HttpResponseMessage Profile(SaveProfileRequestModel objSaveProfileRequestModel)
{
StudentManager = new StudentManager();
SaveProfileRequestDTO objSaveProfileRequestDTO = new SaveProfileRequestDTO()
{
Gender = objSaveProfileRequestModel.Gender,
Name = objSaveProfileRequestModel.Name,
StudentID = objSaveProfileRequestModel.StudentID
};
SaveProfileResponseDTO objSavePofileResponse = StudentManager.SaveProfile(objSaveProfileRequestDTO);
SaveProfileResponseModel objSaveProfileResponseModel = new SaveProfileResponseModel()
{
Status = objSavePofileResponse.Status
};
return Request.CreateResponse(HttpStatusCode.OK, objSavePofileResponse);
}
Any help would be appreciated.
I can also provide the GET method code if you want.
Thank you in advance.
XElement Student = (from u in xElement.Elements("Student")
where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
select (u)).FirstOrDefault();
Student.Element("Name").Value = objProfileRequest.Name;
This last line will cause a NullReferenceException if there is no student in the XML file matching the ID you're passing in.

Export payment in Applications Tab menu of Bill and Adjustments in Acumatica ERP system using webservices api

I need to export all records in Applications Tab Menu of Bill and Adjustments screen as I did in UI like this screenshot below.
I already create codes to provide it using this code below.
try
{
context.CookieContainer = new System.Net.CookieContainer();
context.Timeout = 10000000;
context.Url = url;
LoginResult login = context.Login(username, password);
AP301000Content konten = context.AP301000GetSchema();
//context.AP301000Clear();
konten.DocumentSummary.Type.Commit = false;
konten.DocumentSummary.Type.LinkedCommand = null;
var command = new Command[]
{
new Value { Value = "Bill", LinkedCommand = Konten.DocumentSummary.Type },
new Value { Value = "00123", LinkedCommand = konten.DocumentSummary.ReferenceNbr },
konten.DocumentSummary.Vendor,
konten.Applications.ReferenceNbrDisplayRefNbr,
konten.Applications.DocTypeDisplayDocType
};
var result = context.AP301000Export(command, null, 0, false, true);
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
finally
{
sCon.getLogout(context);
}
After i debug this code I got records only for VendorCD but Reference Nbr and Doc Type didn't exported. Please refer to this screenshot below.
please how to solve this issue.
Thanks
You should use "every" fields:
var command = new Command[]
{
konten.DocumentSummary.ServiceCommands.EveryDocType,
konten.DocumentSummary.ServiceCommands.EveryRefNbr,
konten.DocumentSummary.Vendor,
konten.Applications.ReferenceNbrDisplayRefNbr,
konten.Applications.DocTypeDisplayDocType
};

How to properly dispose objects created for Ldap search using ADODB ADsDSObject provider

I am looking for the best way how to lookup LDAP directory for users by given criteria. At the moment the best performance seems to offer usage of ADsDSObject provider. The code will run in ASP.NET web site.
I would like to confirm how to properly dispose the resources. Here is the code used at the moment. Is the code releasing resources correctly or need to be improved?
public static List<LookupValues> FindBy(LdapSearchCriteria criteria)
{
List<LookupValues> usersMatchingCriteria = new List<LookupValues>();
ADODB.Command adoCommand = new ADODB.Command();
ADODB.Connection adoConnection = new ADODB.Connection();
ADODB.Recordset adoResultSet = new ADODB.Recordset();
adoConnection.ConnectionString = connectionString;
adoConnection.Open();
adoCommand.ActiveConnection = adoConnection;
adoCommand.CommandText = BuildSelectStatmentFrom(criteria);
object dummy = Type.Missing;
try
{
adoResultSet = adoCommand.Execute(out dummy, ref dummy, 0);
if (adoResultSet != null)
{
while (adoResultSet.EOF == false)
{
LookupValues value = new LookupValues();
for (int i = 0; i < adoResultSet.Fields.Count; i++)
{
switch (adoResultSet.Fields[i].Name)
{
case "a-foreignGivenName":
value.FirstName = (adoResultSet.Fields[i].Value).ToString();
break;
case "a-foreignSn":
value.LastName = (adoResultSet.Fields[i].Value).ToString();
break;
}
}
usersMatchingCriteria.Add(value);
adoResultSet.MoveNext();
}
}
}
finally
{
if (adoResultSet != null)
{
adoResultSet.Close();
adoResultSet = null;
}
if (adoConnection != null)
{
adoConnection.Close();
adoConnection = null;
}
}
return usersMatchingCriteria;
}
I found equivalent and even a bit faster to use classes from System.DirectoryServices.Protocols namespace. Equivalent code using .NET classes
public List<LookupValues> FindBy(LdapSearchCriteria criteria)
{
List<LookupValues> usersMatchingCriteria = new List<LookupValues>();
NetworkCredential credentials = new NetworkCredential(connectionDetails.UserName, connectionDetails.Password, connectionDetails.Domain);
LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier(connectionDetails.Server, connectionDetails.Port, false, false);
using (LdapConnection connection = CreateConnection(directoryIdentifier))
{
connection.Bind(credentials);
SearchRequest search = CreateSearchRequest(criteria);
SearchResponse response = connection.SendRequest(search) as SearchResponse;
foreach (SearchResultEntry entry in response.Entries)
{
LookupValues foundUser = GetUserDetailsFrom(entry);
usersMatchingCriteria.Add(foundUser);
}
}
return usersMatchingCriteria;
}

Categories

Resources