libxml2 : xmlFreeTextReader crashes - libxml2

I am using libxml2 (libxml2-2.7.8)
I get crash when I call xmlFreeTextReader after the XMl file is processed.
I do not have a clue as in why is it happening :
Following is the code that I am using:
int parseDevDescMessage(char *buffer, DMXDevice *dmxLocal)
{
//xmlDocPtr xmlDocPointer;
xmlTextReaderPtr xmlTextPointer;
int errorCode=0;
const xmlChar *name, *value;
char *xmlBuffer;
xmlNode *rootElement = NULL;
xmlNode *currentNode = NULL;
devServices *devServicesLocal=NULL;
devServices *devServicesLocalAdd=NULL;
/*
* This initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
xmlBuffer = (char *)malloc(strlen(buffer));
strcpy(xmlBuffer, buffer, strlen(buffer));
/*I am doing this string copy because the variable buffer is referred in the calling function. I am assuming that xmlFreeTextReader is freeing the buffer also
xmlTextPointer = xmlReaderForMemory(xmlBuffer, strlen(xmlBuffer), "somthing.xml", NULL, 0);
if(xmlTextPointer == NULL)
{
#ifdef CTL_MSG_PARSER_DEBUG_NEW
printf("parseDevDescMessage : ERROR WHITE CREATING XML DOC FROM MEM\n");
#endif
errorCode = -1;
goto error;
}
errorCode = xmlTextReaderRead(xmlTextPointer);
while(errorCode == 1)
{
if( ( (strcmp(xmlTextReaderConstName(xmlTextPointer),"serviceList")) == 0 ) &&
( (xmlTextReaderNodeType(xmlTextPointer)) == 1)
)
{
errorCode = xmlTextReaderRead(xmlTextPointer);
while(errorCode == 1)
{
if( ( (strcmp(xmlTextReaderConstName(xmlTextPointer),"service")) == 0) &&
( (xmlTextReaderNodeType(xmlTextPointer)) == 1)
)
{
devServicesLocal = dmxLocal->deviceServices;
if(!devServicesLocal)
{
devServicesLocal = (devServices *)malloc(sizeof(devServices));
memset(devServicesLocal, 0, sizeof(devServices));
dmxLocal->deviceServices = devServicesLocal;
//devServicesLocalAdd = devServicesLocal;
}
else
{
while(devServicesLocal->nextService)
{
devServicesLocal = devServicesLocal->nextService;
}
devServicesLocal->nextService = (devServices *)malloc(sizeof(devServices));
memset(devServicesLocal->nextService, 0, sizeof(devServices));
devServicesLocal = devServicesLocal->nextService;
}
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
value = xmlTextReaderConstValue(xmlTextPointer);
devServicesLocal->serviceType = (char *)malloc(strlen(value));
strcpy(devServicesLocal->serviceType, value);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
value = xmlTextReaderConstValue(xmlTextPointer);
devServicesLocal->serviceId = (char *)malloc(strlen(value));
strcpy(devServicesLocal->serviceId, value);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
value = xmlTextReaderConstValue(xmlTextPointer);
devServicesLocal->SCPDURL = (char *)malloc(strlen(value));
strcpy(devServicesLocal->SCPDURL, value);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
value = xmlTextReaderConstValue(xmlTextPointer);
devServicesLocal->eventSubURL = (char *)malloc(strlen(value));
strcpy(devServicesLocal->eventSubURL, value);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
errorCode = xmlTextReaderRead(xmlTextPointer);
value = xmlTextReaderConstValue(xmlTextPointer);
devServicesLocal->controlURL = (char *)malloc(strlen(value));
strcpy(devServicesLocal->controlURL, value);
}
else
{
errorCode = xmlTextReaderRead(xmlTextPointer);
}
}
}
else
{
errorCode = xmlTextReaderRead(xmlTextPointer);
}
}
error:
xmlMemoryDump();
**xmlFreeTextReader(xmlTextPointer);**
xmlCleanupParser();
return errorCode;
}
Can some one please explain why is this code crashing when xmlFreeTextReader(xmlTextPointer) is called

I used VALGRIND and found a number of memory issues. I fixed one by one all the memory related issues and in the end this crash vanished.
Might be at some place because of the corruption this memory was held on because of which when this was released it was crashing.
Thanks,
-Sun

Related

Wait operation timeout while uploading through Excel Loader in MVC

I'm uploading data from Excel file to database, MVC code reads the first record but on second record it throughs Time Out exception after adding user at "result"
HttpPostedFileBase file = Request.Files["students"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
}
var studentList = new List<RegisterViewModel>();
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var student = new RegisterViewModel();
var Fname = workSheet.Cells[rowIterator, 1].Value.ToString();
var Mname = workSheet.Cells[rowIterator, 2].Value.ToString();
var Lname = workSheet.Cells[rowIterator, 3].Value.ToString();
student.Name = Fname + " " + Mname + " " + Lname;
student.UserName = workSheet.Cells[rowIterator, 4].Value.ToString();
student.Email = workSheet.Cells[rowIterator, 5].Value.ToString();
student.Password = workSheet.Cells[rowIterator, 6].Value.ToString();
student.ConfirmPassword = workSheet.Cells[rowIterator, 7].Value.ToString();
ApplicationDbContext context = new ApplicationDbContext();
var user = new ApplicationUser { UserName = student.UserName, Email = student.Email, Name = student.Name };
var result = await UserManager.CreateAsync(user, student.Password);
if(result!="false")
{
Set executionTimeout property of httpRuntime tah in web.config as shown below:
<system.web>
...
<httpRuntime targetFramework="4.5.1" executionTimeout="30" />
</system.web>
Hope this helps...

import excel file to database using EPPlus

I am having a hard time understanding what should be a simple task. I am now using EPPlus to help me with this task. However, I am at a point of where I can't track what is going on. (per the comment below and days of google searching) I'm trying to read in an excel file and pass that to my EF model. It breaks down at line 159 where I am trying to put in the values from the excel file but keeps coming across as null. However when looking at the values past line 159 they all have the correct information. I am not sure how to even track a bug like this.
TruckController.cs
// POST: Trucks/Import
[HttpPost]
public ActionResult Import(FormCollection formCollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["file"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
file.SaveAs(Server.MapPath("~/" + "test.xlsx"));
//string fileName = file.FileName;
// string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
// var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
var MyImport = new List<string>();
MyImport = ImportDataRecords(new FileInfo(Server.MapPath("~/" ) + "test.xlsx"));
}
}
return View("Import");
}
public List<string> ImportDataRecords(FileInfo file)
{
var resultMessages = new List<string>();
var totalImported = 0;
try
{
using (var excelPackage = new ExcelPackage(file))
{
string DeliveryColumn,
ItemNoColumn,
MaterialColumn,
MaterialDescriptionColumn,
DeliveryQtytoPickColumn,
PickedQuantityColumn,
SalesUoMColumn,
BatchPickedColumn,
BinNoColumn,
BagWeightColumn,
PalletNoColumn,
PalletStackingNoColumn,
StageNoColumn,
SubStopNoColumn,
PickStatusColumn,
PackStatusColumn,
SoldToColumn,
SoldToNameColumn,
ShipToNameColumn;
if (!file.Name.EndsWith("xlsx"))
{
resultMessages.Add("File selected is not an Excel file");
return resultMessages;
}
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null)
{
resultMessages.Add("File was empty");
return resultMessages;
}
using (var headers = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
var expectedHeaders = new[]
{
"Delivery", "Item No.", "Material", "Material Description", "Delivery Qty to Pick",
"Picked Quantity", "Sales UoM", "Batch Picked", "BIN No.", "Bag Weight", "Pallet No.",
"Pallet Stacking No", "Stage No", "Sub Stop No", "Pick Status", "Pack Status", "Sold-To",
"Sold-To Name", "Ship-To Name"
};
if (!expectedHeaders.All(e => headers.Any(h => h.Value.Equals(e))))
{
resultMessages.Add("Some columns are missing from the file");
return resultMessages;
}
DeliveryColumn = headers.First(h => h.Value.Equals("Delivery")).Address[0].ToString();
ItemNoColumn = headers.First(h => h.Value.Equals("Item No.")).Address[0].ToString();
MaterialColumn = headers.First(h => h.Value.Equals("Material")).Address[0].ToString();
MaterialDescriptionColumn = headers.First(h => h.Value.Equals("Material Description")).Address[0].ToString();
DeliveryQtytoPickColumn = headers.First(h => h.Value.Equals("Delivery Qty to Pick")).Address[0].ToString();
PickedQuantityColumn = headers.First(h => h.Value.Equals("Picked Quantity")).Address[0].ToString();
SalesUoMColumn = headers.First(h => h.Value.Equals("Sales UoM")).Address[0].ToString();
BatchPickedColumn = headers.First(h => h.Value.Equals("Batch Picked")).Address[0].ToString();
BinNoColumn = headers.First(h => h.Value.Equals("BIN No.")).Address[0].ToString();
BagWeightColumn = headers.First(h => h.Value.Equals("Bag Weight")).Address[0].ToString();
PalletNoColumn = headers.First(h => h.Value.Equals("Pallet No.")).Address[0].ToString();
PalletStackingNoColumn = headers.First(h => h.Value.Equals("Pallet Stacking No")).Address[0].ToString();
StageNoColumn = headers.First(h => h.Value.Equals("Stage No")).Address[0].ToString();
SubStopNoColumn = headers.First(h => h.Value.Equals("Sub Stop No")).Address[0].ToString();
PickStatusColumn = headers.First(h => h.Value.Equals("Pick Status")).Address[0].ToString();
PackStatusColumn = headers.First(h => h.Value.Equals("Pack Status")).Address[0].ToString();
SoldToColumn = headers.First(h => h.Value.Equals("Sold-To")).Address[0].ToString();
SoldToNameColumn = headers.First(h => h.Value.Equals("Sold-To Name")).Address[0].ToString();
ShipToNameColumn = headers.First(h => h.Value.Equals("Ship-To Name")).Address[0].ToString();
using (var context = new EPPlusTruckContext())
{
var lastRow = worksheet.Dimension.End.Row;
for (var row = 2; row <= lastRow; row++)
{
-----------Line 159-------------> var truck = new Truck()
{
Delivery = worksheet.Cells[DeliveryColumn + row].Value.ToString(),
ItemNo = worksheet.Cells[ItemNoColumn + row].Value.ToString(),
Material = worksheet.Cells[MaterialColumn + row].Value.ToString(),
MaterialDescription = worksheet.Cells[MaterialDescriptionColumn + row].Value.ToString(),
DeliveryQtyToPick = worksheet.Cells[DeliveryQtytoPickColumn + row].Value.ToString(),
PickedQuantity = worksheet.Cells[PickedQuantityColumn + row].Value.ToString(),
SalesUoM = worksheet.Cells[SalesUoMColumn + row].Value.ToString(),
BatchPicked = worksheet.Cells[BatchPickedColumn + row].Value.ToString(),
BinNo = worksheet.Cells[BinNoColumn + row].Value.ToString(),
BagWeight = worksheet.Cells[BagWeightColumn + row].Value.ToString(),
PalletNo = worksheet.Cells[PalletNoColumn + row].Value.ToString(),
PalletStackingNo = worksheet.Cells[PalletStackingNoColumn + row].Value.ToString(),
StageNo = worksheet.Cells[StageNoColumn + row].Value.ToString(),
SubStopNo = worksheet.Cells[SubStopNoColumn + row].Value.ToString(),
PickStatus = worksheet.Cells[PickStatusColumn + row].Value.ToString(),
PackStatus = worksheet.Cells[PackStatusColumn + row].Value.ToString(),
SoldTo = worksheet.Cells[SoldToColumn + row].Value.ToString(),
SoldToName = worksheet.Cells[SoldToNameColumn + row].Value.ToString(),
ShipToName = worksheet.Cells[ShipToNameColumn + row].Value.ToString(),
};
db.Trucks.Add(truck);
try
{
db.SaveChanges();
totalImported++;
}
catch (Exception ex)
{
resultMessages.Add(string.Format("Record on line#{0} failed: {1}\n", row, ex.Message));
}
}
}
}
resultMessages.Insert(0, string.Format("{0} records successfully imported.\n", totalImported));
return resultMessages;
}
}
catch (IOException ex)
{
resultMessages.Add("File still open. Please close Excel file before importing.");
return resultMessages;
}
}
A simple example here:
Reff: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}

How to write two Handlers using Switch Case

i wrote two handlers but i need to write now only one handler using switch case how to write i tried but not working. please help me. this is my two handlers code i want that in switch case.please solve this problem
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Adds_uploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Adds_uploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
2nd Handler
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Fileuploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Fileuploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
I think the only difference if the upload path. I would suggest you to pass along another input form the view and then determine the upload path based on that.
i.e
you would have
//for case one
<input type='hidden' name='uploadType' value='files' />
//for case two
<input type='hidden' name='uploadType' value='adds' />
inside your individual file upload forms and then on your action method you can just use
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
and use this string in your fname construct. So your new method would be like
public void ProcessRequest(HttpContext context)
{
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = mappedDirectory + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath(mappedDirectory), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}

OpenCL imaging - only one pixel is updated

I'm using Opencl.net and I'm trying to do some image processing on the GPU. Unfortunately only the first pixel ([0;0]) has the correct value, and the rest is (0;0;0;0). The OpenCL kernel should assign 0.5 to all color components of every pixel. It seems to me that the kernel is being executed only once (or perhaps the read function is reading only the first pixel). What am I doing wrong? I've omitted not relevant parts from my code:
...
int intPtrSize = 0;
intPtrSize = Marshal.SizeOf(typeof(IntPtr));
Cl.Mem srcImage2DBuffer;
Cl.ImageFormat imageFormat = new Cl.ImageFormat(Cl.ChannelOrder.ARGB, Cl.ChannelType.Float);
int imgWidth = 0, imgHeight = 0;
IntPtr srcFloatDataPtr;
int srcIMGBytesSize = 0;
GCHandle pinnedSrcFloatArray;
//Load image from file into OpenCL buffer
using (FileStream imageFileStream = new FileStream(inputImagePath, FileMode.Open) ) {
System.Drawing.Image inputImage = System.Drawing.Image.FromStream( imageFileStream );
imgWidth = inputImage.Width;
imgHeight = inputImage.Height;
System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(inputImage);
BitmapData bitmapData = bmpImage.LockBits( new Rectangle(0, 0, bmpImage.Width, bmpImage.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
srcIMGBytesSize = bitmapData.Stride * bitmapData.Height;
//Convert image from byte to float array
byte[] inputByteArray = new byte[srcIMGBytesSize];
Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, srcIMGBytesSize);
bmpImage.UnlockBits( bitmapData );
float[] inputFloatArray = new float[srcIMGBytesSize];
Array.Copy(inputByteArray, inputFloatArray, srcIMGBytesSize);
for (int i = 0; i < srcIMGBytesSize; i++) {
inputFloatArray[i] /= 255.0f;
}
pinnedSrcFloatArray = GCHandle.Alloc(inputFloatArray, GCHandleType.Pinned);
srcFloatDataPtr = pinnedSrcFloatArray.AddrOfPinnedObject();
srcImage2DBuffer = Cl.CreateImage2D(_context, Cl.MemFlags.CopyHostPtr | Cl.MemFlags.ReadOnly, imageFormat,
(IntPtr)bitmapData.Width, (IntPtr)bitmapData.Height,
(IntPtr)0, srcFloatDataPtr, out error);
}
float[] outputFloatArray = new float[srcIMGBytesSize];
//I'm not sure whether the pointer here is correct or not.
Cl.Mem resultImage2DBuffer = Cl.CreateImage2D(_context, Cl.MemFlags.CopyHostPtr | Cl.MemFlags.WriteOnly, imageFormat,
(IntPtr)imgWidth, (IntPtr)imgHeight, (IntPtr)0, outputFloatDataPtr, out error);
error = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, srcImage2DBuffer);
error |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, resultImage2DBuffer);
...
IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 };
IntPtr[] regionPtr = new IntPtr[] { (IntPtr)1, (IntPtr)1, (IntPtr)1 };
IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)imgWidth, (IntPtr)imgHeight, (IntPtr)1 };
error = Cl.EnqueueWriteImage(cmdQueue, srcImage2DBuffer, Cl.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, srcFloatDataPtr, 0, null, out clevent);
pinnedSrcFloatArray.Free();
error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 2, null, workGroupSizePtr, null, 0, null, out clevent);
error = Cl.EnqueueReadImage(cmdQueue, resultImage2DBuffer, Cl.Bool.True, originPtr, regionPtr,
(IntPtr)0, (IntPtr)0, outputFloatArray, 0, null, out clevent);
for (int i = 0; i < srcIMGBytesSize; i++) {
outputFloatArray[i] *= 255.0f;
}
//Right here I'm learning that all of the components are 0
for (int i = 0; i < srcIMGBytesSize; i+=4) {
Console.WriteLine("(" + outputFloatArray[i] + "; " + outputFloatArray[i+1] + "; "
+ outputFloatArray[i+2] + "; " + outputFloatArray[i+3] + ")");
}
Thank you!
I've figured out the problem. The region in Cl.EnqueueWriteImage/Cl.EnqueueReadImage should be (imageWidth, imageHeight, 1) instead of (1, 1, 1):
IntPtr[] regionPtr = new IntPtr[] { (IntPtr)imgWidth, (IntPtr)imgHeight, (IntPtr)1 };

Updating existing fields in MS Access database through classic ASP

I've been given working ASP code which I have to change in order to update existing data in database insted of creating new entries. I think I should swap INSERT INTO statment with UPDATE but the code is a bit too coplicated for me to figure out where and what to change.
Here it comes:
// *** Edit Operations: declare variables
// set the form action variable
var MM_editAction = Request.ServerVariables("SCRIPT_NAME");
if (Request.QueryString) {
MM_editAction += "?" + Server.HTMLEncode(Request.QueryString);
}
// boolean to abort record edit
var MM_abortEdit = false;
// query string to execute
var MM_editQuery = "";
// *** Insert Record: set variables
if (String(Request("MM_insert")) == "AddRecord") {
var MM_editConnection = MM_PhoneWeb_conn_STRING;
var MM_editTable = "Employees";
var MM_editRedirectUrl = "userRegister.asp";
var MM_fieldsStr = "textSurname|value|textFirstname|value|textUsername|value|textPass|value";
var MM_columnsStr = "Surname|',none,''|FirstName|',none,''|Username|',none,''|Password|',none,''";
// create the MM_fields and MM_columns arrays
var MM_fields = MM_fieldsStr.split("|");
var MM_columns = MM_columnsStr.split("|");
// set the form values
for (var i=0; i+1 < MM_fields.length; i+=2) {
MM_fields[i+1] = String(Request.Form(MM_fields[i]));
}
// append the query string to the redirect URL
if (MM_editRedirectUrl && Request.QueryString && Request.QueryString.Count > 0) {
MM_editRedirectUrl += ((MM_editRedirectUrl.indexOf('?') == -1)?"?":"&") + Request.QueryString;
}
}
// *** Insert Record: construct a sql insert statement and execute it
if (String(Request("MM_insert")) != "undefined") {
// create the sql insert statement
var MM_tableValues = "", MM_dbValues = "";
for (var i=0; i+1 < MM_fields.length; i+=2) {
var formVal = MM_fields[i+1];
var MM_typesArray = MM_columns[i+1].split(",");
var delim = (MM_typesArray[0] != "none") ? MM_typesArray[0] : "";
var altVal = (MM_typesArray[1] != "none") ? MM_typesArray[1] : "";
var emptyVal = (MM_typesArray[2] != "none") ? MM_typesArray[2] : "";
if (formVal == "" || formVal == "undefined") {
formVal = emptyVal;
} else {
if (altVal != "") {
formVal = altVal;
} else if (delim == "'") { // escape quotes
formVal = "'" + formVal.replace(/'/g,"''") + "'";
} else {
formVal = delim + formVal + delim;
}
}
MM_tableValues += ((i != 0) ? "," : "") + MM_columns[i];
MM_dbValues += ((i != 0) ? "," : "") + formVal;
}
MM_editQuery = "insert into " + MM_editTable + " (" + MM_tableValues + ") values (" + MM_dbValues + ")";
if (!MM_abortEdit) {
// execute the insert
var MM_editCmd = Server.CreateObject('ADODB.Command');
MM_editCmd.ActiveConnection = MM_editConnection;
MM_editCmd.CommandText = MM_editQuery;
MM_editCmd.Execute();
MM_editCmd.ActiveConnection.Close();
if (MM_editRedirectUrl) {
Response.Redirect(MM_editRedirectUrl);

Resources