Index out of bound at xmlworkerhelper in c# - asp.net

PaymentService.PaymentServiceClient client = new
PaymentService.PaymentServiceClient();
PaymentTransactionDto model = new PaymentTransactionDto();
OrderInvoiceDto invoiceData;
List<ProductRepoDto> products;
List<OrderTaxDto> taxes;
// Check payment status
int chkProduct = 0;
int chkCourse = 0;
int chkProductCourse = 0;
#region Get order details for invoice
var order_details = client.GetOrderDetailsForInvoice(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
invoiceData = new OrderInvoiceDto();
if (order_details != null)
{
invoiceData = AutoMapConverter<PaymentService.OrderInvoiceDto, OrderInvoiceDto>.GetMappedData(order_details);
}
#endregion
#region Get Products list in order
var productList = client.GetOrderItemsByOrderId(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
products = new List<ProductRepoDto>();
if (productList != null && productList.Count() > 0)
{
products = AutoMapConverter<PaymentService.ProductRepoDto, ProductRepoDto>.GetMappedList(productList.ToList());
}
#endregion
#region ADD Taxes
#region check product type
decimal Amount = 0;
foreach (var item in products)
{
if (item.TypeId == 1)
chkCourse = 1;
if (item.TypeId == 2)
chkProduct = 1;
if (chkCourse == 1 && chkProduct == 1)
chkProductCourse = 1;
Amount = Amount + (item.Amount * item.Quantity);
Amount = Amount - item.Discount;
}
#endregion
// Apply taxes
client.AddOrderTaxMappingDetails(Convert.ToInt64(orderid), Amount);
#endregion
#region Get Applied Tax details
var taxesApplied = client.GetOrderAppliedTaxes(Convert.ToInt64(orderid));
taxes = new List<OrderTaxDto>();
if (taxesApplied != null && taxesApplied.Count() > 0)
{
taxes = AutoMapConverter<PaymentService.OrderTaxDto, OrderTaxDto>.GetMappedList(taxesApplied.ToList());
}
#endregion
string pdfbody = System.IO.File.ReadAllText(Server.MapPath("~/Views/Payment/InvoiceView.cshtml"));
Document document = new Document();
string fileName = string.Format("{0}.pdf", invoiceData.OrderNumber);
var fpath = HttpContext.Current.Server.MapPath("~/Document/Payment/Invoice/");
if (!Directory.Exists(fpath))
{
Directory.CreateDirectory(fpath);
}
pdfbody = pdfbody.Replace("$name$", string.Format("{0} {1}", invoiceData.Billing_FirstName, invoiceData.Billing_LastName));
pdfbody = pdfbody.Replace("$address$", invoiceData.Billing_Address);
pdfbody = pdfbody.Replace("$billingCity$", invoiceData.Billing_City);
pdfbody = pdfbody.Replace("$billingPinCode$", invoiceData.Billing_PinCode.ToString());
pdfbody = pdfbody.Replace("$billingState$", invoiceData.Billing_State);
pdfbody = pdfbody.Replace("$billingCountry$", invoiceData.Billing_Country);
//pdfbody = pdfbody.Replace("$netAmt$", invoiceData.NetAmt.ToString());
//pdfbody = pdfbody.Replace("$grossAmt$", invoiceData.GrossAmt.ToString());
//pdfbody = pdfbody.Replace("$discountAmt$", invoiceData.DiscountAmt.ToString());
pdfbody = pdfbody.Replace("$orderNumber$", invoiceData.OrderNumber.Remove(0, 2));
pdfbody = pdfbody.Replace("$orderDate$", CommonFunctions.EpochToIstDate(Convert.ToDouble(invoiceData.OrderDate)));
StringBuilder b = new StringBuilder();
decimal totalAmount = 0;
foreach (var item in products)
{
if (!string.IsNullOrEmpty(item.ActivationKey))
item.ActivationKey = string.Format("Activation Key:{0}", item.ActivationKey);
b.AppendFormat("<tr><td width='60%'>{0}<br/>{1}</td>", item.ProductName, item.ActivationKey);
b.AppendFormat("<td width='10%' align='left'>{0}</td>", item.Quantity);
b.AppendFormat("<td width='30%' align='right'>{0}</td></tr>", (item.Amount * item.Quantity) - item.Discount);
totalAmount = totalAmount + (item.Amount * item.Quantity);
totalAmount = totalAmount - item.Discount;
}
pdfbody = pdfbody.Replace("$OrderDetailsList$", Convert.ToString(b));
if (taxes != null && taxes.Count > 0)
{
b = new StringBuilder();
foreach (var item in taxes)
{
b.AppendFormat("<tr><td width='80%' colspan='2'>{0} ({1}%)</td>", item.TaxName, item.Percentage);
b.AppendFormat("<td width='20%' align='right'>{0}</td></tr>", item.Amount);
}
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", Convert.ToString(b));
}
else
{
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", "");
}
pdfbody = pdfbody.Replace("$netAmt$", totalAmount.ToString());
pdfbody = pdfbody.Replace("$rupees$", CommonFunctions.ConvertNumbertoWords(Convert.ToInt32((int)Math.Ceiling(totalAmount))));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fpath + fileName, FileMode.Create));
document.Open();
StringReader sr = new StringReader(pdfbody);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
document.Close();
I want to generate pdf invoice.so i am using itextsharp.
but i am getting Index out of bound array at XMLWorkerHelper.
I am using itextsharp.xmlworker.dll, v5.4.5.0
when i try to update itextsharp.xmlworker.dll, v5.4.5.9
this code works fine..but all other modules of my project which use iTextsharp starts getting error.
if this is version problem, then how i add two different dll in bin folder and use it
or it is code related error?

Related

Xamarin forms: How to add tapped event on XamForms.Controls.Calendar specialdate?

I am using XamForms.Controls.Calendar package for showing calendar in my project. I am marking events on the calendar using the below code.
private void AddSpecialDateWithList(List<events> list)
{
List<SpecialDate> newList = new List<SpecialDate>();
foreach (events model in list)
{
string startDate = model.start;
int startIndex = startDate.IndexOf('T');
if (startIndex > 0)
{
startDate = startDate.Substring(0, startIndex);
}
string endDate = model.end;
int endIndex = endDate.IndexOf('T');
if (endIndex > 0)
{
endDate = endDate.Substring(0, endIndex);
}
List<DateTime> dates = GetDatesBetween(DateTime.Parse(startDate), DateTime.Parse(endDate));
for(int i=0;i< dates.Count; i++)
{
var newDate = AddDate(dates[i], model);
newList.Add(newDate);
}
}
calendar.SpecialDates = newList;
}
private SpecialDate AddDate(DateTime dateTime, events model)
{
SpecialDate newDate = new SpecialDate(dateTime)
{
Selectable = true,
BackgroundPattern = new BackgroundPattern(1)
{
Pattern = new List<Pattern>
{
new Pattern { WidthPercent = 1f, HightPercent = 0.7f, Color = Color.White },
new Pattern{ WidthPercent = 1f, HightPercent = 0.3f, Color = Color.Yellow, Text = model.title, TextColor=Color.Black, TextSize=10, TextAlign=TextAlign.LeftCenter},
}
}
};
return newDate;
}
Screenshot:
When I tap a day having event(31 Jan having maths homework), I need to get the event id and all the other details associated with that event. How can I do this feature? Also is it possible to show month, week and day view in XamForms.Controls.Calendar?
You could get the index of SpecialDate in your list in the event DateClicked
private void calendar_DateClicked(object sender, DateTimeEventArgs e)
{
int num = 0;
var specialList = calendar.SpecialDates;
var date = e.DateTime;
foreach(SpecialDate specialDate in specialList)
{
if(specialDate.Date.Year==date.Year&& specialDate.Date.Month == date.Month&&specialDate.Date.Day == date.Day)
{
events model = list[num];
// do something you want
}
else
{
num++;
}
}
}

customize the height and width of ESRI map callout

here is the formatted String which i am binding to callout but i am able to see only some contents of my string in callout
private async void WebMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
try
{
WebMapView.DismissCallout();
MapPoint mapLocation = null;
var layers = await WebMapView.IdentifyLayersAsync(e.Position, 20, false);
if (layers.Count > 0)
{
foreach (var idResults in layers)
{
FeatureLayer idLayer = idResults.LayerContent as FeatureLayer;
await idLayer.LoadAsync();
var result = layers.First();
var feature = result.GeoElements.First() as ArcGISFeature;
await feature.LoadAsync(); // Load feature to get all attributes
Feature idFeature = result.GeoElements.First() as Feature;
featureAttrs = idFeature.Attributes;
var stateExtent = idFeature.Geometry;
Graphicoverlay = new GraphicsOverlay();
Graphic graphicLine = null;
graphicLine = new Graphic(stateExtent, AppConstant.HighLight1);
Graphicoverlay.Graphics.Add(graphicLine);
EnvelopeBuilder myEnvelopeBuilder = new EnvelopeBuilder(SpatialReferences.WebMercator);
//Geometry abd = oneGraphic.Geometry;
myEnvelopeBuilder.UnionOf(graphicLine.Geometry.Extent);
myEnvelopeBuilder.Expand(1.3);
mapLocation = myEnvelopeBuilder.Center;
Geometry myGeometry = GeometryEngine.Project(mapLocation, SpatialReferences.WebMercator);
MapPoint projectedLocation = (MapPoint)myGeometry;
string formattedString = "";
if (featureAttrs.Count > 0)
{
foreach (var attributes in featureAttrs)
{
string recordOneAttribute = $"{attributes.Key} {attributes.Value}";
formattedString = $"{formattedString}\n{ recordOneAttribute}";
}
}
CalloutDefinition calloutDef = new CalloutDefinition("Feature:",formattedString);
WebMapView.ShowCalloutAt(mapLocation, calloutDef);
}
}

EPPlus Array dimensions exceeded supported range. System.OutOfMemoryException

Ok so I am trying to load a CSVStream into an ExcelPackage (I am using EPPlus).
It always fails at line 221482, no matter what option I choose. I am running on x64 and I have in my app.config...
The error given is the one from the title :(
public ExcelPackage ExcelPackageFromCsvStream(Stream csvStream)
{
var excelPackage = new ExcelPackage();
var workSheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] { eDataTypes.String }
};
using (var sr = new StreamReader(csvStream))
{
int i = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
workSheet.Cells["A" + i].LoadFromText(line, csvFormat);
i++;
}
}
return excelPackage;
}
Resolved it by creating multiple ExcelPackages and also I've read the stream in batches (e.g. 200k lines at once)
public List<ExcelPackage> ExcelPackagesFromCsvStream(Stream csvStream, int batchSize)
{
var excelPackages = new List<ExcelPackage>();
int currentPackage = -1; // so that first package will have the index 0
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] {eDataTypes.String}
};
using (var sr = new StreamReader(csvStream))
{
int index = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
if ((index - 1) % batchSize == 0)
{
var excelPackage = new ExcelPackage();
excelPackage.Workbook.Worksheets.Add("Sheet1");
excelPackages.Add(excelPackage);
currentPackage++;
index = 1;
}
excelPackages[currentPackage].Workbook.Worksheets.First().Cells["A" + index].LoadFromText(line, csvFormat);
index++;
}
}
return excelPackages;
}

Validating a phone number using ASP.NET and the Twilio API

I'm trying to check whether numbers are valid using the code below. Will this work?
try
{
TwilioRest.Account account = new TwilioRest.Account(TwilioRest.TwilioConstants.ACCOUNT_SID, TwilioRest.TwilioConstants.ACCOUNT_TOKEN);
string strResponse = account.request(String.Format("/{0}/Accounts/{1}/OutgoingCallerIds", TwilioRest.TwilioConstants.API_VERSION, TwilioRest.TwilioConstants.ACCOUNT_SID), "GET");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
XmlNode root = xmlDoc.DocumentElement.ChildNodes[0];
int cont = 0;
if (root.ChildNodes.Count > 0)
{
for (int i = 0; i < root.ChildNodes.Count; i++)
{
string ss = root.ChildNodes[i].SelectSingleNode("PhoneNumber").ChildNodes[0].Value;
if (phoneno.Trim() == ss)
{
cont = 1;
break;
}
}
}
if (cont == 0)
{
btnSubmit.Visible = true;
}
}
catch (TwilioRest.TwilioRestException ex)
{
mpValidatePhone.Show();
ucMsgPhone.MessageType = MessageType.Error;
ucMsgPhone.Text = TwilioErrorMessage(ex.ToString());
}
try like this....
string strResponse = account.request(String.Format("/{0}/Accounts/{1}/OutgoingCallerIds",
TwilioRest.TiwlioConstants.API_VERSION, TwilioRest.TiwlioConstants.ACCOUNT_SID), "GET");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
XmlNode root = xmlDoc.DocumentElement.ChildNodes[0];
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes[0])
{
string nodeVal = node.SelectSingleNode("PhoneNumber").ChildNodes[0].Value.ToString();
string fonVal = foneCountryCode + PhoneNumber.Replace("-", "");
//if (node.SelectSingleNode("PhoneNumber").ChildNodes[0].Value == "+" + PhoneNumber.Replace("-", ""))
if(nodeVal == fonVal)
{
result = true;
break;
}
}

How to set the next activity from the current automated activity?

I am trying to decide the next activity from the current activity (Automatic decision activity)The below is my code. How to set the next activity?
public void DebugUserCheck(string workitemid)
{
CoreServiceSession client = new CoreServiceSession();
SessionAwareCoreServiceClient csClient = client.GetClient();
var readoption = new ReadOptions();
WorkItemData workitem = (WorkItemData)csClient.Read(workitemid, readoption);
ActivityInstanceData currentactivity = (ActivityInstanceData)csClient.Read(workitem.Activity.IdRef, readoption);
TridionActivityDefinitionData activitydefinition = (TridionActivityDefinitionData)csClient.Read(currentactivity.ActivityDefinition.IdRef, readoption);
ProcessDefinitionData processdefinition = (ProcessDefinitionData)csClient.Read(activitydefinition.ProcessDefinition.IdRef, readoption);
IList<ActivityDefinitionData> activityDefinitions = new List<ActivityDefinitionData>(processdefinition.ActivityDefinitions);
string superuseractivitytitle = "";
string superuseractivityid = "";
string normaluseractivitytitle = "";
string normaluseractivityid = "";
foreach (var activity in activityDefinitions)
{
if (activity.Title == "Override")
{
superuseractivitytitle = activity.Title;
superuseractivityid = activity.Id;
}
if (activity.Title == "Author Decision")
{
normaluseractivitytitle = activity.Title;
normaluseractivityid = activity.Id;
}
}
UserData user = csClient.GetCurrentUser();
if (user.Id == "tcm:0-141-65552")
{
ActivityDefinitionData nextactivity = (ActivityDefinitionData)csClient.Read(superuseractivityid, readoption);
ActivityFinishData finishdata = new ActivityFinishData();
finishdata.Message = "Automatic decision activity finished";
csClient.FinishActivity(currentactivity.Id, finishdata, readoption);
}
else
{
ActivityDefinitionData nextactivity = (ActivityDefinitionData)csClient.Read(normaluseractivityid, readoption);
ActivityFinishData finishdata = new ActivityFinishData();
finishdata.Message = "Automatic decision activity finished";
csClient.FinishActivity(currentactivity.Id, finishdata, readoption);
}
}
Instead of ActivityFinishData use DecisionActivityFinishData
var decisionActivityFinishData = new DecisionActivityFinishData
{
NextActivity = new LinkToActivityDefinitionData{IdRef = "next activity ID"}
};
csClient.FinishActivity(currentactivity.Id, decisionActivityFinishData,
readoption);

Resources