In this article, we will learn how to update a category in Quickbooks online from .NET MVC web application using SDK.
Before using any Quickbooks online API we need access token, if you don’t know how to get access token then you can find it here.
- First, we have to create a ServiceContext with Auth tokens and realmId.
- For that, we need access token and realmId
- We have to get the category from Quickbooks online by calling Item API.
- We are querying an item by Name and Type. (Type should be category)
- For querying/get item we have to define QueryService
- We need to pass the ServiceContext object into QueryService.
- We must need item Id and SyncToken for an update.
- We will create an item object and pass all new data(which we want to update) along with Id and SyncToken.
- After that, We have to create a DataService object by passing a ServiceContext object as a parameter.
- Add item object in DataService.Update<item>() for updating an category.
- It will return the newly updated item object, you can store the required details to the database according to your needs.
- The code is as below.
public ActionResult UpdateCategoryByName() { List<Item> ItemList = new List<Item>(); try { OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(Access_token); // Create a ServiceContext with Auth tokens and realmId ServiceContext serviceContext = new ServiceContext(RealmId, IntuitServicesType.QBO, oauthValidator); serviceContext.IppConfiguration.MinorVersion.Qbo = "23"; serviceContext.IppConfiguration.BaseUrl.Qbo = QboBaseUrl; // Create a QuickBooks QueryService using ServiceContext QueryService<Item> querySvc = new QueryService<Item>(serviceContext); string EXISTING_CATEGORY_QUERYBYNAME = string.Format("select * from Item where Name = '{0}' and Type = '{1}'", "Electronics", "Category"); Item objCategoryFound = querySvc.ExecuteIdsQuery(EXISTING_CATEGORY_QUERYBYNAME).FirstOrDefault<Item>(); if (objCategoryFound != null) { Item ObjItem = new Item(); ObjItem.Id = objCategoryFound.Id; ObjItem.SyncToken = objCategoryFound.SyncToken; ObjItem.Name = "Electronics and Peripheral"; ObjItem.TypeSpecified = objCategoryFound.TypeSpecified; ObjItem.Type = objCategoryFound.Type; DataService dataService = new DataService(serviceContext); Item UpdateEntity = dataService.Update<Item>(ObjItem); if (UpdateEntity != null && !string.IsNullOrEmpty(UpdateEntity.Id)) { //you can write Database code here ViewBag.IsSuccess = true; } } return View(); } catch (IdsException ex) { return View(); } catch (Exception ex) { return View(); } }
- If there is an item whose name is “Electronics” and Type is “Category” in Quickbooks online then its Name will be updated to “Electronics and Peripheral”. basically category is an item of type Category in Quickbooks Online.