app crashes before the request is sent to the server - c#

I'm building an android app with Xamarin which communicates with an ASP.net server's API. I'm trying to upload a file to the server using the following lines of code:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
//progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = "myvideooo.mp4", username = "psyoptica" };
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
The app crashes before the server receives the request. The file I'm trying to upload could be a video or an audio file. The server receives the request after the app has crashed. This works fine on the local server but the crash happens with the live server. My server side code looks like this:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
File.WriteAllBytes(tempFilePath, model.data);
if (model.fileName.Contains("audio"))
{
File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
string audio_thumb = "mic_thumb.jpg";
string destination = Path.Combine(pathToThumbs, audio_thumb);
string source = Path.Combine(pathToFiles, audio_thumb);
if (!System.IO.File.Exists(destination))
{
System.IO.File.Copy(source, destination, true);
}
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = "mic_thumb.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
long videoid = VideoBLL.Process_Info(vd, false);
}
else
{
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname+"_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
}
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}`
What am I doing wrong here that's making the app crash. Is there a better way to do this?
Any help is appreciated.

Related

Xamarin.iOS - Set audio sample rate for each video when merging multiple videos

Trying to stitch multiple videos using AVAssetTrack and AVMutableCompositionTrack. Uploaded videos could have different audio settings (e.g. sample rate) - what's the best way to pass in desired audio settings when adding AVAssetTracks to AVMutableVideoComposition? Currently using the following code, certain videos with 48KHz stitched with 44.1KHz produce no sound when played on IE/Edge, but works on other browsers:
Composition = new AVMutableComposition();
AVMutableCompositionTrack VideoCompositionTrack = Composition.AddMutableTrack(AVMediaType.Video, 0);
AVMutableCompositionTrack AudioCompositionTrack = Composition.AddMutableTrack(AVMediaType.Audio, 1);
AVMutableVideoCompositionLayerInstruction LayerInstruction = AVMutableVideoCompositionLayerInstruction.FromAssetTrack(VideoCompositionTrack);
CMTime StartTime = CMTime.Zero;
AVUrlAssetOptions Options = new AVUrlAssetOptions
{
PreferPreciseDurationAndTiming = true
};
CMTimeRange TimeRange;
NSError InsertError = null;
int Counter = 0;
CGSize FinalRenderSize = new CGSize();
foreach (NSUrl VideoLocation in SelectedVideoLocations)
{
using (AVAsset Asset = new AVUrlAsset(VideoLocation, Options))
{
TimeRange = new CMTimeRange()
{
Start = CMTime.Zero,
Duration = Asset.Duration
};
if (Asset.TracksWithMediaType(AVMediaType.Video).Length > 0)
{
using (AVAssetTrack VideoAssetTrack = Asset.TracksWithMediaType(AVMediaType.Video)[0])
{
if (Counter == 0)
{
FinalRenderSize = VideoAssetTrack.NaturalSize;
}
LayerInstruction.SetTransform(VideoAssetTrack.PreferredTransform, StartTime);
VideoCompositionTrack.InsertTimeRange(TimeRange, VideoAssetTrack, StartTime, out InsertError);
}
}
if (Asset.TracksWithMediaType(AVMediaType.Audio).Length > 0)
{
using (AVAssetTrack AudioAssetTrack = Asset.TracksWithMediaType(AVMediaType.Audio)[0])
{
LayerInstruction.SetTransform(AudioAssetTrack.PreferredTransform, StartTime);
AudioCompositionTrack.InsertTimeRange(TimeRange, AudioAssetTrack, StartTime, out InsertError);
}
}
StartTime = CMTime.Add(StartTime, Asset.Duration);
Counter++;
}
}
AVMutableVideoCompositionInstruction MainInstruction = new AVMutableVideoCompositionInstruction
{
TimeRange = VideoCompositionTrack.TimeRange,
LayerInstructions = new AVVideoCompositionLayerInstruction[1] { LayerInstruction }
};
AVMutableVideoComposition CompositionInstruction = AVMutableVideoComposition.Create(Composition);
CompositionInstruction.Instructions = new AVMutableVideoCompositionInstruction[1] { MainInstruction };
CompositionInstruction.FrameDuration = new CMTime(1, 30);
CompositionInstruction.RenderScale = 1.0f;
CompositionInstruction.RenderSize = FinalRenderSize;
string FilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), FolderName, FileName);
await LocalStorage.DeleteFileAsync(FilePath);
NSUrl FilePathURL = NSUrl.CreateFileUrl(new string[] { FilePath });
MediaURL = FilePath;
AVAssetExportSession ExportSession = new AVAssetExportSession(Composition, AVAssetExportSessionPreset.Preset960x540);
if (CompositionInstruction != null)
{
ExportSession.VideoComposition = CompositionInstruction;
}
ExportSession.ShouldOptimizeForNetworkUse = true;
ExportSession.OutputUrl = FilePathURL;
ExportSession.OutputFileType = AVFileType.Mpeg4;
await ExportSession.ExportTaskAsync();
if (ExportSession.Status != AVAssetExportSessionStatus.Completed)
{
throw new Exception(ExportSession.Error.DebugDescription);
}

Refreshing of several controls in loop Winforms

I'm trying to make weather application. And when I input new city in my combobox,my labels and pictureboxes don't refresh. I have already tried Refresh() Update() and Invalidate() and none of them worked. Tell me please ,what I'm suppose to do. Thank you in advance!
private async void SetWeatherForecastDataToWeatherApp(string city)
{
try
{
var jsonData = string.Empty;
var url = string.Format("http://api.openweathermap.org/data/2.5/forecast?q={0}&APPID=a54961a05f7a1fc0cf9bd2bf1465dea5", city);
var uri = new Uri(url);
var request = WebRequest.Create(uri);
var response = await request.GetResponseAsync();
using (var stream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(stream))
{
jsonData = await streamReader.ReadToEndAsync();
}
}
response.Close();
_jsonFutureWeatherForecastData = jsonData;
_weatherForecast = JsonConvert.DeserializeObject<WeatherForecast>(_jsonFutureWeatherForecastData);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Input Error", MessageBoxButtons.OK);
}
var dayNameLabelList = new List<Label>();
var weatherDescriptionLablList = new List<Label>();
var gradesLabel = new List<Label>();
var pictureBoxList = new List<PictureBox>();
int yLocation = 50;
int xLocation = Width / 2;
int cnt = 0;
string currDayOfWeek = string.Empty;
string CurrentDate = string.Empty;
for (int i = 0; i < 9; i++)
{
currDayOfWeek = _dateConverter.ConvertMilisecondsToCurrentTime(_weatherForecast.WeatherList[i].CurrentDate).DayOfWeek.ToString();
CurrentDate = _dateConverter.ConvertMilisecondsToCurrentTime(_weatherForecast.WeatherList[i].CurrentDate).Day.ToString();
cnt++;
pictureBoxList.Add(new PictureBox());
pictureBoxList[i].Name = "WeatherForecastImage" + cnt.ToString();
pictureBoxList[i].Location = new Point(xLocation, yLocation);
pictureBoxList[i].Load($"Icons/{_weatherForecast.WeatherList[i].Weather[0].Icon}.png");
Controls.Add(pictureBoxList[i]);
pictureBoxList[i].Invalidate();
dayNameLabelList.Add(new Label());
dayNameLabelList[i].Text = currDayOfWeek + " " + CurrentDate;
dayNameLabelList[i].Location = new Point(xLocation + 100, yLocation);
dayNameLabelList[i].Size = new Size(100, 15);
dayNameLabelList[i].Font = new Font("Lucida Sans", 10, FontStyle.Regular);
Controls.Add(dayNameLabelList[i]);
weatherDescriptionLablList.Add(new Label());
weatherDescriptionLablList[i].Text = _weatherForecast.WeatherList[i].Weather[0].Description;
weatherDescriptionLablList[i].Location = new Point(xLocation + 100, yLocation + 15);
weatherDescriptionLablList[i].Font = new Font("Lucida Sans", 8, FontStyle.Regular);
Controls.Add(weatherDescriptionLablList[i]);
gradesLabel.Add(new Label());
gradesLabel[i].Text = _weatherForecast.WeatherList[i].Main.Temperature.ToString("0") + " C°";
gradesLabel[i].Location = new Point(xLocation + 200, yLocation);
gradesLabel[i].Font = new Font("Lucida Sans", 10, FontStyle.Regular);
Controls.Add(gradesLabel[i]);
yLocation += 100;
}
for (int i = 0; i < dayNameLabelList.Count; i++)
{
dayNameLabelList[i].ForeColor = Color.White;
weatherDescriptionLablList[i].ForeColor = Color.White;
gradesLabel[i].ForeColor = Color.White;
}
}
You need to add event handlers to the combo for either SelectedIndexChangedEvent (if it's a non-editable combo), or TextUpdateEvent if it is (likely both in that latter case). Those event handlers then change the other controls as needed.

Viewing XML output from C#

I'm trying to work with the UPS api to create a shipping label. The UPS api uses a webservice to send an XML request to UPS. UPS then sends a response back. Here is my question.
Is there a way to view the XML that is outputted when I call the "shipmentRequest" method?
This is the first time I've used an API and a webservice so if you need me to provide more information just let me know.
Thanks!
EDIT: Here is my C# code
ShipService shpSvc = new ShipService();
ShipmentRequest shipmentRequest = new ShipmentRequest();
UPSSecurity upss = new UPSSecurity();
//shpSvc.Url = "https://onlinetools.ups.com/webservices/Ship";
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = apiCode;
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = userName;
upssUsrNameToken.Password = password;
upss.UsernameToken = upssUsrNameToken;
shpSvc.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "nonvalidate" };
request.RequestOption = requestOption;
shipmentRequest.Request = request;
ShipmentType shipment = new ShipmentType();
shipment.Description = "Ship webservice example";
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = accountNumber;
PaymentInfoType paymentInfo = new PaymentInfoType();
ShipmentChargeType shpmentCharge = new ShipmentChargeType();
BillShipperType billShipper = new BillShipperType();
billShipper.AccountNumber = accountNumber;
shpmentCharge.BillShipper = billShipper;
shpmentCharge.Type = "01";
ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
paymentInfo.ShipmentCharge = shpmentChargeArray;
shipment.PaymentInformation = paymentInfo;
ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] addressLine = { "480 Parkton Plaza" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "Timonium";
shipperAddress.PostalCode = "21093";
shipperAddress.StateProvinceCode = "MD";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipper.Name = "ABC Associates";
shipper.AttentionName = "ABC Associates";
ShipPhoneType shipperPhone = new ShipPhoneType();
shipperPhone.Number = "1234567890";
shipper.Phone = shipperPhone;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] shipFromAddressLine = { "Ship From Street" };
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "Timonium";
shipFromAddress.PostalCode = "21093";
shipFromAddress.StateProvinceCode = "MD";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipFrom.AttentionName = "Mr.ABC";
shipFrom.Name = "ABC Associates";
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { "Some Street" };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = "Roswell";
shipToAddress.PostalCode = "30076";
shipToAddress.StateProvinceCode = "GA";
shipToAddress.CountryCode = "US";
shipTo.Address = shipToAddress;
shipTo.AttentionName = "DEF";
shipTo.Name = "DEF Associates";
ShipPhoneType shipToPhone = new ShipPhoneType();
shipToPhone.Number = "1234567890";
shipTo.Phone = shipToPhone;
shipment.ShipTo = shipTo;
ServiceType service = new ServiceType();
service.Code = "01";
shipment.Service = service;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "1";
ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
uom.Code = "LBS";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
PackagingType packType = new PackagingType();
packType.Code = "02";
package.Packaging = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
LabelSpecificationType labelSpec = new LabelSpecificationType();
LabelStockSizeType labelStockSize = new LabelStockSizeType();
labelStockSize.Height = "6";
labelStockSize.Width = "4";
labelSpec.LabelStockSize = labelStockSize;
LabelImageFormatType labelImageFormat = new LabelImageFormatType();
labelImageFormat.Code = "SPL";
labelSpec.LabelImageFormat = labelImageFormat;
shipmentRequest.LabelSpecification = labelSpec;
shipmentRequest.Shipment = shipment;
ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
MessageBox.Show("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
MessageBox.Show("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
You can inherit from the UPS service and read the response as xml by providing your own XmlWriter by overriding GetWriterForMessage(). You can see a working example here.
i am using this code display xml it may help you.
XDocument mySourceDoc = new XDocument();
mySourceDoc = XDocument.Load(shipmentResponse);
txtxml.Text = mySourceDoc.ToString();

Expedia hotel API

I am working on Expedia hotel API.All the function are working except booking.All the other request using GET method for requesting.But in booking we have to use the POST method with different URL.So i changed the URL for request but still getting the error.
My codes are
HotelServicesImplService client = new HotelServicesImplService();
HotelRoomReservationRequest bookreq = new HotelRoomReservationRequest();
HotelRoomReservationResponse bookres = new HotelRoomReservationResponse();
addressInfo bookad = new addressInfo();
reservationInfo bookinfo = new reservationInfo();
client.Url = "https://book.api.ean.com/ean-services/rs/hotel/v3";
//bookreq.minorRevSpecified = true;
//bookreq.minorRev = 25;
bookreq.hotelId = 106347;
bookreq.apiKey = "api";
bookreq.cid = "cid";
bookreq.arrivalDate = "12/11/2013";
bookreq.departureDate = "12/13/2013";
bookreq.supplierType = SupplierType.E;
bookreq.rateKey = "af00b688-acf4-409e-8bdc-fcfc3d1cb80c";
bookreq.roomTypeCode = "198058";
bookreq.rateCode = "484072";
bookreq.RoomGroup = new[] { new Room
{
numberOfAdults=Convert.ToInt32(2),
numberOfChildren=Convert.ToInt32(0),
childAges=new int[] {} ,
firstName="Test Booking",
lastName="Test Booking",
bedTypeId="23",
smokingPreference=SmokingPreference.NS,
}};
float i = float.Parse("231.18");
bookreq.currencyCode = "USD";
bookreq.chargeableRate = i;
bookinfo.email = "ranaabhi007#yahoo.com";
bookinfo.firstName = "TestBooking";
bookinfo.lastName = "TestBooking";
bookinfo.homePhone = "2145370159";
bookinfo.workPhone = "2145370159";
bookinfo.creditCardType = "CA";
bookinfo.creditCardNumber = "5401999999999999";
bookinfo.creditCardIdentifier = "TestBooking";
bookinfo.creditCardExpirationMonth = "12";
bookinfo.creditCardExpirationYear = "2015";
bookad.city = "Seattle";
bookad.stateProvinceCode = "WA";
bookad.countryCode = "US";
bookad.postalCode = "98004";
bookreq.ReservationInfo = bookinfo;
bookad.address1 = "travelnow";
//bookad.city = txtCity.Text;
//bookad.stateProvinceCode = txtState.Text;
//bookad.countryCode = txtCountry.Text;
//bookad.postalCode = txtPostal.Text;
bookreq.AddressInfo = bookad;
bookres = client.getReservation(bookreq);
// HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(client);
Response.Write(bookres.confirmationNumbers);
Response.Write(bookres.departureDate);
Response.Write(bookres.drivingDirections);
Response.Write(bookres.CouponInformationResponse);
but i am still getting the error
The request failed with HTTP status 404: Not Found.
Are you sure your URL is correct? According to the documentation, it should be
https://book.api.ean.com/ean-services/rs/hotel/v3/res

Query for All Invoices With Open Balances using QuickBooks Online (QBO) Intuit Partner Platform (IPP) DevKit

I am trying to Query for all invoices with open balances using IPP but I keep on getting 0 results back. Am I doing something wrong in code?
Here is my C# code snippet that I am trying to do with the applied Filtering
InvoiceQuery qboInvoiceQuery = new InvoiceQuery();
int iMaxPageNumber = QUERY_MAX_PAGE_NUMBER; // A Constant with the Maximum Page Number allowed in a query
int iResultsPerPage = QUERY_MAX_NUM_PER_PAGE_INVOICE; // A Constant with the Maximum Results per page
// Paging Information
qboInvoiceQuery.PageNumber = QUERY_START_PAGE_NUMBER;
qboInvoiceQuery.ResultsPerPage = iResultsPerPage;
#region Query Filtering
//////////////////////////////////////////////
// initial filtering via Query Criteria //
//////////////////////////////////////////////
// Get only Open (Unpaid) Invoices
qboInvoiceQuery.OpenBalance = (decimal)0.00;
qboInvoiceQuery.SpecifyOperatorOption(FilterProperty.OpenBalance, FilterOperatorType.AFTER);
//////////////////////////////////////////////
// END initial filtering via Query Criteria //
//////////////////////////////////////////////
#endregion
// Complete the Query calls to build the list
IEnumerable<Invoice> results = qboInvoiceQuery.ExecuteQuery<Invoice>(_ServiceContext);
IEnumerable<Invoice> qboInvoices = results;
int iCount = results.Count();
while (iCount > 0 && iCount == iResultsPerPage && qboInvoiceQuery.PageNumber <= iMaxPageNumber)
{
qboInvoiceQuery.PageNumber++;
results = qboInvoiceQuery.ExecuteQuery<Invoice>(_ServiceContext);
iCount = results.Count();
qboInvoices = qboInvoices.Concat(results);
}
*** UPDATE ***
I have implemented peterl's answer and now have the following code. However I am now running into a new problem that my code is always returning the default of 10 invoices and is not taking into consideration my body. Even if i set it to a different page number or ResultsPerPage value I was get back the first page and 10 results. Any ideas?
private Dictionary<string, Invoice> GetUnpaidInvoicesDictionary(IdType CustomerId, bool bById = true)
{
Dictionary<string, Invoice> dictionary = new Dictionary<string, Invoice>();
int iMaxPageNumber = 100;
int iResultsPerPage = 100;
try
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = _sConsumerKey,
SignatureMethod = SignatureMethod.HmacSha1,
ConsumerSecret = _sConsumerSecret
};
string sBaseURL = "https://oauth.intuit.com/oauth/v1";
string sUrlRequestToken = "/get_request_token";
string sUrlAccessToken = "/get_access_token";
OAuthSession oSession = new OAuthSession(consumerContext,
sBaseURL + sUrlRequestToken,
sBaseURL,
sBaseURL + sUrlAccessToken);
oSession.AccessToken = new TokenBase
{
Token = _sAccessToken,
ConsumerKey = _sConsumerKey,
TokenSecret = _sAccessTokenSecret
};
int iPageNumber = QUERY_START_PAGE_NUMBER;
string sCustomerId = CustomerId.Value;
string sBodyBase = "PageNum={0}&ResultsPerPage={1}&Filter=OpenBalance :GreaterThan: 0.00 :AND: CustomerId :EQUALS: {2}";
string sBody = String.Format(sBodyBase, iPageNumber, iResultsPerPage, sCustomerId);
IConsumerRequest conReq = oSession.Request();
conReq = conReq.Post().WithRawContentType("application/x-www-form-urlencoded").WithRawContent(System.Text.Encoding.ASCII.GetBytes(sBody)); ;
conReq = conReq.ForUrl(_DataService.ServiceContext.BaseUrl + "invoices/v2/" + _DataService.ServiceContext.RealmId);
conReq = conReq.SignWithToken();
// Complete the Query calls to build the list
SearchResults searchResults = (SearchResults)_DataService.ServiceContext.Serializer.Deserialize<SearchResults>(conReq.ReadBody());
IEnumerable<Invoice> results = ((Invoices)searchResults.CdmCollections).Invoice;
IEnumerable<Invoice> qboInvoices = results;
int iCount = searchResults.Count;
while (iCount > 0 && iCount == iResultsPerPage && iPageNumber <= iMaxPageNumber)
{
iPageNumber++;
sBody = String.Format(sBodyBase, iPageNumber, iResultsPerPage, sCustomerId);
conReq = oSession.Request();
conReq = conReq.Post().WithRawContentType("application/x-www-form-urlencoded").WithRawContent(System.Text.Encoding.ASCII.GetBytes(sBody)); ;
conReq = conReq.ForUrl(_DataService.ServiceContext.BaseUrl + "invoices/v2/" + _DataService.ServiceContext.RealmId);
conReq = conReq.SignWithToken();
searchResults = (SearchResults)_DataService.ServiceContext.Serializer.Deserialize<SearchResults>(conReq.ReadBody());
results = ((Invoices)searchResults.CdmCollections).Invoice;
qboInvoices = qboInvoices.Concat(results);
iCount = searchResults.Count;
}
if (bById)
foreach (Invoice Inv in qboInvoices)
dictionary.Add(Inv.Id.Value, Inv);
else
foreach (Invoice Inv in qboInvoices)
dictionary.Add(Inv.Header.DocNumber, Inv);
return dictionary;
}
catch (Exception)
{
return null;
}
}
* UPDATE *
There is a similar issue out there that involves the new api tester. This could be related to this issue and they are currently looking into it.
Stack Overflow: QuickBooks Online querying with filter returns 401 everytime
This is a bug in the DevKit. The OpenBalance filter defaults to :EQUALS: and does not support :GreaterThan:.
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0400_QuickBooks_Online/Invoice#Attributes_Supporting_Filtering_and_Sorting
Here is a workaround using DevDefined to construct the OAuth header:
public List<Intuit.Ipp.Data.Qbo.Invoice> GetQboUnpaidInvoices(DataServices dataServices, int startPage, int resultsPerPage, IdType CustomerId)
{
StringBuilder requestXML = new StringBuilder();
StringBuilder responseXML = new StringBuilder();
var requestBody = String.Format("PageNum={0}&ResultsPerPage={1}&Filter=OpenBalance :GreaterThan: 0.00 :AND: CustomerId :EQUALS: {2}", startPage, resultsPerPage, CustomerId.Value);
HttpWebRequest httpWebRequest = WebRequest.Create(dataServices.ServiceContext.BaseUrl + "invoices/v2/" + dataServices.ServiceContext.RealmId) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(httpWebRequest, requestBody));
requestXML.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(requestXML.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
Intuit.Ipp.Data.Qbo.SearchResults searchResults = (Intuit.Ipp.Data.Qbo.SearchResults)dataServices.ServiceContext.Serializer.Deserialize<Intuit.Ipp.Data.Qbo.SearchResults>(new StreamReader(data).ReadToEnd());
return ((Intuit.Ipp.Data.Qbo.Invoices)searchResults.CdmCollections).Invoice.ToList();
}
}
protected string GetDevDefinedOAuthHeader(HttpWebRequest webRequest, string requestBody)
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
SignatureMethod = SignatureMethod.HmacSha1,
UseHeaderForOAuthParameters = true
};
consumerContext.UseHeaderForOAuthParameters = true;
//URIs not used - we already have Oauth tokens
OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
"https://www.example.com",
"https://www.example.com");
oSession.AccessToken = new TokenBase
{
Token = accessToken,
ConsumerKey = consumerKey,
TokenSecret = accessTokenSecret
};
IConsumerRequest consumerRequest = oSession.Request();
consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
if (webRequest.Headers.Count > 0)
{
ConsumerRequestExtensions.AlterContext(consumerRequest, context => context.Headers = webRequest.Headers);
if (webRequest.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded")
{
Dictionary<string, string> formParameters = new Dictionary<string, string>();
foreach (string formParameter in requestBody.Split('&'))
{
formParameters.Add(formParameter.Split('=')[0], formParameter.Split('=')[1]);
}
consumerRequest = consumerRequest.WithFormParameters(formParameters);
}
}
consumerRequest = consumerRequest.SignWithToken();
return consumerRequest.Context.GenerateOAuthParametersForHeader();
}
http://nuget.org/packages/DevDefined.OAuth

Categories