I want to capture all warnings while importing a solution programatically in CRM 2016. In the response object I am not getting any such information - dynamics-crm-2013

var importSolutionRequest = new ImportSolutionRequest
{
ImportJobId = Guid.NewGuid(),
CustomizationFile = fileBytes,
OverwriteUnmanagedCustomizations = true,
PublishWorkflows = true,
SkipProductUpdateDependencies = true,
};
var response = (ImportSolutionResponse)Service.Execute(importSolutionRequest);
I am not getting any useful information in this response object. What changes should I do to get warnings in this object, which occured while importing solution?

You have to query the ImportJob to get the results you want (https://msdn.microsoft.com/en-us/library/gg327847.aspx).
From the SDK (https://msdn.microsoft.com/en-us/library/gg509050.aspx):
// Monitor import success
byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation);
ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest()
{
CustomizationFile = fileBytes,
ImportJobId = Guid.NewGuid()
};
_serviceProxy.Execute(impSolReqWithMonitoring);
Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation);
ImportJob job = (ImportJob)_serviceProxy.Retrieve(ImportJob.EntityLogicalName, impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" }));
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(job.Data);
String ImportedSolutionName = doc.SelectSingleNode("//solutionManifest/UniqueName").InnerText;
String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/#result").Value;
Console.WriteLine("Report from the ImportJob data");
Console.WriteLine("Solution Unique name: {0}", ImportedSolutionName);
Console.WriteLine("Solution Import Result: {0}", SolutionImportResult);
Console.WriteLine("");
// This code displays the results for Global Option sets installed as part of a solution.
System.Xml.XmlNodeList optionSets = doc.SelectNodes("//optionSets/optionSet");
foreach (System.Xml.XmlNode node in optionSets)
{
string OptionSetName = node.Attributes["LocalizedName"].Value;
string result = node.FirstChild.Attributes["result"].Value;
if (result == "success")
{
Console.WriteLine("{0} result: {1}",OptionSetName, result);
}
else
{
string errorCode = node.FirstChild.Attributes["errorcode"].Value;
string errorText = node.FirstChild.Attributes["errortext"].Value;
Console.WriteLine("{0} result: {1} Code: {2} Description: {3}",OptionSetName, result, errorCode, errorText);
}
}

Related

FileStore.CreateFile returns ntStatus = 3221226071

I am using this SMBLibrary. Related to this closed issue, I sometimes get ntStatus = 3221226071 when I attempt to FileStore.CreateFile(). What does "DFS pathname not on local server" mean? If I keep trying, eventually it will work. Leads me to believe some resources are being held or not released/disconnected. Any ideas here?
"SMBLibrary" Version="1.4.8"
Here is my code:
[Fact]
public void Unit_Test_To_Test_SMBLibrary()
{
var server = "myRemoteServer";
var shareName = "shareddir";
var windowsPath = "Data\\Folder1\\unittest";
var random = new System.Random();
var filename = "createdBySmbclient" + random.Next(1, 10).ToString() + ".txt";
var domain = "my.domain";
var username = "myUser";
var password = "--put secret password here--";
var client = new SMB2Client();
bool isConnected = client.Connect(server, SMBTransportType.DirectTCPTransport);
if(isConnected)
{
try
{
NTStatus ntStatus = client.Login(domain, username, password);
if (ntStatus == NTStatus.STATUS_SUCCESS)
{
ISMBFileStore fileStore = client.TreeConnect(shareName, out ntStatus);
object fileHandle;
FileStatus fileStatus;
var windowsPathWithFile = Path.Combine(windowsPath, filename);
// 1st, create empty file.
ntStatus = fileStore.CreateFile(
out fileHandle,
out fileStatus,
windowsPathWithFile,
AccessMask.GENERIC_READ | AccessMask.GENERIC_WRITE,
0,
ShareAccess.None,
CreateDisposition.FILE_OPEN_IF,
CreateOptions.FILE_NON_DIRECTORY_FILE,
null
);
// create file contents and get the bytes
byte[] filebytes = Encoding.ASCII.GetBytes("hello world");
// 2nd, write data to the newly created file
if (ntStatus == NTStatus.STATUS_SUCCESS && fileStatus == FileStatus.FILE_CREATED)
{
int numberOfBytesWritten;
ntStatus = fileStore.WriteFile(out numberOfBytesWritten, fileHandle, 0, filebytes);
fileStore.FlushFileBuffers(fileHandle);
fileStore.CloseFile(fileHandle);
fileStore.Disconnect();
_logger.LogDebug(string.Format("Export successful: {0}", windowsPathWithFile));
}
else
{
throw new Exception(string.Format("ERROR: ntStatus = {0}, fileStatus = {1}", ntStatus, fileStatus));
}
}
}
finally
{
client.Logoff();
client.Disconnect();
}
}
}

Getting "EIdHTTPProtocolException with message 'HTTP/1.1 400 BAD REQUEST'" exception

I am working on a VCL application and I have to integrate Twilio using its REST API:
https://www.twilio.com/docs/usage/your-request-to-twilio
Here is my code:
pair<bool, String> SMSTwilio::SendMessage(TComponent* Owner,
String ToNumber, String FromNumber, String Message)
{
if(Message.Length() > MESSAGE_LIMIT) {
ShowMessage("Message must have " + IntToStr(MESSAGE_LIMIT) +
" or fewer characters. Cannot send message with " +
IntToStr(Message.Length()) + "characters.");
}
AccountSID = "AC2d48*****************0deb52";
AuthToken = "9e28ec***************c0126e";
Message = "Hi";
FromNumber = "+1740****95";
ToNumber = "+9*****791";
String URI = "https://api.twilio.com/2010-04-01/Accounts/"
+ AccountSID +
"/Messages";
TStringList* params = new TStringList();
params->Add("From=" + FromNumber);
params->Add("To=" + ToNumber);
params->Add("Body=" + Message);
TIdHTTP* HTTP = new TIdHTTP(Owner);
HTTP->Request->Connection = "Keep-Alive";
HTTP->Request->ContentType = "application/x-www-form-urlencoded";
HTTP->Request->BasicAuthentication = true;
HTTP->Request->Username = AccountSID;
HTTP->Request->Password = AuthToken;
TIdSSLIOHandlerSocketOpenSSL* Handler = new TIdSSLIOHandlerSocketOpenSSL(Owner);
Handler->SSLOptions->Method = sslvTLSv1;
HTTP->IOHandler = Handler;
bool isSuccess = false;
String Result = "";
__try {
try {
HTTP->ReadTimeout = 5000;
HTTP->ConnectTimeout = 5000;
Result = HTTP->Post(URI, params);
isSuccess = true;
} catch(Exception &e) {
isSuccess = false;
Result = e.Message;
}
}
__finally {
delete HTTP;
delete params;
}
return make_pair(isSuccess, Result);
}
I am getting an EIdHTTPProtocolException with message "HTTP/1.1 400 BAD REQUEST" thrown by Result = HTTP->Post(URI, params);.
You are posting to the wrong URL.
You are posting to .../Messages but you need to post to .../Messages.json instead (notice the .json at the end), per Twilio's Message Resource documentation:
Create a Message resource
POST https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages.json
To send a new outgoing message, make an HTTP POST to this Messages list resource URI.
Also, although not errors per-say, there are some other issues with your code:
your Owner parameter is unnecessary. Since you are creating and destroying your TIdHTTP object in the same function, there is no need to assign an Owner to it at all. And it would be more useful to assign that TIdHTTP object as the Owner for the TIdSSLIOHandlerSocketOpenSSL object, instead of some unknown external Owner.
you are not returning an error to the caller if the Message is too long to send.
you are not adequately protecting your objects from leaks if something bad happens (why not use C++ smart pointers instead of try..finally?).
your catch() should be catching the Exception object by const reference.
you don't need Request->Connection = "Keep-Alive" since you are closing the connection after the Post() is finished, you are not actually using a keep-alive.
you should be using the SSLOptions->SSLVersions property instead of the SSLOptions->Method property. That will then allow you to enable sslvTLSv1_1 and sslvTLSv1_2, since many servers are phasing out TLS 1.0 nowadays, so you should prepare for that sooner rather than later.
With that said, try something more like this:
#include <utility>
#include <memory>
std::pair<bool, String> SMSTwilio::SendMessage(
String ToNumber, String FromNumber, String Message)
{
if (Message.Length() > MESSAGE_LIMIT) {
String msg = Format(_D("Message must have %d or fewer characters. Cannot send message with %d characters."), ARRAYOFCONST(( MESSAGE_LIMIT, Message.Length() )) );
//ShowMessage(msg);
return std::make_pair(false, msg);
}
String AccountSID = _D("AC2d48*****************0deb52");
String AuthToken = _D("9e28ec***************c0126e");
//Message = _D("Hi");
//FromNumber = _D("+1740****95");
//ToNumber = _D("+9*****791");
String URI = Format(_D("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"), ARRAYOFCONST(( AccountSID )) );
std::unique_ptr<TStringList> params(new TStringList); // or std::auto_ptr prior to C++11
params->Add(_D("From=") + FromNumber);
params->Add(_D("To=") + ToNumber);
params->Add(_D("Body=") + Message);
std::unique_ptr<TIdHTTP> HTTP(new TIdHTTP(nullptr)); // or std::auto_ptr prior to C++11
HTTP->ReadTimeout = 5000;
HTTP->ConnectTimeout = 5000;
//HTTP->Request->Connection = _D("Keep-Alive");
HTTP->Request->ContentType = _D("application/x-www-form-urlencoded");
HTTP->Request->BasicAuthentication = true;
HTTP->Request->Username = AccountSID;
HTTP->Request->Password = AuthToken;
TIdSSLIOHandlerSocketOpenSSL* Handler = new TIdSSLIOHandlerSocketOpenSSL(HTTP.get());
Handler->SSLOptions->SSLVersions = TIdSSLVersions() << sslvTLSv1 << sslvTLSv1_1 << sslvTLSv1_2;
HTTP->IOHandler = Handler;
bool isSuccess = false;
String Result;
try {
Result = HTTP->Post(URI, params);
isSuccess = true;
}
catch (const Exception &e) {
isSuccess = false;
Result = e.Message;
}
return std::make_pair(isSuccess, Result);
}

Try catch input invalid type integer input

I use swagger, now i want to catch input data.
My code:
#GET
#Path("/getById/{wId}")
#Produces({ MediaType.APPLICATION_JSON })
#Consumes({ MediaType.APPLICATION_JSON })
#ApiOperation(value = "Get warehouse by id", notes = "Get warehouse by id", response = Warehouse.class)
#ApiResponses(value = {
#ApiResponse(code = 400, message = "Invalid Id supplied"),
#ApiResponse(code = 404, message = "Warehouse not found") })
public Response getWarehouseById(
#ApiParam(value = "ID of warehouse to fetch", required = true) #PathParam("wId") int wId)
throws WebApplicationException {
Warehouse warehouse = warehouseService.findWarehouseByID(wId);
if(warehouse != null && warehouse.getWareHouseID() != 0){
String[] errorMessage = new String[]{};
String[] message = new String[]{Constants.SUCCESS};
Object[] rows = new Object[]{warehouse};
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.SUCCESS,errorMessage,rows,message)).build();
}else{
String[] errorMessage = new String[]{Constants.NOT_FOUND};
String[] message = new String[]{};
Object[] rows = new Object[]{};
return Response.status(ApiResponseMessage.NOT_FOUND).entity(new ApiResponseMessage(ApiResponseMessage.NOT_FOUND,errorMessage, rows, message)).build();
}
}
If i input string value to int wId, i'll get result
Can not construct instance of java.lang.Integer from String value 'int': not a valid Integer value
Could you tell me how to fix? Tks all...

ArrayList Double

Im getting this error
java.lang.NumberFormatException: Invalid double: "-20.528899,"
im using a webservice to get latitude and longitude from bd, and show in a map.
I am not able to pass the latitude and longitude values to list
i am saving lat and long at the same column in db, so this field should be "lat, long" eg "-20.528899, -47.438933" and i need to parse this in the list...can i do this?
public List<Localizacoes> buscarLocalizacoes(){
List<Localizacoes> lista = new ArrayList<Localizacoes>();
SoapObject buscarLocalizacoes = new SoapObject(NAMESPACE, BUSCAR);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(buscarLocalizacoes);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("uri:" + BUSCAR, envelope);
Vector<SoapObject> resposta = (Vector<SoapObject>) envelope.getResponse();
for (SoapObject soapObject : resposta){
Localizacoes loc = new Localizacoes();
loc.setId(Integer.parseInt(soapObject.getProperty("id").toString()));
loc.setNome(soapObject.getProperty("nome").toString());
loc.setDescricao(soapObject.getProperty("descricao").toString());
loc.setPosicao(soapObject.getProperty("posicao").toString()); // error in this line
lista.add(loc);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return lista;
}
activity
dao = new LocalizacoesDAO(context);
List<Localizacoes> lista = dao.buscarLocalizacoes();
Log.d("Teste Buscar", lista.toString());
public void setPosicao(LatLng poLatLng) {
this.poLatLng = poLatLng;
this.posicao = String.valueOf(poLatLng.latitude) + " " + String.valueOf(poLatLng.longitude);
}
public void setPosicao(String posicao) {
this.posicao = posicao;
String[] pos = posicao.split(" ");
this.poLatLng = new LatLng(Double.valueOf(pos[0]), Double.valueOf(pos[1]));
}
can anyone help me pls?
Change the following line in your setPosicao(String) method
String[] pos = posicao.split(" ");
INTO
String[] pos = posicao.split(", ");
(Since you have a ',' and a ' ' in the string)

Why does this controller double the inserts when I try to archive the results of the Bing Search API?

I'm trying to archive my search results for a term by
Using the Bing API in an async controller
Inserting them into database using Entity Framework
using the Bing API and insert them into a database using entity framework. For whatever reason it is returning 50 results, but then it enters 100 results into the database.
My Controller Code:
public class DHWebServicesController : AsyncController
{
//
// GET: /WebService/
private DHContext context = new DHContext();
[HttpPost]
public void RunReportSetAsync(int id)
{
int iTotalCount = 1;
AsyncManager.OutstandingOperations.Increment(iTotalCount);
if (!context.DHSearchResults.Any(xx => xx.CityMarketComboRunID == id))
{
string strBingSearchUri = #ConfigurationManager.AppSettings["BingSearchURI"];
string strBingAccountKey = #ConfigurationManager.AppSettings["BingAccountKey"];
string strBingUserAccountKey = #ConfigurationManager.AppSettings["BingUserAccountKey"];
CityMarketComboRun cityMarketComboRun = context.CityMarketComboRuns.Include(xx => xx.CityMarketCombo).Include(xx => xx.CityMarketCombo.City).First(xx => xx.CityMarketComboRunID == id);
var bingContainer = new Bing.BingSearchContainer(new Uri(strBingSearchUri));
bingContainer.Credentials = new NetworkCredential(strBingUserAccountKey, strBingAccountKey);
// now we can build the query
Keyword keyword = context.Keywords.First();
var bingWebQuery = bingContainer.Web(keyword.Name, "en-US", "Moderate", cityMarketComboRun.CityMarketCombo.City.Latitude, cityMarketComboRun.CityMarketCombo.City.Longitude, null, null, null);
var bingWebResults = bingWebQuery.Execute();
context.Configuration.AutoDetectChangesEnabled = false;
int i = 1;
DHSearchResult dhSearchResult = new DHSearchResult();
List<DHSearchResult> lst = new List<DHSearchResult>();
var webResults = bingWebResults.ToList();
foreach (var result in webResults)
{
dhSearchResult = new DHSearchResult();
dhSearchResult.BingID = result.ID;
dhSearchResult.CityMarketComboRunID = id;
dhSearchResult.Description = result.Description;
dhSearchResult.DisplayUrl = result.DisplayUrl;
dhSearchResult.KeywordID = keyword.KeywordID;
dhSearchResult.Created = DateTime.Now;
dhSearchResult.Modified = DateTime.Now;
dhSearchResult.Title = result.Title;
dhSearchResult.Url = result.Url;
dhSearchResult.Ordinal = i;
lst.Add(dhSearchResult);
i++;
}
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
context.SaveChanges();
}
AsyncManager.Parameters["message"] = "The total number of results was "+lst.Count+". And there are " + context.DHSearchResults.Count().ToString();
}
else
{
AsyncManager.Parameters["message"] = "You have already run this report";
}
AsyncManager.OutstandingOperations.Decrement(iTotalCount);
}
public string RunReportSetCompleted(string message)
{
string str = message;
return str;
}
}
Here is how I am calling it from my asp.net mvc 4 page.
#Ajax.ActionLink("Run Report", "GatherKeywordsFromBing", "DHWebServices",
new { id=item.CityMarketComboRunID},
new AjaxOptions { OnSuccess = "ShowNotifier();", UpdateTargetId = "TopNotifierMessage", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = strCityMarketComboProgressID, LoadingElementDuration = 1000 },
new { #class = "ViewLink" })
<span class="ProgressIndicator" id="#strCityMarketComboProgressID"><img src="#Url.Content("~/Content/img/SmallBall.gif")" alt="loading" /></span>
For whatever reason all of
Try saving only once:
foreach (DHSearchResult c in lst)
{
context.DHSearchResults.Add(c);
}
context.SaveChanges();
Also there's nothing asynchronous in your code, so there's no point of using asynchronous controller. Not only that it won't improve anything but it might make things worse.