ShopifySharp icon indicating copy to clipboard operation
ShopifySharp copied to clipboard

Object reference not set to an instance of an object. Creating Draft Order

Open TIMGATVOLER opened this issue 4 years ago • 20 comments

I am getting an Object reference not set to an instance of an object. reference when calling the DraftOrderService.CreateAsync error. I'm not sure where to turn to ask for help on this.

var url = ....
var token = ...
var service = new ShopifySharp.DraftOrderService(url,token);
var draft = new ShopifySharp.DraftOrder();
var lineItems = new List<ShopifySharp.DraftLineItem>();
lineItems.Add(new ShopifySharp.DraftLineItem {
    VariantId = 39986266341566,
    Quantity = 1
});
draft.LineItems = lineItems;
var output = null;
output = System.Threading.Tasks.Task.Run(() => service.CreateAsync(draft)).Result;

I'm able to call several other services and return data successfully using this method to execut the asnchronous command sycronously. Not sure if that is in play here as the issue or not.

TIMGATVOLER avatar Aug 06 '21 15:08 TIMGATVOLER

Thanks for the bug report! Could you post the full exception message and stack trace?

nozzlegear avatar Aug 06 '21 15:08 nozzlegear

Here's the serialized exception being thrown.

{
  "ClassName": "System.AggregateException",
  "Message": "One or more errors occurred.",
  "Data": null,
  "InnerException": {
    "ClassName": "System.NullReferenceException",
    "Message": "Object reference not set to an instance of an object.",
    "Data": null,
    "InnerException": null,
    "HelpURL": null,
    "StackTraceString": "   at ShopifySharp.ShopifyService.<>c__DisplayClass26_0`1.<<ExecuteRequestAsync>b__0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DefaultRequestExecutionPolicy.<Run>d__0`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.ShopifyService.<ExecuteRequestAsync>d__26`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DraftOrderService.<CreateAsync>d__6.MoveNext()",
    "RemoteStackTraceString": null,
    "RemoteStackIndex": 0,
    "ExceptionMethod": "8\nMoveNext\nShopifySharp, Version=5.12.0.0, Culture=neutral, PublicKeyToken=null\nShopifySharp.ShopifyService+<>c__DisplayClass26_0`1+<<ExecuteRequestAsync>b__0>d\nVoid MoveNext()",
    "HResult": -2147467261,
    "Source": "ShopifySharp",
    "WatsonBuckets": null
  },
  "HelpURL": null,
  "StackTraceString": "   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)\r\n   at VolerWeb.DataServices.Shopify.DataService.Services.DraftOrder.Create(Shop s, DraftOrder input, DraftOrder& output, List`1& exceptions) in c:\\AppDev\\Applications\\VolerWebApp\\trunk\\Voler.com\\App_Code\\VolerWeb.DataServices\\Shopify.DataService.cs:line 163",
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": "8\nGetResultCore\nmscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Threading.Tasks.Task`1\nTResult GetResultCore(Boolean)",
  "HResult": -2146233088,
  "Source": "mscorlib",
  "WatsonBuckets": null,
  "InnerExceptions": [
    {
      "ClassName": "System.NullReferenceException",
      "Message": "Object reference not set to an instance of an object.",
      "Data": null,
      "InnerException": null,
      "HelpURL": null,
      "StackTraceString": "   at ShopifySharp.ShopifyService.<>c__DisplayClass26_0`1.<<ExecuteRequestAsync>b__0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DefaultRequestExecutionPolicy.<Run>d__0`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.ShopifyService.<ExecuteRequestAsync>d__26`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DraftOrderService.<CreateAsync>d__6.MoveNext()",
      "RemoteStackTraceString": null,
      "RemoteStackIndex": 0,
      "ExceptionMethod": "8\nMoveNext\nShopifySharp, Version=5.12.0.0, Culture=neutral, PublicKeyToken=null\nShopifySharp.ShopifyService+<>c__DisplayClass26_0`1+<<ExecuteRequestAsync>b__0>d\nVoid MoveNext()",
      "HResult": -2147467261,
      "Source": "ShopifySharp",
      "WatsonBuckets": null
    }
  ]
}

TIMGATVOLER avatar Aug 06 '21 16:08 TIMGATVOLER

Thanks! This is a tough one, I don't see anything that immediately jumps out at me as the cause of the error. It looks like you've created your own wrapper class for the package's DraftOrderService? Does your code set the execution policy on the ShopifySharp service using SetExecutionPolicy at any point? Does it ever change the HttpClient?

nozzlegear avatar Aug 06 '21 18:08 nozzlegear

No I am not, here's a more simple test without the wrapper incase that is obfuscating something. This is being executed in an ASP.NET .ASPX page.

var url = "...";
var token = "...";
var draft = new ShopifySharp.DraftOrder();
draft.Email = "...";
var lineItems = new List<ShopifySharp.DraftLineItem>();
lineItems.Add(new ShopifySharp.DraftLineItem
{
    VariantId = 39986266341566,
    Quantity = 1
});
draft.LineItems = lineItems;
var service = new ShopifySharp.DraftOrderService(url, token);
try
{
    draft = System.Threading.Tasks.Task.Run(() => service.CreateAsync(draft)).Result;
}
catch(Exception exc)
{
    TextBox1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(exc, Newtonsoft.Json.Formatting.Indented);

}


var variantid = 39986266341566;
var service2 = new ShopifySharp.ProductVariantService(url, token);
ShopifySharp.ProductVariant pv = null;

try
{
    pv = System.Threading.Tasks.Task.Run(() => service2.GetAsync(variantid)).Result;
    TextBox1.Text += Environment.NewLine + Environment.NewLine + pv.Title;
}
catch(Exception exc)
{
    TextBox1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(exc, Newtonsoft.Json.Formatting.Indented);

}

Here is TextBox1's value which is the serialized exception and then the variant title that worked fine.

{
  "ClassName": "System.AggregateException",
  "Message": "One or more errors occurred.",
  "Data": null,
  "InnerException": {
    "ClassName": "System.NullReferenceException",
    "Message": "Object reference not set to an instance of an object.",
    "Data": null,
    "InnerException": null,
    "HelpURL": null,
    "StackTraceString": "   at ShopifySharp.ShopifyService.<>c__DisplayClass26_0`1.<<ExecuteRequestAsync>b__0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DefaultRequestExecutionPolicy.<Run>d__0`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.ShopifyService.<ExecuteRequestAsync>d__26`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DraftOrderService.<CreateAsync>d__6.MoveNext()",
    "RemoteStackTraceString": null,
    "RemoteStackIndex": 0,
    "ExceptionMethod": "8\nMoveNext\nShopifySharp, Version=5.12.0.0, Culture=neutral, PublicKeyToken=null\nShopifySharp.ShopifyService+<>c__DisplayClass26_0`1+<<ExecuteRequestAsync>b__0>d\nVoid MoveNext()",
    "HResult": -2147467261,
    "Source": "ShopifySharp",
    "WatsonBuckets": null
  },
  "HelpURL": null,
  "StackTraceString": "   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)\r\n   at ASP.dev_tim_shopify_submitorder_aspx.Button1_Click(Object sender, EventArgs e) in c:\\AppDev\\Applications\\VolerWebApp\\trunk\\Voler.com\\dev-tim\\Shopify\\SubmitOrder.aspx:line 66",
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": "8\nGetResultCore\nmscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Threading.Tasks.Task`1\nTResult GetResultCore(Boolean)",
  "HResult": -2146233088,
  "Source": "mscorlib",
  "WatsonBuckets": null,
  "InnerExceptions": [
    {
      "ClassName": "System.NullReferenceException",
      "Message": "Object reference not set to an instance of an object.",
      "Data": null,
      "InnerException": null,
      "HelpURL": null,
      "StackTraceString": "   at ShopifySharp.ShopifyService.<>c__DisplayClass26_0`1.<<ExecuteRequestAsync>b__0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DefaultRequestExecutionPolicy.<Run>d__0`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.ShopifyService.<ExecuteRequestAsync>d__26`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DraftOrderService.<CreateAsync>d__6.MoveNext()",
      "RemoteStackTraceString": null,
      "RemoteStackIndex": 0,
      "ExceptionMethod": "8\nMoveNext\nShopifySharp, Version=5.12.0.0, Culture=neutral, PublicKeyToken=null\nShopifySharp.ShopifyService+<>c__DisplayClass26_0`1+<<ExecuteRequestAsync>b__0>d\nVoid MoveNext()",
      "HResult": -2147467261,
      "Source": "ShopifySharp",
      "WatsonBuckets": null
    }
  ]
}

RACING RED / XSM

TIMGATVOLER avatar Aug 06 '21 19:08 TIMGATVOLER

I've done very little with asych calls in my career so some of this may just be ignorance on my part.

I tried this way as well and I get the exact same exception however using this implementation method I can retrieve the variant just fine.

<%@ Page Language="C#" Async="true" %>

<!DOCTYPE html>

<script runat="server">


    protected void Page_Load(object sender, EventArgs e)
    {
        //RegisterAsyncTask(new PageAsyncTask(MyTask));
        RegisterAsyncTask(new PageAsyncTask(MyTask2));
    }

    private async System.Threading.Tasks.Task MyTask2()
    {
        var url = "...";
        var token = "...";
        var draft = new ShopifySharp.DraftOrder();
        draft.Email = "...";
        var lineItems = new List<ShopifySharp.DraftLineItem>();
        var variantid = 39986266341566;
        lineItems.Add(new ShopifySharp.DraftLineItem
        {
            VariantId = variantid,
            Quantity = 1
        });
        draft.LineItems = lineItems;
        var service = new ShopifySharp.DraftOrderService(url, token);
        var order = await service.CreateAsync(draft);
        TextBox1.Text = order.OrderId.ToString();
    }

.......

TIMGATVOLER avatar Aug 06 '21 20:08 TIMGATVOLER

Okay, thanks! Turning the async calls into sync calls can sometimes cause issues, but I don't think that's the problem here. It looks like something inside the ShopifySharp service itself is throwing a null reference exception, but I'm having trouble figuring out what it might be. Our draft order tests are passing without issue, and I use draft orders in production but haven't had null reference exceptions.

Let's try to pare it down even more, try this code with your Shopify domain and access token and tell me if it works:

var service = new ShopifySharp.DraftOrderService(url, token);
var variantId = ...;
var draftOrder = await service.CreateAsync(new DraftOrder()
{
	LineItems = new List<DraftLineItem>()
	{
		new DraftLineItem()
		{
			Title = "Custom Draft Line Item",
			Price = 15.00m,
			Quantity = 2
		}
	},
	Note = "A note for the draft order"
});

Console.WriteLine("Draft order id is " + draftOrder.Id.Value);

This is the bare minimum required to create a draft order, and it's what we do in the automated unit tests for this package. Let me know what happens!

nozzlegear avatar Aug 06 '21 21:08 nozzlegear

It's a web project so I have to execute it in an aspx page but same issue.

Would it make sense to try to create a different shopify object and see if it throws the same or similar exception?

It seems like all the reads that I've attempted work fine it's just the writes.

<%@ Page Language="C#" Async="true" %>

<!DOCTYPE html>

<script runat="server">


    protected void Page_Load(object sender, EventArgs e)
    {
        RegisterAsyncTask(new PageAsyncTask(MyTask3));
    }

    private async System.Threading.Tasks.Task MyTask3()
    {
        var url = "..";
        var token = "..";
        var service = new ShopifySharp.DraftOrderService(url, token);
        var draftOrder = await service.CreateAsync(new ShopifySharp.DraftOrder()
        {
	        LineItems = new List<ShopifySharp.DraftLineItem>()
	        {
		        new ShopifySharp.DraftLineItem()
		        {
			        Title = "Custom Draft Line Item",
			        Price = 15.00m,
			        Quantity = 2
		        }
	        },
	        Note = "A note for the draft order"
        });

        TextBox1.Text = "Draft order id is " + draftOrder.Id.Value;
    }

TIMGATVOLER avatar Aug 06 '21 22:08 TIMGATVOLER

I tried creating a product and the exception thrown is pretty similar.

private async System.Threading.Tasks.Task MyTask()
    {
        try
        {
            var service = new ShopifySharp.ProductService(url, token);
            var product = new ShopifySharp.Product()
            {
                Title = "Burton Custom Freestlye 151",
                Vendor = "Burton",
                BodyHtml = "<strong>Good snowboard!</strong>",
                ProductType = "Snowboard",
                Images = new List<ShopifySharp.ProductImage>
                {
                    new ShopifySharp.ProductImage
                    {
                        Attachment = "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="
                    }
                },
            };

            product = await service.CreateAsync(product, new ShopifySharp.ProductCreateOptions() { Published = false });

            TextBox1.Text = product.Id.ToString();

        }
        catch(Exception exc)
        {
            PublishException(exc, TextBox1);
        }
    }

    private static void PublishException(Exception exc, System.Web.UI.WebControls.TextBox tb)
    {
        tb.Text = Newtonsoft.Json.JsonConvert.SerializeObject(exc, Newtonsoft.Json.Formatting.Indented);
    }

Nearly identical exception except different service call.

{
  "ClassName": "System.NullReferenceException",
  "Message": "Object reference not set to an instance of an object.",
  "Data": null,
  "InnerException": null,
  "HelpURL": null,
  "StackTraceString": "   at ShopifySharp.ShopifyService.<>c__DisplayClass26_0`1.<<ExecuteRequestAsync>b__0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.DefaultRequestExecutionPolicy.<Run>d__0`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.ShopifyService.<ExecuteRequestAsync>d__26`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at ShopifySharp.ProductService.<CreateAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at ASP.dev_tim_shopify_submitorder_aspx.<MyTask>d__4.MoveNext() in c:\\AppDev\\Applications\\VolerWebApp\\trunk\\Voler.com\\dev-tim\\Shopify\\SubmitOrder.aspx:line 36",
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": "8\nMoveNext\nShopifySharp, Version=5.12.0.0, Culture=neutral, PublicKeyToken=null\nShopifySharp.ShopifyService+<>c__DisplayClass26_0`1+<<ExecuteRequestAsync>b__0>d\nVoid MoveNext()",
  "HResult": -2147467261,
  "Source": "ShopifySharp",
  "WatsonBuckets": null
}

TIMGATVOLER avatar Aug 06 '21 22:08 TIMGATVOLER

Thanks, this is very strange. I suppose it might have to do with the synchronous call, as it's odd that calls using two different services are both throwing null reference exceptions.

Let's try a new approach, can you create a completely new .NET console project and see if you can get the package to work there? Use the same version of ShopifySharp if you can (I think you're using 5.12.0 if I'm reading the exception right). Make sure to change the Main method in Program.fs to async:

using ShopifySharp;

namespace MyApp
{
	public class Program
	{
		public async Task Main()
		{
			var service = new DraftOrderService(domain, token);
			var order = await service.CreateAsync(...);

			Console.WriteLine("Draft order id is " + order.Id.Value);
		}
	}
}

Let me know if you have any questions about setting up the console project!

nozzlegear avatar Aug 09 '21 04:08 nozzlegear

I get a Feature 'asynch main' is not available in C# 7.0. I'm using Visual Studio Pro 2017 version 15.9.3.

I can get the code to run following the recommendations from this stack over throw article: https://stackoverflow.com/questions/9208921/cant-specify-the-async-modifier-on-the-main-method-of-a-console-app

I get the same exception attempting to run the draft order creation. Exception Code NugetPackages ConsoleProperties

TIMGATVOLER avatar Aug 09 '21 13:08 TIMGATVOLER

I got it to run as an asych main by modifying the project csproj file.

It still throws the exception however.

ProjFileChange Code2 Exception2

TIMGATVOLER avatar Aug 09 '21 13:08 TIMGATVOLER

This is very very strange. Are you building a private app? My next guess is maybe your access token/password doesn't have the proper permissions for creating draft orders or products, although Shopify should be returning an error that would make ShopifySharp throw a different kind of exception if that was the case.

-- Josh Harms

On Mon, Aug 9, 2021, at 08:54, TIMGATVOLER wrote:

I got it to run as an asych main by modifying the project csproj file.

It still throws the exception however.

ProjFileChange https://user-images.githubusercontent.com/88549427/128717598-379f3b22-639b-4328-aa34-d586e972b5df.PNG Code2 https://user-images.githubusercontent.com/88549427/128717612-a507ab0d-0ac6-4d50-8eab-03367f5d79ef.PNG Exception2 https://user-images.githubusercontent.com/88549427/128717619-3975113d-79db-48a6-8a79-aa17f8deb723.PNG

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/nozzlegear/ShopifySharp/issues/658#issuecomment-895242749, or unsubscribe https://github.com/notifications/unsubscribe-auth/AASOE7CDV3YBUERW7RRRAV3T37MZPANCNFSM5BWCUNLQ.

nozzlegear avatar Aug 09 '21 14:08 nozzlegear

Yes it is a private app. This is really my first time attempting to develop against the shopify api and I am extremely new to using their platform to begin with.

Here's the permission configuration its pretty limited atm. Does anything stand out?

Permissions

TIMGATVOLER avatar Aug 09 '21 14:08 TIMGATVOLER

I tried altering the permissions on the private app to see if I could get a different exception.

When I revoke all access to orders and draft orders I get the following error.

(403 Forbidden) [API] This action requires merchant approval for read_draft_orders scope.

TIMGATVOLER avatar Aug 09 '21 14:08 TIMGATVOLER

That’s what I would expect it to throw if you didn’t have permissions, and your permissions screenshot looks correct. I think the next step is to see exactly what Shopify is returning that might be causing this null reference exception. We’ll need to skip ShopifySharp itself and use an HttpClient to make a request directly to the Shopify api. I’m not at home right now, but as soon as I’m back later today I can give you some code to set this up! Thanks for humoring me here, I haven’t seen this issue before so it’s baffling me at the moment.

-- Josh Harms

On Mon, Aug 9, 2021, at 09:30, TIMGATVOLER wrote:

I tried altering the permissions on the private app to see if I could get a different exception.

When I revoke all access to orders and draft orders I get the following error.

(403 Forbidden) [API] This action requires merchant approval for read_draft_orders scope.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/nozzlegear/ShopifySharp/issues/658#issuecomment-895273163, or unsubscribe https://github.com/notifications/unsubscribe-auth/AASOE7BEE7YUMES3VTV3M73T37Q75ANCNFSM5BWCUNLQ.

nozzlegear avatar Aug 09 '21 14:08 nozzlegear

So i downloaded the project from github and added it to my console and debugged the source code.

The exception is occuring on line 220 of ShopifyService.cs.

I notice that the rawResult variable the json root element is

"draft_orders": [

But DraftOrderService.cs on line 93 is passing "draft_order" (notice the lack of the 's' to make it plural.)

So I modified that to make it "draft_orders" and rebuilt and reran.

In debugging the data variable being returned on line 220 didn't throw the object null reference.

Now I get a completely different exception though...

this appears to be coming from line 221 of the ShopifyService.cs

{ "ClassName": "Newtonsoft.Json.JsonSerializationException", "Message": "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ShopifySharp.DraftOrder' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath 'draft_orders'.", "Data": null, "InnerException": null, "HelpURL": null, "StackTraceString": " at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\r\n at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType, JsonSerializer jsonSerializer)\r\n at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType)\r\n at Newtonsoft.Json.Linq.JToken.ToObject[T]()\r\n at ShopifySharp.ShopifyService.<>c__DisplayClass26_01.<<ExecuteRequestAsync>b__0>d.MoveNext() in C:\Users\timot\Downloads\ShopifySharp-master\ShopifySharp-master\ShopifySharp\Services\ShopifyService.cs:line 221\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at ShopifySharp.DefaultRequestExecutionPolicy.Run[T](CloneableRequestMessage request, ExecuteRequestAsync1 executeRequestAsync, CancellationToken cancellationToken) in C:\\Users\\timot\\Downloads\\ShopifySharp-master\\ShopifySharp-master\\ShopifySharp\\Infrastructure\\Policies\\DefaultRequestExecutionPolicy.cs:line 12\r\n at ShopifySharp.ShopifyService.ExecuteRequestAsync[T](RequestUri uri, HttpMethod method, CancellationToken cancellationToken, HttpContent content, String rootElement, Dictionary2 headers) in C:\Users\timot\Downloads\ShopifySharp-master\ShopifySharp-master\ShopifySharp\Services\ShopifyService.cs:line 202\r\n at ShopifySharp.DraftOrderService.CreateAsync(DraftOrder order, CancellationToken cancellationToken) in C:\Users\timot\Downloads\ShopifySharp-master\ShopifySharp-master\ShopifySharp\Services\DraftOrder\DraftOrderService.cs:line 93\r\n at ShopifySharpTest.Program.MyTask3(String[] args) in C:\Users\timot\OneDrive\Documents\Visual Studio 2017\Projects\ShopifySharpTest\ShopifySharpTest\Program.cs:line 58\r\n at ShopifySharpTest.Program.Main(String[] args) in C:\Users\timot\OneDrive\Documents\Visual Studio 2017\Projects\ShopifySharpTest\ShopifySharpTest\Program.cs:line 14", "RemoteStackTraceString": null, "RemoteStackIndex": 0, "ExceptionMethod": null, "HResult": -2146233088, "Source": "Newtonsoft.Json", "WatsonBuckets": null }`

TIMGATVOLER avatar Aug 09 '21 14:08 TIMGATVOLER

Seems like from the API documentation it should be returning draft_order not draft_orders.

https://shopify.dev/api/admin/rest/reference/orders/draftorder#create-2021-07

So I think the main issue is what is being returned or rather why its being returned that way.

Anything else you want me to try?

TIMGATVOLER avatar Aug 09 '21 15:08 TIMGATVOLER

I verified that the requestMessage on line 204 is a POST. I verified that it is being posted to: /admin/api/2021-07/draft_orders.json

When I hit a debug point on line 208 and drill into the response, response.RequestMessage indicates a GET call to the url and rather than display my domain it's showing the myshopify version of our domain. I don't do a whole lot with these sort of remote requests responses so I'm not sure if that is normal or not but seems odd.

So I googled "HttpClient SendAsynch sending a GET instead of POSt" and the first thing I found was:

https://stackoverflow.com/questions/35094809/c-sharp-httpclient-postasjson-sending-get-request-instead-of-post

It mentions someone changing the URL and redirecting...so that brought me back to why is the URL changing....

So I thought I'd try using the myshopify URL instead of our domain...

image

TIMGATVOLER avatar Aug 09 '21 15:08 TIMGATVOLER

Post Mortem

Thank you for all your help with this Joshua. I really appreciate how responsive you were through this process and I am pretty sure we will be a continued user of ShopfySharp because of that.

The documentation indicates that "custom domain should work too" but it clearly does not. I'm not sure if that is a new development or not. That may need to be updated.

Additionally, that it would make sense to throw an exception when the response URL is different than the request URL. You could probably get fancy and validate that and send a second request to the correct request URL too. But either would suffice to prevent this issue in the future with others.

Thanks again for all your help.

TIMGATVOLER avatar Aug 09 '21 15:08 TIMGATVOLER

Ah perfect, glad you got it figured out! The custom domains did work at one time, but now that you say that I remember there being an older bug report about this same behavior. I'll change the documentation and then add some code to catch this happening and throw a relevant error message.

-- Josh Harms

On Mon, Aug 9, 2021, at 10:41, TIMGATVOLER wrote:

Post Mortem

Thank you for all your help with this Joshua. I really appreciate how responsive you were through this process and I am pretty sure we will be a continued user of ShopfySharp because of that.

The documentation indicates that "custom domain should work too" but it clearly does not. I'm not sure if that is a new development or not. That may need to be updated.

Additionally, that it would make sense to throw an exception when the response URL is different than the request URL. You could probably get fancy and validate that and send a second request to the correct request URL too. But either would suffice to prevent this issue in the future with others.

Thanks again for all your help.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/nozzlegear/ShopifySharp/issues/658#issuecomment-895329273, or unsubscribe https://github.com/notifications/unsubscribe-auth/AASOE7FDFNG5VQDU4UKAEJLT37ZIZANCNFSM5BWCUNLQ.

nozzlegear avatar Aug 09 '21 19:08 nozzlegear