Object reference not set to an instance of an object while connecting Microsoft Dynamics GP 2018 with eConnect 18 using .net Framework 4.6.1 - asp.net-core

I have tried many solutions for this simple error but I couldn't find bug what actually cause it.
Here is some code for reference.
GPController
[HttpPost("testConnection")]
public bool TestConnection()
{
try
{
var data = eConn.GetEntity();
if (data)
{
return true;
}
return false;
}
catch(Exception ex)
{
throw ex;
}
}
eConn.cs
public static bool GetEntity()
{
try
{
string connString = DataAccess.ConnectionString;
eConnectOut myRequest = new eConnectOut();
myRequest.DOCTYPE = "Customer";
myRequest.OUTPUTTYPE = 1;
myRequest.INDEX1FROM = "Customer001";
myRequest.INDEX1TO = "Customer001";
myRequest.FORLIST = 1;
// Create the eConnect requester XML document object
RQeConnectOutType[] eConnectOutType =
new RQeConnectOutType[1] { new RQeConnectOutType()};
eConnectOutType[0].eConnectOut = myRequest;
eConnectType eConnectDoc = new eConnectType();
eConnectDoc.RQeConnectOutType = eConnectOutType;
// Serialize the object to produce an XML document
MemoryStream memStream = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
serializer.Serialize(memStream, eConnectDoc);
memStream.Position = 0;
XmlDocument myDoc = new XmlDocument();
myDoc.Load(memStream);
eConnectMethods eConnCall = new eConnectMethods();
eConnCall.RequireProxyService = false;
// Retrieve the specified customer document
string myCustomer = eConnCall.GetEntity(connString, myDoc.OuterXml);
return true;
}
catch(Exception ex)
{
throw ex;
}
}
In eConn.cs calling GetEntity method I am getting this error.
{System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Dynamics.GP.eConnect.EventLogHelper.AddExceptionHeader(String action, Object[] inputParameters, StringBuilder errorString)
at Microsoft.Dynamics.GP.eConnect.EventLogHelper.CreateEventLogEntry(Exception exception, String action, Object[] inputParameters)
at Microsoft.Dynamics.GP.eConnect.eConnectMethods.GetEntity(String connectionString, String sXML)
at AP.GPServices.Helper.eConn.GetEntity() in D:\projects\APSystem SM\Source Code\AP.GPServices\Helper\eConn.cs:line 46}
I am referring this Programmer guide.
http://www.mypurelogic.com/files/purelogic/files/manuals/econnectprogrammersguide.pdf

Related

RallyApi in Java - Trying to return project hierarchy for a feature

Given a Feature result set passed into this function, I am trying to traverse up the project hierarchy up to the subscription. I can't I get a null pointer on the projResponse =... No even sure of the approach for this.
private static void getProjHierarchyForFeature(RallyRestApi restApi, QueryResponse featureSet,
Time2Market time2market, Integer featureInSet) {
String tempHierarchy = "";
JsonArray tempFeatures = featureSet.getResults();
//time2market.setProjectName(projectName);
try {
JsonObject obj1 = tempFeatures.get(featureInSet).getAsJsonObject();
JsonObject proj = obj1.get("Project").getAsJsonObject();
String url = proj.get("_ref").getAsString();
QueryRequest projQuery = new QueryRequest(url);
projQuery.setFetch(new Fetch("_ref", "_refObjectUUID", "_refObjectName"));
QueryResponse projResponse = restApi.query(projQuery);
if (projResponse.wasSuccessful()) {
JsonArray tempProj = projResponse.getResults();
// Here we have the project object, now process Parents...
Boolean moreParents = true;
while (moreParents) {
QueryRequest parentQuery = new QueryRequest(url);
//projQuery.setFetch(new Fetch("_ref", "_refObjectUUID", "_refObjectName"));
QueryResponse parentResponse = restApi.query(parentQuery);
if (parentResponse.wasSuccessful()) {
System.out.println ("proj Response... " + parentResponse.toString());
JsonArray projParent = parentResponse.getResults();
tempHierarchy.concat(projParent.get(0).getAsString());
JsonArray tempParent = parentResponse.getResults();
proj = tempParent.getAsJsonObject();
} else {
moreParents = false;
}
}
} else {
System.err.println("The following errors occurred: ");
for (String err : projResponse.getErrors()) {
System.err.println("\t" + err);
}
throw new java.lang.Error("Rally API Call Error Occurred");
}
} catch (Exception e) {
e.printStackTrace();
}
}
You probably want to use a GetRequest instead of a QueryRequest since you're just reading a single object. Also, include Parent in your fetch. Then you should have the data to be able to determine whether there is a parent and to continue looping or not.

autodesk design automation

FATAL ERROR: Unhandled Access Violation Reading 0x0008 Exception at 1d8257a5h
Failed missing output
I finally made it work with HostApplicationServices.getRemoteFile in local AutoCAD, then migrated it to Design Automation. It is also working now. The below is the command of .NET plugin.
To have a simple test, I hard-coded the URL in the plugin. you could replace the URL with the workflow at your side (either by an json file, or input argument of Design Automation)
My demo ReadDWG the entities from the remote URL file, then wblock the entities to current drawing (HostDWG), finally save current drawing.
Hope it helps to address the problem at your side.
.NET command
namespace PackageNetPlugin
{
class DumpDwgHostApp: HostApplicationServices
{
public override string FindFile(string fileName,
Database database,
FindFileHint hint)
{
throw new NotImplementedException();
}
public override string GetRemoteFile(Uri url,
bool ignoreCache)
{
//return base.GetRemoteFile(url, ignoreCache);
Database db =
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument.Database;
string localPath = string.Empty;
if (ignoreCache)
{
localPath =
Autodesk.AutoCAD.ApplicationServices.Application.
GetSystemVariable("STARTINFOLDER") as string;
string filename =
System.IO.Path.GetFileName(url.LocalPath);
localPath += filename;
using (var client = new WebClient())
{
client.DownloadFile(url, localPath);
}
}
return localPath;
}
public override bool IsUrl(string filePath)
{
Uri uriResult;
bool result = Uri.TryCreate(filePath,
UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp ||
uriResult.Scheme == Uri.UriSchemeHttps);
return result;
}
}
public class Class1
{
[CommandMethod("MyPluginCommand")]
public void MyPluginCommand()
{
try {
string drawingPath =
#"https://s3-us-west-2.amazonaws.com/xiaodong-test-da/remoteurl.dwg";
DumpDwgHostApp oDDA = new DumpDwgHostApp();
string localFileStr = "";
if (oDDA.IsUrl(drawingPath)){
localFileStr = oDDA.GetRemoteFile(
new Uri(drawingPath), true);
}
if(!string.IsNullOrEmpty(localFileStr))
{
//source drawing from drawingPath
Database source_db = new Database(false, true);
source_db.ReadDwgFile(localFileStr,
FileOpenMode.OpenTryForReadShare, false, null);
ObjectIdCollection sourceIds =
new ObjectIdCollection();
using (Transaction tr =
source_db.TransactionManager.StartTransaction())
{
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
SymbolUtilityServices.GetBlockModelSpaceId(source_db),
OpenMode.ForRead);
foreach (ObjectId id in btr)
{
sourceIds.Add(id);
}
tr.Commit();
}
//current drawing (main drawing working with workitem)
Document current_doc =
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument;
Database current_db = current_doc.Database;
Editor ed = current_doc.Editor;
//copy the objects in source db to current db
using (Transaction tr =
current_doc.TransactionManager.StartTransaction())
{
IdMapping mapping = new IdMapping();
source_db.WblockCloneObjects(sourceIds,
SymbolUtilityServices.GetBlockModelSpaceId(current_db),
mapping, DuplicateRecordCloning.Replace, false);
tr.Commit();
}
}
}
catch(Autodesk.AutoCAD.Runtime.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString());
}
}
}
}

Stream PDF Byte array from WebAPI to browser

I'm working in C#.net in a WebAPI...
I have...
WebAPI Controller...
public class GetSMBController : ApiController
{
public HttpResponseMessage GET(int AgencyID, string UserName)
{
var Pdfs = new HttpResponseMessage();
Pdfs = Utilities.Reporting.CreateStandardMapBooklet(AgencyID,UserName);
return Pdfs;
}
}
That calls a method...
public static HttpResponseMessage CreateStandardMapBooklet(int AgencyID, string userName)
{
string baseDataPath = #"\\dvfmweb4\\arcgisserver\basedata\";
string tempDataPath = #"\\dvfmweb4\arcgisserver\tempGrowerData\";
string unitTestSession = "UnitTestSession";
int ShadeType = 1;
bool isInImagery = false;
double MaxSceneSize = 1.5;
bool ScaleBar = true;
int MapSettingID = 0;
bool OverallPage = false;
bool OverallImagery = false;
bool IsRecordKeepingSheet = false;
int RecordKeepingSheetID = 0;
int TemplateID = 1480;
RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport _Pdfs = new RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport(
baseDataPath,
tempDataPath,
unitTestSession,
AgencyID,
ShadeType,
isInImagery,
MaxSceneSize,
ScaleBar,
MapSettingID,
TemplateID,
OverallPage,
OverallImagery,
false,
RecordKeepingSheetID,
userName,
true);
PDF testPDF = new PDF();
byte[] test = null;
try
{
List<RCIS.Mapping.MapDomain.Layout.CreatePdfResponse> pdf = _Pdfs.CreateReports();
foreach (var item in pdf)
{
//PDFInfo info = new PDFInfo();
//info.PdfBytes = item.PdfBytes;
testPDF.Report = item.PdfBytes;
test = item.PdfBytes;
}
}
catch(Exception e)
{
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(test)
};
response.Content = new ByteArrayContent(test);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = String.Format(AgencyID + userName + DateTime.Now.ToString("MMMddyyyy_HHmmss"))
};
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = new TimeSpan(0, 0, 60) // Cache for 30s so IE8 can open the PDF
};
return response;
}
Sorry for some of the commented out stuff and goofy variable names...I'm just trying to see if this is a viable thing.
the test object and HttpResponse message Content ARE populated but
I'm receiving this error when I call this from a browser...
This XML file does not appear to have any style information associated with it. The document tree is shown below.
An error has occurred.
Value cannot be null. Parameter name: content
System.ArgumentNullException
at System.Net.Http.ByteArrayContent..ctor(Byte[] content) at MappingServicesWebAPI.Utilities.Reporting.CreateStandardMapBooklet(Int32 AgencyID, String userName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Utilities\Reporting.cs:line 92 at MappingServicesWebAPI.Controllers.GetSMBController.GET(Int32 AgencyID, String UserName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Controllers\MappingController.cs:line 143 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.b__c(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.b__4() at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)

Converting a JSON object to an equivalent in JAVA

I am massively stuck with converting a PHP server request into an equivalent Java Request. This is the code that contains the JSON object that I need to replicate in JAVA and send from an Android device:
$(".unableprocess").click(function() {
if (!confirm("Confirm not able to process...!")) {
return false;
} else {
var item_id = $(this).attr('data-id');
var table_id = $(this).attr('table-id');
var data = {
BookOrders: {
item_id: item_id,
table_id: table_id
}
};
$.ajax({
url: //MY URL HERE ,
type: "POST",
data: data,
success: function(evt, responseText) {
location.reload();
}
});
}
});
And here is my Java class that attempts to perform the same functionality. The class extends AsyncTask and all network interactions occur in the doInBackground() method. Here is my code:
#Override
protected Boolean doInBackground(String... arg0) {
try{
HashMap<String, String> hashMap = new HashMap<String,String>();
JSONObject jsonObject = new JSONObject();
int statusCode;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(tableMateCannotProcessURL);
// JSON object creation begins here:
jsonObject.accumulate("item_id",this.itemId);
jsonObject.accumulate("table_id",this.tableId);
JSONObject jObject = new JSONObject();
jObject.accumulate("BookOrders", jsonObject);
// JSON object ends here
Log.v("ATOMIC BLAST",jObject.toString());
String json = jObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
Integer statusCodeInt = new Integer(statusCode);
Log.v("HTTPResponse",statusCodeInt.toString());
String result= "";
StringBuilder builder = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}
else {
Log.e("==>", "Failed to download file");
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
The JSON object that I created looks like this after printing it out to the console:
{"BookOrders":{"table_id":"1","item_id":"2"}}
After POSTing this object to the server I do not get the expected response. What is the proper method for converting the JSON object into an equivalent JSON object in JAVA? Any guidance, direction or a solution would be most appreciated.
Update php to version 5.4 helped me.
In this version json_encode($x, JSON_PRETTY_PRINT) works just as needed.
Your JSON seems to be correct but it's an Object in an Object.
JSONObject json = new JSONObject(yourdata);
JSONObject jsonTable = new JSONObject(json.getString("BookOrders"));
Log.d("JsonDebug", "json:" + jsonTable.toString());
If you are not sure if you have a JSONObject or an Array you can validate it by using
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array

SerializeObject and DeserializeObject

I use this following code but it gives error
Service1.svc.cs
public static byte[] SerializeObject<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
dcs.WriteObject(writer, obj); writer.Flush();
return ms.ToArray();
}
}
}
client code Windows phone
public static T DeserializeObject<T>(byte[] xml)
{
using (MemoryStream memoryStream = new MemoryStream(xml))
{
using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(memoryStream, XmlDictionaryReaderQuotas.Max))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
return (T)dcs.ReadObject(reader);
}
}
}
I call this DeserializeObject from below code
void svc_Get_Conn(object send, GetConnCompletedEventArgs e)
{
CookieContainer con =DeserializeObject<CookieContainer>(e.Result);
}
This gives following error
Message = "Type 'System.Net.PathList' with data contract name 'PathList:http://schemas.datacontract.org/2004/07/System.Net' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using...
How to solve this?
CookieContainer can't be serializable. Check this workaround
cheers