C# - System.FormatException SQLite connection - c#

I am experiencing an error that I cannot understand, can anyone explain to me what I am miserably doing wrong?
Database Table:
CREATE TABLE "posti_auto_mil" (
"n_posto" TEXT NOT NULL UNIQUE,
"id_utente" INTEGER NOT NULL,
"targa_1" TEXT NOT NULL,
"targa_2" TEXT NOT NULL,
"targa_3" TEXT NOT NULL,
"targa_4" TEXT NOT NULL,
"targa_5" TEXT NOT NULL,
"locazione" TEXT NOT NULL
);
LoadCar.cs
public static bool CheckTarga(int idUtente)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var output = cnn.Query($"select * from utenti where id = {idUtente}").FirstOrDefault();
if (output != null)
{
var targa = cnn.Query($"select * from posti_auto_mil where id = {idUtente}").FirstOrDefault();
if (targa != null)
{
var checkpresenza = cnn.Query($"select locazione from posti_auto_mil where id_utente = {idUtente} limit 1");
if (checkpresenza.ToString() == "interno")
{
targaicon = 1;
}
else if (checkpresenza.ToString() == "esterno")
{
targaicon = 2;
}
else if (checkpresenza.ToString() == "provvisorio")
{
targaicon = 2;
}
else targaicon = 3;
}
return true;
}
else
{
targaicon = 3;
return false;
}
}
Form1.cs
//Parking
//Visibilità
listView_targheinfo.Items.Clear();
listView_targheinfo.Visible = true;
pictureBox_infobox.Visible = true;
if (Classi.LoadCar.CheckTarga(Int32.Parse(home_textBox_id.Text)) == true)
{
if (Classi.LoadCar.targaicon == 1)
{
pictureBox_infobox.BackgroundImage = global::RegistroAccessi_8Rgt.Properties.Resources.parking_32px_green;
}
else if (Classi.LoadCar.targaicon == 2)
{
pictureBox_infobox.BackgroundImage = global::RegistroAccessi_8Rgt.Properties.Resources.no_parking_32px;
}
else if (Classi.LoadCar.targaicon == 3)
{
pictureBox_infobox.BackgroundImage = global::RegistroAccessi_8Rgt.Properties.Resources.parking_32px_yellow;
}
else
{
pictureBox_infobox.BackgroundImage = global::RegistroAccessi_8Rgt.Properties.Resources.no_parking_32px;
}
}
else
{
pictureBox_infobox.BackgroundImage = global::RegistroAccessi_8Rgt.Properties.Resources.no_parking_32px;
}
Error:
I've done various tests but I don't understand what I'm doing wrong... can someone clarify this for me?
I can do a personnel search in the same way but I can't do it for vehicle number plates.

Related

Invalid Data in Excel File. Index was outside the bounds of the array.C#

Cant find answer in any of the suggestions.I am trying to upload an excel file to the postgre Db.
Here is the C# code :
public static List<Common.Transactions.TransactionDetail> GetTransactionDetails(string path)
{
if (!File.Exists(path))
{
return null;
}
var transactionDetails = new List<Common.Transactions.TransactionDetail>();
foreach (var sheet in Workbook.Worksheets(path))
{
int officeId = 0;
foreach (var row in sheet.Rows.Skip(1))
{
var td = new Common.Transactions.TransactionDetail
{
GlAccountId = Core.GlAccounts.GetGlAcccountId(row.Cells[1]?.Text),
AccountNumberId = Deposit.AccountHolders.GetAccountNumberId(row.Cells[2]?.Text),
ShareAccountId = Core.ShareAccounts.GetShareAccountId(row.Cells[3]?.Text),
LoanId = Loan.LoanAccounts.GetLoanId(row.Cells[4]?.Text),
Debit = row.Cells[5]?.Text.ToDecimal(),
Credit = row.Cells[6]?.Text.ToDecimal(),
StatementReference = row.Cells[7]?.Text
};
if (row.Cells[7] != null)
{
td.OfficeId = Office.Offices.GetOfficeIdByCode(row.Cells[7]?.Text);
officeId = Office.Offices.GetOfficeIdByCode(row.Cells[7]?.Text);
}
if (td.AccountNumberId == 0)
{
td.AccountNumberId = null;
}
if (td.LoanId == 0)
{
td.LoanId = null;
}
if (td.ShareAccountId == 0)
{
td.ShareAccountId = null;
}
if (row.Cells[0] != null)
{
td.AccountName = row.Cells[0].Text;
}
if (row.Cells[1] != null && string.IsNullOrWhiteSpace(td.AccountName))
{
td.AccountName = row.Cells[1].Text;
}
if (row.Cells[2] != null && string.IsNullOrWhiteSpace(td.AccountName))
{
td.AccountName = row.Cells[2].Text;
}
if (row.Cells[3] != null && string.IsNullOrWhiteSpace(td.AccountName))
{
td.AccountName = row.Cells[3].Text;
}
#region OfficeId
if (td.AccountNumberId != null)
{
officeId = Deposit.AccountHolders.GetAccountOfficeId(td.AccountNumberId.ToLong());
}
if (td.LoanId != null)
{
officeId = Loan.LoanGrant.GetAccountOfficeId(td.LoanId.ToLong());
}
if (td.ShareAccountId != null)
{
officeId = Core.ShareAccounts.GetAccountOfficeId(td.ShareAccountId.ToLong());
}
#endregion
td.OfficeId = officeId != 0 ? officeId : SessionHelper.GetOfficeId();
td.OfficeCode = Office.Offices.GetOfficeCode(officeId);
transactionDetails.Add(td);
}
}
foreach (var detail in transactionDetails)
{
if (detail.Debit.ToDecimal() > 0 && detail.Credit > 0)
{
throw new TransactionDetailException(
$#"Invalid transaction. Either debit or credit should be null for '{detail.AccountName}'.");
}
if (detail.AccountNumberId > 0)
{
if (detail.Debit.ToDecimal() > 0)
{
if (detail.Debit > Deposit.AccountHolders.GetDepositAccountBalance(detail.AccountNumberId.ToLong()))
{
throw new TransactionDetailException(
$#"Insufficient balance in account '{detail.AccountName}'.");
}
}
detail.GlAccountId = Deposit.AccountHolders.GetGlAccountId(detail.AccountNumberId);
}
if (detail.ShareAccountId > 0)
{
if (detail.Debit.ToDecimal() > 0)
{
if (detail.Debit > Core.ShareAccounts.GetShareBalance(detail.ShareAccountId.ToLong()))
{
throw new TransactionDetailException(
$#"Insufficient balance in account '{detail.AccountName}'.");
}
}
detail.GlAccountId = Core.ShareAccounts.GetGlAccountId(detail.ShareAccountId.ToLong());
}
if (detail.LoanId > 0)
{
if (detail.Credit.ToDecimal() > 0)
{
if (detail.Credit > Loan.LoanAccounts.GetLoanCollectionBalance(detail.LoanId.ToLong(), Core.DateConversion.GetCurrentServerDate()))
{
throw new TransactionDetailException(
$#"Insufficient balance in account '{detail.AccountName}'.");
}
}
detail.GlAccountId = Loan.LoanGrant.GetLoanTransactionGLAccountId(detail.LoanId.ToLong());
}
detail.AuditUserId = Common.Helpers.SessionHelper.GetUserId();
detail.AccountNumberId = detail.AccountNumberId <= 0 ? null : detail.AccountNumberId;
detail.LoanId = detail.LoanId <= 0 ? null : detail.LoanId;
detail.ShareAccountId = detail.ShareAccountId <= 0 ? null : detail.ShareAccountId;
detail.EnableDeleteButton = true;
if (detail.GlAccountId == 0)
{
throw new TransactionDetailException($#"{detail.AccountName} is not a valid account.");
}
}
return transactionDetails;
}
}
I get error Index was outside the bounds of array.Invalid excel data.
My excel data
Gl Account Deposit A/C Share A/C Loan A/C Debit Credit Statement Reference
Loss Recovery Fund 0 1000 uploaded from excel
Risk Coverage Fund 0 1106 uploaded from excel
Ok solved it..The problem was with my excel data.
I was looking for row[7] which didnt exist.Had to add one column to the
excel file and it worked.
The exception was here in the code :
if (row.Cells[7] != null)
{
td.OfficeId = Office.Offices.GetOfficeIdByCode(row.Cells[7]?.Text);
officeId = Office.Offices.GetOfficeIdByCode(row.Cells[7]?.Text);
}
Thanks #LocEngineer Sir for your time.

How to defer the update at the client side after async postback in updatepanel

I have an old system which uses UpdatePanels of asp.net
After the postback is completed, we know that the inside of UpdatePanel is updated
Can i delay this update somehow on the client side ? is that possible?
So it will be like, when the postback is started, i set a javascript datetime object on the client side
Once the postback is completed, and the data is returned from the server, before updating the client side interface, i check how many miliseconds has passed and I delay the update of the client side until certain miliseconds has passed
is this possible?
asp.net 4.5 c#
let me clarify better
i want each update of the page to be exactly 500 miliseconds after the ajax postback request started
however the server delay is unknown and changes for the every location
let say that for person 1 the server delay is 122 ms
for person 2 the server delay is 234
for person 3 the server delay is 444
so i would be have to delay the page update at the client side
for the person 1 : 378 ms
for the person 2 : 266 ms
for the person 3 : 56 ms
i have checked and i found that there is a function :
Sys.WebForms.PageRequestManager pageLoading Event
so if i can somehow override the function that this function calls to update the page i can achieve
(i still dont know what function it calls to complete the update operation on the client side)
lets assume that inside
Sys.WebForms.PageRequestManager pageLoading Event
updateTheChanges function is called
so if i can override this updateTheChanges function and call it with a delay i can achieve what i want
I need exactly something like this which will overwrite the update function of the updatepanel. So i can call this function with a delay
ASP.Net Webforms w/ AJAX Slow Rendering
ty
here the web resource files
script resource 1 : http://pastebin.com/0rSCMn3g
script resource 2 : http://pastebin.com/GvqwpPv8
script resource 3 below
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) {
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options) {
var validationResult = true;
if (options.validation) {
if (typeof(Page_ClientValidate) == 'function') {
validationResult = Page_ClientValidate(options.validationGroup);
}
}
if (validationResult) {
if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) {
theForm.action = options.actionUrl;
}
if (options.trackFocus) {
var lastFocus = theForm.elements["__LASTFOCUS"];
if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) {
if (typeof(document.activeElement) == "undefined") {
lastFocus.value = options.eventTarget;
} else {
var active = document.activeElement;
if ((typeof(active) != "undefined") && (active != null)) {
if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) {
lastFocus.value = active.id;
} else if (typeof(active.name) != "undefined") {
lastFocus.value = active.name;
}
}
}
}
}
}
if (options.clientSubmit) {
__doPostBack(options.eventTarget, options.eventArgument);
}
}
var __pendingCallbacks = new Array();
var __synchronousCallBackIndex = -1;
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {
var postData = __theFormPostData +
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
if (theForm["__EVENTVALIDATION"]) {
postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
}
var xmlRequest, e;
try {
xmlRequest = new XMLHttpRequest();
} catch (e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader);
} catch (e) {}
var callback = new Object();
callback.eventCallback = eventCallback;
callback.context = context;
callback.errorCallback = errorCallback;
callback.async = useAsync;
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex] = null;
}
__synchronousCallBackIndex = callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange = WebForm_CallbackComplete;
callback.xmlRequest = xmlRequest;
// e.g. http:
var action = theForm.action || document.location.pathname,
fragmentIndex = action.indexOf('#');
if (fragmentIndex !== -1) {
action = action.substr(0, fragmentIndex);
}
if (!__nonMSDOMBrowser) {
var queryIndex = action.indexOf('?');
if (queryIndex !== -1) {
var path = action.substr(0, queryIndex);
if (path.indexOf("%") === -1) {
action = encodeURI(path) + action.substr(queryIndex);
}
} else if (action.indexOf("%") === -1) {
action = encodeURI(action);
}
}
xmlRequest.open("POST", action, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xmlRequest.send(postData);
return;
}
callback.xmlRequest = new Object();
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
var xmlRequestFrame = document.frames[callbackFrameID];
if (!xmlRequestFrame) {
xmlRequestFrame = document.createElement("IFRAME");
xmlRequestFrame.width = "1";
xmlRequestFrame.height = "1";
xmlRequestFrame.frameBorder = "0";
xmlRequestFrame.id = callbackFrameID;
xmlRequestFrame.name = callbackFrameID;
xmlRequestFrame.style.position = "absolute";
xmlRequestFrame.style.top = "-100px"
xmlRequestFrame.style.left = "-100px";
try {
if (callBackFrameUrl) {
xmlRequestFrame.src = callBackFrameUrl;
}
} catch (e) {}
document.body.appendChild(xmlRequestFrame);
}
var interval = window.setInterval(function() {
xmlRequestFrame = document.frames[callbackFrameID];
if (xmlRequestFrame && xmlRequestFrame.document) {
window.clearInterval(interval);
xmlRequestFrame.document.write("");
xmlRequestFrame.document.close();
xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
xmlRequestFrame.document.close();
xmlRequestFrame.document.forms[0].action = theForm.action;
var count = __theFormPostCollection.length;
var element;
for (var i = 0; i < count; i++) {
element = __theFormPostCollection[i];
if (element) {
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
fieldElement.type = "hidden";
fieldElement.name = element.name;
fieldElement.value = element.value;
xmlRequestFrame.document.forms[0].appendChild(fieldElement);
}
}
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIdFieldElement.type = "hidden";
callbackIdFieldElement.name = "__CALLBACKID";
callbackIdFieldElement.value = eventTarget;
xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement);
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackParamFieldElement.type = "hidden";
callbackParamFieldElement.name = "__CALLBACKPARAM";
callbackParamFieldElement.value = eventArgument;
xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement);
if (theForm["__EVENTVALIDATION"]) {
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackValidationFieldElement.type = "hidden";
callbackValidationFieldElement.name = "__EVENTVALIDATION";
callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value;
xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement);
}
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIndexFieldElement.type = "hidden";
callbackIndexFieldElement.name = "__CALLBACKINDEX";
callbackIndexFieldElement.value = callbackIndex;
xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement);
xmlRequestFrame.document.forms[0].submit();
}
}, 10);
}
function WebForm_CallbackComplete() {
for (var i = 0; i < __pendingCallbacks.length; i++) {
callbackObject = __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex = -1;
}
__pendingCallbacks[i] = null;
var callbackFrameID = "__CALLBACKFRAME" + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
WebForm_ExecuteCallback(callbackObject);
}
}
}
function WebForm_ExecuteCallback(callbackObject) {
var response = callbackObject.xmlRequest.responseText;
if (response.charAt(0) == "s") {
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(1), callbackObject.context);
}
} else if (response.charAt(0) == "e") {
if ((typeof(callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) {
callbackObject.errorCallback(response.substring(1), callbackObject.context);
}
} else {
var separatorIndex = response.indexOf("|");
if (separatorIndex != -1) {
var validationFieldLength = parseInt(response.substring(0, separatorIndex));
if (!isNaN(validationFieldLength)) {
var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
if (validationField != "") {
var validationFieldElement = theForm["__EVENTVALIDATION"];
if (!validationFieldElement) {
validationFieldElement = document.createElement("INPUT");
validationFieldElement.type = "hidden";
validationFieldElement.name = "__EVENTVALIDATION";
theForm.appendChild(validationFieldElement);
}
validationFieldElement.value = validationField;
}
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(separatorIndex + validationFieldLength + 1), callbackObject.context);
}
}
}
}
}
function WebForm_FillFirstAvailableSlot(array, element) {
var i;
for (i = 0; i < array.length; i++) {
if (!array[i]) break;
}
array[i] = element;
return i;
}
var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1);
var __theFormPostData = "";
var __theFormPostCollection = new Array();
var __callbackTextTypes = /^(text|password|hidden|search|tel|url|email|number|range|color|datetime|date|month|week|time|datetime-local)$/i;
function WebForm_InitCallback() {
var formElements = theForm.elements,
count = formElements.length,
element;
for (var i = 0; i < count; i++) {
element = formElements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((__callbackTextTypes.test(type) || ((type == "checkbox" || type == "radio") && element.checked)) && (element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
} else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
} else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&";
}
function WebForm_EncodeCallback(parameter) {
if (encodeURIComponent) {
return encodeURIComponent(parameter);
} else {
return escape(parameter);
}
}
var __disabledControlArray = new Array();
function WebForm_ReEnableControls() {
if (typeof(__enabledControlArray) == 'undefined') {
return false;
}
var disabledIndex = 0;
for (var i = 0; i < __enabledControlArray.length; i++) {
var c;
if (__nonMSDOMBrowser) {
c = document.getElementById(__enabledControlArray[i]);
} else {
c = document.all[__enabledControlArray[i]];
}
if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) {
c.disabled = false;
__disabledControlArray[disabledIndex++] = c;
}
}
setTimeout("WebForm_ReDisableControls()", 0);
return true;
}
function WebForm_ReDisableControls() {
for (var i = 0; i < __disabledControlArray.length; i++) {
__disabledControlArray[i].disabled = true;
}
}
function WebForm_SimulateClick(element, event) {
var clickEvent;
if (element) {
if (element.click) {
element.click();
} else {
clickEvent = document.createEvent("MouseEvents");
clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
if (!element.dispatchEvent(clickEvent)) {
return true;
}
}
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
return false;
}
return true;
}
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (src &&
((src.tagName.toLowerCase() == "input") &&
(src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")) ||
((src.tagName.toLowerCase() == "a") &&
(src.href != null) && (src.href != "")) ||
(src.tagName.toLowerCase() == "textarea")) {
return true;
}
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
} else {
defaultButton = document.all[target];
}
if (defaultButton) {
return WebForm_SimulateClick(defaultButton, event);
}
}
return true;
}
function WebForm_GetScrollX() {
if (__nonMSDOMBrowser) {
return window.pageXOffset;
} else {
if (document.documentElement && document.documentElement.scrollLeft) {
return document.documentElement.scrollLeft;
} else if (document.body) {
return document.body.scrollLeft;
}
}
return 0;
}
function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
return window.pageYOffset;
} else {
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
} else if (document.body) {
return document.body.scrollTop;
}
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
if (__nonMSDOMBrowser) {
theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
} else {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
}
if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
return this.oldSubmit();
}
return true;
}
function WebForm_SaveScrollPositionOnSubmit() {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) {
return this.oldOnSubmit();
}
return true;
}
function WebForm_RestoreScrollPosition() {
if (__nonMSDOMBrowser) {
window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
} else {
window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
}
if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
return theForm.oldOnLoad();
}
return true;
}
function WebForm_TextBoxKeyHandler(event) {
if (event.keyCode == 13) {
var target;
if (__nonMSDOMBrowser) {
target = event.target;
} else {
target = event.srcElement;
}
if ((typeof(target) != "undefined") && (target != null)) {
if (typeof(target.onchange) != "undefined") {
target.onchange();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}
function WebForm_TrimString(value) {
return value.replace(/^\s+|\s+$/g, '')
}
function WebForm_AppendToClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index === -1) {
element.className = (element.className === '') ? className : element.className + ' ' + className;
}
}
function WebForm_RemoveClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index >= 0) {
element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' +
currentClassName.substring(index + className.length + 1, currentClassName.length));
}
}
function WebForm_GetElementById(elementId) {
if (document.getElementById) {
return document.getElementById(elementId);
} else if (document.all) {
return document.all[elementId];
} else return null;
}
function WebForm_GetElementByTagName(element, tagName) {
var elements = WebForm_GetElementsByTagName(element, tagName);
if (elements && elements.length > 0) {
return elements[0];
} else return null;
}
function WebForm_GetElementsByTagName(element, tagName) {
if (element && tagName) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(tagName);
}
if (element.all && element.all.tags) {
return element.all.tags(tagName);
}
}
return null;
}
function WebForm_GetElementDir(element) {
if (element) {
if (element.dir) {
return element.dir;
}
return WebForm_GetElementDir(element.parentNode);
}
return "ltr";
}
function WebForm_GetElementPosition(element) {
var result = new Object();
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
if (element.offsetParent) {
result.x = element.offsetLeft;
result.y = element.offsetTop;
var parent = element.offsetParent;
while (parent) {
result.x += parent.offsetLeft;
result.y += parent.offsetTop;
var parentTagName = parent.tagName.toLowerCase();
if (parentTagName != "table" &&
parentTagName != "body" &&
parentTagName != "html" &&
parentTagName != "div" &&
parent.clientTop &&
parent.clientLeft) {
result.x += parent.clientLeft;
result.y += parent.clientTop;
}
parent = parent.offsetParent;
}
} else if (element.left && element.top) {
result.x = element.left;
result.y = element.top;
} else {
if (element.x) {
result.x = element.x;
}
if (element.y) {
result.y = element.y;
}
}
if (element.offsetWidth && element.offsetHeight) {
result.width = element.offsetWidth;
result.height = element.offsetHeight;
} else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
result.width = element.style.pixelWidth;
result.height = element.style.pixelHeight;
}
return result;
}
function WebForm_GetParentByTagName(element, tagName) {
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName)) {
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
function WebForm_SetElementHeight(element, height) {
if (element && element.style) {
element.style.height = height + "px";
}
}
function WebForm_SetElementWidth(element, width) {
if (element && element.style) {
element.style.width = width + "px";
}
}
function WebForm_SetElementX(element, x) {
if (element && element.style) {
element.style.left = x + "px";
}
}
function WebForm_SetElementY(element, y) {
if (element && element.style) {
element.style.top = y + "px";
}
}
Here is a way to delay the UpdatePanel refresh without freezing the user interface:
In the pageLoading event handler, save the ID and the previous HTML of the panels to be updated
In the pageLoad event handler, save the new HTML of the panels but replace it by the old one
After the delay expires, set the new HTML in the updated panels
Here is the client code:
<script type="text/javascript">
var updateTime = 0;
var updatedPanelArray = [];
function setUpdateTime() {
updateTime = new Date(Date.now() + 500);
}
function pageLoading(sender, e) {
updatedPanelArray.length = 0;
var panels = e.get_panelsUpdating();
for (var i = 0; i < panels.length; i++) {
var pnl = panels[i];
updatedPanelArray.push({ id: pnl.id, oldHTML: pnl.innerHTML });
}
}
function pageLoad(sender, e) {
if (e.get_isPartialLoad()) {
for (var i = 0; i < updatedPanelArray.length; i++) {
var updatedPanel = updatedPanelArray[i];
var pnl = document.getElementById(updatedPanel.id);
updatedPanel.newHTML = pnl.innerHTML;
pnl.innerHTML = updatedPanel.oldHTML;
setTimeout(refreshUpdatePanel, updateTime - Date.now());
}
}
}
function refreshUpdatePanel() {
for (var i = 0; i < updatedPanelArray.length; i++) {
var updatedPanel = updatedPanelArray[i];
var pnl = document.getElementById(updatedPanel.id);
pnl.innerHTML = updatedPanel.newHTML;
}
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoading);
</script>
The update time is set before triggering the asynchronous postback:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblUpdatePanel1" runat="server" />
<asp:Button ID="btnUpdatePanel" runat="server" OnClientClick="setUpdateTime();" OnClick="btnUpdatePanel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
It can be tested with the following event handler in code-behind (suggestion: set the delay to 5000 ms in the Javascript code to make it obvious):
protected void btnUpdatePanel_Click(object sender, EventArgs e)
{
lblUpdatePanel1.Text = DateTime.Now.ToString();
}
If you don't mind the user interface being frozen while waiting, you can delay the refresh by keeping the pageLoad event handler busy until the delay expires:
<script type="text/javascript">
var updateTime = 0;
function setUpdateTime() {
updateTime = new Date(Date.now() + 500);
}
function pageLoad(sender, e) {
if (e.get_isPartialLoad()) {
while (Date.now() < updateTime) {
// Loop until the delay expires
}
}
}
</script>
You can initialize the update time before triggering the asynchronous postback:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<asp:Button ID="btn1" runat="server" OnClientClick="setUpdateTime();" ... />
</ContentTemplate>
</asp:UpdatePanel>
Use UpdatePanel.UpdateMode Property to gets or sets a value that indicates when an UpdatePanel control's content is updated. For more details visit this link.
You could delay the server side, so all the delays would be more or less equals for everyone.
If this is not an option, you could have a hidden field inside the update panel (or somewhere else). The function that handles the update (in the server side) would calculate the time it took execute, and before finishing, would update this hidden field. Now back in the client side, check the value of this field and calculate the difference between this value and yours 500ms. You could use datetimes or milliseconds.
It's not the prettiest solution but imho, this is not a frequent problem that people want to handle (in fact, I dont think that you should delay a faster response to the slowest one)

How to add a TextField if there is already an existing TextField in ABCPDF?

It's fairly straight-forward to add a TextField using ABCPDF:
public FormField AddTextField(string inRect, string inName, string inText)
{
int fieldId = mDoc.AddObject("<</Type /Annot /Subtype /Widget /F 4 /FT /Tx /Ff 4096 /Q 1>>");
mDoc.SetInfo(fieldId, "/V:Text", inText);
RegisterField(fieldId, inName, inRect);
return new FormField(fieldId, mDoc);
}
With this as the implementation:
FormField text = AddTextField("40 530 300 580", "TextField1", "Hello World!");
text.DefaultAppearance = "/TimesRoman 36 Tf 0 0 1 rg";
text.BorderColor = "0 0 0";
text.FillColor = "220 220 220";
text.TextAlign = "Left";
If I need to add two fields that have the same name, it's a little more complex:
public int AddGroupField(FormField[] inKids, string inName, string inValue)
{
if (inKids.Length == 0)
throw new Exception("Cannot have a group field with no kids");
string ft = null, dv = null;
int fieldId = mDoc.AddObject("<< /Kids [] >>");
foreach (FormField kid in inKids)
{
mDoc.SetInfo(fieldId, "/Kids[]:Ref", kid.Id.ToString());
mDoc.SetInfo(kid.Id, "/Parent:Ref", fieldId);
if (ft == null)
ft = mDoc.GetInfo(kid.Id, "/FT");
if (dv == null)
dv = mDoc.GetInfo(kid.Id, "/DV");
mDoc.SetInfo(kid.Id, "/FT:Del", "");
mDoc.SetInfo(kid.Id, "/V:Del", "");
mDoc.SetInfo(kid.Id, "/DV:Del", "");
}
mDoc.SetInfo(fieldId, "/FT", ft);
mDoc.SetInfo(fieldId, "/T:Text", inName);
mDoc.SetInfo(fieldId, "/V:Text", inValue);
if (dv != null)
mDoc.SetInfo(fieldId, "/DV:Text", dv);
int eid = mDoc.GetInfoInt(mDoc.Root, "/AcroForm:Ref");
mDoc.SetInfo(eid, "/Fields*[]:Ref", fieldId);
return fieldId;
}
With this as the implementation:
FormField[] kids = new FormField[2];
kids[0] = AddTextField("40 230 300 280", null, null);
kids[1] = AddTextField("40 170 300 220", null, null);
int id = AddGroupField(kids, "TextField1", "Hello World!");
However, I'm having issues with adding a TextField to a PDF where a TextField already exists with that same name. So, for example, if my PDF already has a field named "TextField1" and then I want to add another field with that same name, none of the above implementations will work.
I was able to get the answer from ABCPDF support. And as you can see, it's not exactly a simple process. I'm not sure anyone could just figure this out on their own without spending months and months of research on the PDF spec and the ABCPDF product.
public FormField AddTextField(string inRect, string inName, string inText)
{
bool fieldAlreadyExists = mDoc.Form[inName] != null;
int fieldId = mDoc.AddObject("<</Type /Annot /Subtype /Widget /F 4 /FT /Tx /Ff 4096 /Q 1>>");
mDoc.SetInfo(fieldId, "/V:Text", inText);
RegisterField(fieldId, inName, inRect);
var field = new FormField(fieldId, mDoc);
if (fieldAlreadyExists)
{
InteractiveForm form = new InteractiveForm(mDoc);
form.AddFieldIntoExistingGroup(field, true);
}
return field;
}
private bool AddFieldIntoExistingGroup(FormField field, bool refreshForm)
{
bool duplicatesFound = false;
int acroFormID = mDoc.GetInfoInt(mDoc.Root, "/AcroForm:Ref");
int parentID = mDoc.GetInfoInt(field.Id, "/Parent:Ref");
ArrayAtom kids;
if (parentID > 0)
{
kids = mDoc.ObjectSoup.Catalog.Resolve(Atom.GetItem(mDoc.ObjectSoup[parentID].Atom, "Kids")) as ArrayAtom;
}
else
{
kids = mDoc.ObjectSoup.Catalog.Resolve(Atom.GetItem(mDoc.ObjectSoup[acroFormID].Atom, "Fields")) as ArrayAtom;
}
Dictionary<string, List<IndirectObject>> items = new Dictionary<string, List<IndirectObject>>();
for (int i = 0; i < kids.Count; i++)
{
IndirectObject io = mDoc.ObjectSoup.Catalog.ResolveObj(kids[i]);
if (io == null)
{
continue; // shouldn't really happen
}
string name = mDoc.GetInfo(io.ID, "/T:Text");
if (!items.ContainsKey(name))
{
items[name] = new List<IndirectObject>();
}
items[name].Add(io);
}
foreach (KeyValuePair<string, List<IndirectObject>> pair in items)
{
if (pair.Value.Count > 1)
{
duplicatesFound = true;
// shift field down to be a child of a new field node
int id = mDoc.AddObject("<< >>");
if (parentID > 0)
{
mDoc.SetInfo(parentID, "/Kids[]:Ref", id);
mDoc.SetInfo(id, "/Parent:Ref", parentID);
}
else
{
mDoc.SetInfo(acroFormID, "/Fields[]:Ref", id);
}
string[] dictEntries = new[] { "/FT", "/T", "/TU", "/Ff", "/V", "/DV" };
foreach (IndirectObject io in pair.Value)
{
foreach (string dictEntry in dictEntries)
{
string val = mDoc.GetInfo(io.ID, dictEntry);
if (!string.IsNullOrEmpty(val))
{
mDoc.SetInfo(id, dictEntry, val);
mDoc.SetInfo(io.ID, dictEntry + ":Del", "");
}
}
ArrayRemoveOneRefAtom(kids, io.ID);
mDoc.SetInfo(id, "/Kids[]:Ref", io.ID);
mDoc.SetInfo(io.ID, "/Parent:Ref", id);
}
}
}
if ((refreshForm) && (duplicatesFound))
{
mDoc.Form.Refresh();
}
return duplicatesFound;
}
private static bool ArrayRemoveOneRefAtom(ArrayAtom array, int id)
{
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
RefAtom refAtom = array[i] as RefAtom;
if ((refAtom != null) && (refAtom.ID == id))
{
ArrayRemoveAt(array, i);
return true;
}
}
}
return false;
}
private static void ArrayRemoveAt(ArrayAtom array, int index)
{
if (index == 0)
{ // Workaround for bug in some versions of ABCpdf
Atom[] copy = new Atom[array.Count];
array.CopyTo(copy, 0);
array.Clear();
for (int i = 1; i < copy.Length; i++)
array.Add(copy[i]);
}
else
{
array.RemoveAt(index);
}
}

mailmerge with visto how to get each record of MailMerge.DataSource.DataFields

I' have a Project that needs to do a mailmerge, I'm performing this with VSTO. I need to check if all records on the MailMerge.DataSource.DataFields are ok. i'm doing that with this code.
public void verificarPersonas(Word.Document Doc)
{
ThisAddIn ThisAddIn = Globals.ThisAddIn;
List<Personas> miListaPersonas = new List<Personas>();
decimal nRecords = Doc.MailMerge.DataSource.RecordCount;
if (nRecords == 0)
{
cambiarEstado("Empty db or documento does'n prepared for mail merge", false);
}
else
{
string fieldIdentificacion = persParm("Identificacion");
string fieldNombre = persParm("Nombres");
string fieldApellido = persParm("Apellidos");
string fieldEmail = persParm("Email");
string fieldDireccion = persParm("Direccion");
string fieldTelefono = persParm("Telefono");
if (String.IsNullOrEmpty(fieldIdentificacion) || String.IsNullOrEmpty(fieldNombre))
{
cambiarEstado("", false);
return;
}
else
{
for (int i = 1; i <= nRecords; i++)
{
Doc.MailMerge.DataSource.FirstRecord = i;
Doc.MailMerge.DataSource.LastRecord = i;
// Here Allways get the first record
dynamic fields = Doc.MailMerge.DataSource.DataFields;
// ________________________________
Personas personaActual = new Personas();
personaActual.IdPersona = 0;
try
{
personaActual.Identificacion = fields(fieldIdentificacion).value;
personaActual.Nombres = fields(fieldNombre).value;
personaActual.Apellidos = (String.IsNullOrEmpty(fieldApellido) ? "" : fields(fieldApellido).value);
personaActual.Email = (String.IsNullOrEmpty(fieldEmail) ? "" : fields(fieldEmail).value);
personaActual.Direccion = (String.IsNullOrEmpty(fieldDireccion) ? "" : fields(fieldDireccion).value);
personaActual.Telefono = (String.IsNullOrEmpty(fieldTelefono) ? "" : fields(fieldTelefono).value);
miListaPersonas.Add(personaActual);
}
catch (Exception e)
{
cambiarEstado(""+e.Message, false);
return;
}
}
string listaPersonasJson = JsonConvert.SerializeObject(miListaPersonas);
string respuesta = wt.getWebData("Personas", "verificarPersonasVSTO", new { personas = listaPersonasJson });
}
}
}
My problem is that dynamic fields = Doc.MailMerge.DataSource.DataFields; allways get the first record.
How can I do to get datafields for the active record ?
After some hours of research and some tries. get that the fields collection of datasource dont move the pointer when you set FirstRecord and Lastrecord, it must be moved using activerecords, using WdMailMergeActiveRecord enumeration, sonething like this:
int nRecords = Doc.MailMerge.DataSource.RecordCount;
for (int i = 1; i <= nRecords; i++)
{
Doc.MailMerge.DataSource.FirstRecord = i; //It doesn't work
Doc.MailMerge.DataSource.LastRecord = i; // it doesn't work
Doc.MailMerge.DataSource.ActiveRecord = (i == 1 ?
Word.WdMailMergeActiveRecord.wdFirstDataSourceRecord :Word.WdMailMergeActiveRecord.wdNextDataSourceRecord);
Doc.MailMerge.DataSource.ActiveRecord = (i == nRecords ? Word.WdMailMergeActiveRecord.wdLastDataSourceRecord : Doc.MailMerge.DataSource.ActiveRecord);
dynamic fields = Doc.MailMerge.DataSource.DataFields;
}

Nullable Property throwing NullReferenceException on .HasValue

This line of (C#) code
if (!currentLap.S1.HasValue)
is giving me
System.NullReferenceException: Object reference not set to an instance of an object.
provided I'm sure that currentLap variable is instantiated (because it's being used a few lines before and it is a local variable) and it has following property:
private double? _s1;
[DefaultValue(null)]
[JsonConverter(typeof(ShortDoubleConverter))]
public double? S1
{
get { return _s1; }
set { _s1 = value; }
}
how can it possibly throw NullReferenceException? Can it be something to do with optimization on Release mode?
Thanks,
Stevo
EDIT:
here is full method code.
public void Update(DriverData driverData)
{
LapInfo currentLap = this.CurrentLap;
if (currentLap != null &&
this.LastDriverData != null &&
driverData.TotalLaps != this.LastDriverData.TotalLaps &&
driverData.InPits &&
driverData.Speed < 10 &&
!this.LastDriverData.InPits)
{
currentLap.Escaped = true;
}
this.LastDriverData = driverData;
if ((currentLap == null || currentLap.Lap != driverData.LapNumber) &&
!this.Laps.TryGetValue(driverData.LapNumber, out currentLap))
{
currentLap = new LapInfo() { Lap = driverData.LapNumber, Parent = this, Class = driverData.Class };
this.Laps.Add(driverData.LapNumber, currentLap);
int lapsCount = 0, completedDriverLaps = 0, cleanLaps = 0;
this.TotalLaps = driverData.TotalLaps;
//if it's not the first lap
if (driverData.TotalLaps > 0)
{
//previous lap
if (this.CurrentLap == null || !this.CurrentLap.Escaped)
{
this.CompletedLaps++;
if (this.CurrentLap == null || !this.CurrentLap.MaxIncident.HasValue)
this.CleanLaps++;
}
}
foreach (DriverLapsInfo laps in this.Parent.LapsByVehicle.Values)
{
lapsCount += laps.TotalLaps;
completedDriverLaps += laps.CompletedLaps;
cleanLaps += laps.CleanLaps;
}
this.Parent.Parent.SetLapsCount(driverData, lapsCount, driverData.Class, completedDriverLaps, cleanLaps);
}
this.CurrentLap = currentLap;
//add incidents
if (driverData.Incidents != null)
{
foreach (IncidentScore incident in driverData.Incidents)
{
this.CurrentLap.MaxIncident = Math.Max(this.CurrentLap.MaxIncident ?? 0, incident.Strength);
this.CurrentLap.Incidents++;
this.Incidents++;
}
}
LapInfo previousLap = null;
if ((this.PreviousLap == null || this.PreviousLap.Lap != driverData.TotalLaps) &&
this.Laps.TryGetValue(driverData.TotalLaps, out previousLap))
{
this.PreviousLap = previousLap;
if (!this.PreviousLap.Date.HasValue)
{
this.PreviousLap.Date = DateTime.UtcNow;
}
}
if (currentLap.Position == 0)
currentLap.Position = driverData.Position;
if (driverData.CurrentS1 > 0)
{
**if (!currentLap.S1.HasValue)**
{
this.UpdateBestS1(driverData.BestS1);
this.Parent.Parent.UpdateBestS1(driverData.BestS1, driverData.UniqueName);
currentLap.UpdateS1(driverData.CurrentS1, driverData);
//reset the best split set at the finish line
if (this.PreviousLap != null && this.PreviousLap.SplitBest < 0)
this.PreviousLap.SplitBest = 0;
}
if (driverData.CurrentS2.HasValue && driverData.CurrentS1.HasValue && !currentLap.S2.HasValue)
{
double s2 = driverData.CurrentS2.Value - driverData.CurrentS1.Value;
this.UpdateBestS2(s2);
this.Parent.Parent.UpdateBestS2(s2, driverData.UniqueName);
currentLap.UpdateS2(s2, driverData);
}
}
if (this.PreviousLap != null)
{
if (driverData.LastLap > 0)
{
if (!this.PreviousLap.S3.HasValue && driverData.LastS2.HasValue)
{
double s3 = driverData.LastLap.Value - driverData.LastS2.Value;
this.UpdateBestS3(s3);
this.Parent.Parent.UpdateBestS3(s3, driverData.UniqueName);
this.PreviousLap.UpdateS3(s3, driverData);
}
if (!this.PreviousLap.LapTime.HasValue)
{
double? bestLap = this.Parent.Parent.BestLap;
this.PreviousLap.UpdateLapTime(driverData, 0);
this.Parent.Parent.UpdateBestLap(this.PreviousLap, driverData.BestLap, driverData);
this.UpdateBestLap(driverData.BestLap, this.PreviousLap);
this.PreviousLap.UpdateLapTime(driverData, bestLap);
}
}
else
{
if (this.PreviousLap.SplitBest.HasValue)
this.PreviousLap.UpdateBestSplit();
if (this.PreviousLap.SplitSelf.HasValue)
this.PreviousLap.UpdateSelfSplit();
}
}
if (driverData.InPits)
{
switch (driverData.Sector)
{
case Sectors.Sector1:
if (previousLap != null)
previousLap.InPits = true;
break;
case Sectors.Sector3:
currentLap.InPits = true;
break;
}
}
//lap to speed
if (currentLap.TopSpeed < driverData.Speed)
{
driverData.TopSpeedLap = driverData.Speed;
currentLap.UpdateTopSpeed(driverData.Speed);
}
else
driverData.TopSpeedLap = currentLap.TopSpeed;
//overall top speed
if (this.TopSpeed < driverData.Speed)
{
driverData.TopSpeed = driverData.Speed;
this.TopSpeed = driverData.Speed;
this.Parent.Parent.UpdateTopSpeed(this.TopSpeed, driverData);
}
else
driverData.TopSpeed = this.TopSpeed;
}
There is no way on earth the code can make it to that line and currentLap beeing null.
Or am I going crazy? :)
.HasValue will not throw if the nullable reference is null, but a.b.HasValue will if a is null.
I suspect that currentLap == null. I know you say you're sure that currentLap is not null, but I think that's the most likely explanation. Can you post more code?
Update:
Thanks for posting your code.
This doesn't throw:
void Main() {
var f = new Foo();
Console.WriteLine (f.S1);
Console.WriteLine (f.S1.HasValue);
}
class Foo {
private double? _s1 = null;
public double? S1 {
get { return _s1; }
set { _s1 = value; }
}
}
Could you try to create a minimal reproduction? (minimal code that exhibits the issue)
Maybe have a look at the previous line of code :) - debugger often highlights the next line after the one where the NullReferenceException was actually thrown.

Categories

Resources