OLE DB Object field to SQL image field migration c# - sql

I am trying to migrate OLE object field (access 2003) to SQL 2005 field, now I managed to get Doc file working (function copied),
but no luck with EXCEL/PDF and other files.
short sFlag = 0;
int nIndex = 0;
int nCount = 0;
int nOffset = 0;
int nImgLen = 0;
int nReadbyte = 14400;
string szImgType = string.Empty;
if (bData.Length > 0)
{
MemoryStream memStream = new MemoryStream(bData, true);
byte[] bArray = new byte[nReadbyte];
nCount = memStream.Read(bArray, 0, nReadbyte);
if (bArray[78] == (byte)0x42 && bArray[79] == (byte)0x4D) //BMP FORMAT
{
sFlag = 1;
nOffset = 78;
szImgType = "image/bmp";
}
else
{
for (nIndex = 78; nIndex < nReadbyte - 2; nIndex++)
{
if (bArray[nIndex] == (byte)0xFF && bArray[nIndex + 1] == (byte)0xD8) //JPG FORMAT
{
sFlag = 2;
nOffset = nIndex;
szImgType = "image/pjpeg";
break;
}
else if (bArray[nIndex] == (byte)0x25 && bArray[nIndex + 1] == (byte)0x50) //PDF FORMAT
{
sFlag = 3;
nOffset = nIndex;
szImgType = "application/pdf";
FileType = "application/pdf";
break;
}
else if (bArray[nIndex] == (byte)0xD0 && bArray[nIndex + 1] == (byte)0xCF) //MSWORD FORMAT
{
sFlag = 4;
nOffset = nIndex;
szImgType = "application/msword";
FileType = "application/msword";
break;
}
}
}
if (sFlag > 0)
{
nImgLen = bData.Length - nOffset;
memStream.Position = 0;
memStream.Write(bData, nOffset, nImgLen);
memStream.Position = 0;
byte[] bImgData = bData; //new byte[nImgLen];
return bImgData;
}
else
{
return null;
}
}
else {
return null;
}
}
will like to know any pointers/ lookups to migrate ole objects to SQL 2005 fields.
-Prash

Related

Execution gets stuck at date picking functionality of selenium webdriver

I am new to selenium automation, I have written a script to pick check in and check out dates from webpage of tripadvisor.in. I hope the code and xpaths are correct coz out of 7 or 8 executions the scrips successfully running only once. I thought abt synchronization issue and tried adding all types of waits but still the execution getting stuck as calendar. Sometimes stucking at check-in date, sometimes at check-out date but sometimes working fine. Can I get help to sort this issue plz...
public void selectCheckDate(String date, WebElement forwardArrow) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date expectedDate = dateFormat.parse(prop.getProperty(date));
String day = new SimpleDateFormat("dd").format(expectedDate);
String month = new SimpleDateFormat("MMMM").format(expectedDate);
String year = new SimpleDateFormat("yyyy").format(expectedDate);
String expectedMonthYear = month + " " + year;
logger.log(Status.INFO, "Expected Month and year: "+expectedMonthYear);
WebDriverWait wait = new WebDriverWait(driver, 20);
String dd1 = "", dd2 = "";
String d1 = null, d2 = null;
boolean flag1 = false;
boolean flag2 = false;
while (true) {
String displayDate1 = driver.findElement(By.xpath("//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div")).getText();
String displayDate2 = driver.findElement(By.xpath("(//*[#class='vr-datepicker-LargeStyles__caption--Srrff']/div)[2]")).getText();
if (displayDate1.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d1 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex = isElementExists(d1);
if(ex==true) {
dd1 = driver.findElement(By.xpath(d1)).getText();
if (dd1.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d1))).click();
//driver.findElement(By.xpath(d1)).click();
flag1 = true;
break;
}
}
}
if (flag1 == true) {
break;
}
}
if (flag1 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else if (displayDate2.contains(expectedMonthYear)) {
//addWait();
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 7; j++) {
d2 = "//*[#id='BODY_BLOCK_JQUERY_REFLOW']/div[14]/div/div/div[2]/div/div/div[2]/div[2]/div[3]/div["
+ i + "]/div[" + j + "]";
boolean ex1 = isElementExists(d2);
if(ex1==true) {
dd2 = driver.findElement(By.xpath(d2)).getText();
if (dd2.equals(day)) {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(d2))).click();
//driver.findElement(By.xpath(d2)).click();
flag2 = true;
break;
}
}
}
if (flag2 == true) {
break;
}
}
if (flag2 == true) {
reportPass("Entered date: "+prop.getProperty(date));
break;
}
} else {
forwardArrow.click();
}
}
} catch (ParseException e) {
reportFail(e.getMessage());
}
}

Null pointer exception on Processing (ldrValues)

My code involves both Processing and Arduino. 5 different photocells are triggering 5 different sounds. My sound files play only when the ldrvalue is above the threshold.
The Null Pointer Exception is highlighted on this line
for (int i = 0; i < ldrValues.length; i++) {
I am not sure which part of my code should be changed so that I can run it.
import processing.serial.*;
import processing.sound.*;
SoundFile[] soundFiles = new SoundFile[5];
Serial myPort; // Create object from Serial class
int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};
void setup() {
size(200, 200);
println((Object[])Serial.list());
String portName = Serial.list()[3];
myPort = new Serial(this, portName, 9600);
soundFiles[0] = new SoundFile(this, "1.mp3");
soundFiles[1] = new SoundFile(this, "2.mp3");
soundFiles[2] = new SoundFile(this, "3.mp3");
soundFiles[3] = new SoundFile(this, "4.mp3");
soundFiles[4] = new SoundFile(this, "5.mp3");
}
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}
You're approach is shall we say optimistic ? :)
It's always assuming there was a message from Serial, always formatted the right way so it could be parsed and there were absolutely 0 issues buffering data (incomplete strings, etc.))
The simplest thing you could do is check if the parsing was successful, otherwise the ldrValues array would still be null:
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
// double check parsing int values from the string was successfully as well, not just buffering the string
if(ldrValues != null){
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}else{
// print a helpful debugging message otherwise
println("error parsing ldrValues from string: " + myString);
}
}
(Didn't know you could parse a int[] with int(): nice!)

NullPointerException for statement

public void loadFileRecursiv(String pathDir)
{
File fisier = new File(pathDir);
File[] listaFisiere = fisier.listFiles();
for(int i = 0; i < listaFisiere.length; i++)
{
if(listaFisiere[i].isDirectory())
{
loadFileRecursiv(pathDir + File.separatorChar + listaFisiere[i].getName());
}
else
{
String cuExtensie = listaFisiere[i].getName();
String nume = cuExtensie.split(".")[0];
String acronimBanca = nume.split("_")[0];
String tipAct = nume.split("_")[1];
String dataActString = nume.split("_")[2];
//Date dataAct = new SimpleDateFormat("dd-MM-yyyy").parse(dataActString);
//String denBanca = inlocuireAcronim(acronimBanca);
insertData(listaFisiere[i], cuExtensie, acronimBanca, tipAct, dataActString);
//fisiere[i].renameTo(new File("u02/ActeConstitutive/Mutate"));
}
}
}
I have a simple code that checks all files and folders recursevely when a path is given. Unfortunately, i have a NULLPOINTEREXCEPTION for for(int i = 0; i < listaFisiere.length; i++) this line. What can be the problem? Thank you!
check whether listaFisiere is null or not
If not null, change this line as for(int i = 0; i < listaFisiere.length(); i++)
and
you can change your code as below
for(File path:listaFisiere)
{
if(path.isDirectory())
{
loadFileRecursiv(pathDir + File.separatorChar + path.getName());
}
else
{
String cuExtensie = path.getName();
String nume = cuExtensie.split(".")[0];
String acronimBanca = nume.split("_")[0];
String tipAct = nume.split("_")[1];
String dataActString = nume.split("_")[2];
//Date dataAct = new SimpleDateFormat("dd-MM-yyyy").parse(dataActString);
//String denBanca = inlocuireAcronim(acronimBanca);
insertData(path, cuExtensie, acronimBanca, tipAct, dataActString);
//fisiere[i].renameTo(new File("u02/ActeConstitutive/Mutate"));
}
}

Label Printing using iTextSharp

I have a logic to export avery label pdf. The logic exports the pdf with labels properly but when i print that pdf, the page size measurements (Page properties) that i pass isn't matching with the printed page.
Page Properties
Width="48.5" Height="25.4" HorizontalGapWidth="0" VerticalGapHeight="0" PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8" PageSize="A4" LabelsPerRow="4" LabelRowsPerPage="10"
The above property values are converted equivalent to point values first before applied.
Convert to point
private float mmToPoint(double mm)
{
return (float)((mm / 25.4) * 72);
}
Logic
public Stream SecLabelType(LabelProp _label)
{
List<LabelModelClass> Model = new List<LabelModelClass>();
Model = RetModel(_label);
bool IncludeLabelBorders = false;
FontFactory.RegisterDirectories();
Rectangle pageSize;
switch (_label.PageSize)
{
case "A4":
pageSize = iTextSharp.text.PageSize.A4;
break;
default:
pageSize = iTextSharp.text.PageSize.A4;
break;
}
var doc = new Document(pageSize,
_label.PageMarginLeft,
_label.PageMarginRight,
_label.PageMarginTop,
_label.PageMarginBottom);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, output);
writer.CloseStream = false;
doc.Open();
var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
var tbl = new PdfPTable(numOfCols);
var colWidths = new List<float>();
for (int i = 1; i <= numOfCols; i++)
{
if (i % 2 > 0)
{
colWidths.Add(_label.Width);
}
else
{
colWidths.Add(_label.HorizontalGapWidth);
}
}
var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
var size = new iTextSharp.text.Rectangle(w, h);
tbl.SetWidthPercentage(colWidths.ToArray(), size);
//var val = System.IO.File.ReadLines("C:\\Users\\lenovo\\Desktop\\test stock\\testing3.txt").ToArray();
//var ItemNoArr = Model.Select(ds => ds.ItemNo).ToArray();
//string Header = Model.Select(ds => ds.Header).FirstOrDefault();
int cnt = 0;
bool b = false;
int iAddRows = 1;
for (int iRow = 0; iRow < ((Model.Count() / _label.LabelsPerRow) + iAddRows); iRow++)
{
var rowCells = new List<PdfPCell>();
for (int iCol = 1; iCol <= numOfCols; iCol++)
{
if (Model.Count() > cnt)
{
if (iCol % 2 > 0)
{
var cellContent = new Phrase();
if (((iRow + 1) >= _label.StartRow && (iCol) >= (_label.StartColumn + (_label.StartColumn - 1))) || b)
{
b = true;
try
{
var StrArr = _label.SpineLblFormat.Split('|');
foreach (var x in StrArr)
{
string Value = "";
if (x.Contains(","))
{
var StrCommaArr = x.Split(',');
foreach (var y in StrCommaArr)
{
if (y != "")
{
Value = ChunckText(cnt, Model, y, Value);
}
}
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
else
{
Value = ChunckText(cnt, Model, x, Value);
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
}
}
catch (Exception e)
{
var fontHeader1 = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 6, 0);
cellContent.Add(new Chunk("NA", fontHeader1));
}
cnt += 1;
}
else
iAddRows += 1;
var cell = new PdfPCell(cellContent);
cell.FixedHeight = _label.Height;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;
rowCells.Add(cell);
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
_label.LabelRowsPerPage = _label.LabelRowsPerPage == null ? 0 : _label.LabelRowsPerPage;
if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
{
tbl.Rows.Add(CreateGapRow(numOfCols, _label));
}
}
doc.Add(tbl);
doc.Close();
output.Position = 0;
return output;
}
private PdfPRow CreateGapRow(int numOfCols, LabelProp _label)
{
var cells = new List<PdfPCell>();
for (int i = 0; i < numOfCols; i++)
{
var cell = new PdfPCell();
cell.FixedHeight = _label.VerticalGapHeight;
cell.Border = Rectangle.NO_BORDER;
cells.Add(cell);
}
return new PdfPRow(cells.ToArray());
}
A PDF document may have very accurate measurements, but then those measurements get screwed up because the page is scaled during the printing process. That is a common problem: different printers will use different scaling factors with different results when you print the document using different printers.
How to avoid this?
In the print dialog of Adobe Reader, you can choose how the printer should behave:
By default, the printer will try to "Fit" the content on the page, but as not every printer can physically use the full page size (due to hardware limitations), there's a high chance the printer will scale the page down if you use "Fit".
It's better to choose the option "Actual size". The downside of using this option is that some content may get lost because it's too close to the border of the page in an area that physically can't be reached by the printer, but the advantage is that the measurements will be preserved.
You can set this option programmatically in your document by telling the document it shouldn't scale:
writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
See How to set initial view properties? for more info about viewer preferences.

Why result of GetPageLabels is different from the Adobe Acrobat

I edit page number of pdf in Adobe Acrobat X Pro.
Test PDF
result:
1-FrontCover
2-FrontFold
3-i
4-ii
5-iii
6-1
7-2
8-3
9-4
10-5
11-BackFold
12-BackCover
But this result of GetPageLabels is wrong
page number:
0-FrontCover1
1-FrontFold1
2-FrontFoldi
3-FrontFoldii
4-FrontFoldiii
5-FrontFold1
6-FrontFold2
7-FrontFold3
8-FrontFold4
9-FrontFold5
10-BackFold1
11-BackCover1
C# Code:
objLabels = PdfPageLabels.GetPageLabels(objReader);
TextBox1.Text += "page number:" + Environment.NewLine;
if (objLabels != null) {
for (i = 0; i <= objLabels.Length - 1; i++) {
TextBox1.Text += i + "-" + objLabels(i) + Environment.NewLine;
}
}
How to get the correct result like Adobe Acrobat X Pro?
There is a small bug in PdfPageLabels.GetPageLabels(PdfReader). When encountering a new page label dictionary without a P (prefix) entry, it does not reset the current prefix value:
int pagecount = 1;
String prefix = "";
char type = 'D';
for (int i = 0; i < n; i++) {
if (numberTree.ContainsKey(i)) {
PdfDictionary d = (PdfDictionary)PdfReader.GetPdfObjectRelease(numberTree[i]);
if (d.Contains(PdfName.ST)) {
pagecount = ((PdfNumber)d.Get(PdfName.ST)).IntValue;
}
else {
pagecount = 1;
}
if (d.Contains(PdfName.P)) {
prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
}
if (d.Contains(PdfName.S)) {
type = ((PdfName)d.Get(PdfName.S)).ToString()[1];
}
else {
type = 'e';
}
}
...
}
You can fix this by adding the following else clause to the if in question:
if (d.Contains(PdfName.P)) {
prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
}
else
{
prefix = "";
}
Whith this change I get I get
page number:
0 - FrontCover
1 - FrontFold
2 - i
3 - ii
4 - iii
5 - 1
6 - 2
7 - 3
8 - 4
9 - 5
10 - BackFold
11 - BackCover
PS: The same issue is present in the Java iText version, tested in ReadPageLabels.java.
Thank you for helping to solve my problem,
Here is my complete program.
public string[] ReadPageLabel(PdfReader objReader, int intPageCount)
{
PdfDictionary objDictionary ;
Dictionary<int, PdfObject> objTree ;
string[] arrLabels ;
int i ;
char chrLabelKind ;
string strLabelPrefix ;
int intLableNumber ;
//PdfPageLabels is wrong
//arrLabels = PdfPageLabels.GetPageLabels(objReader)
arrLabels = new string[intPageCount];
if (objReader.Catalog.Get(PdfName.PAGELABELS) != null) {
objTree = PdfNumberTree.ReadTree(PdfReader.GetPdfObjectRelease(objReader.Catalog.Get(PdfName.PAGELABELS)));
chrLabelKind = 'D';
strLabelPrefix = "";
intLableNumber = 1;
for (i = 0; i <= intPageCount - 1; i++) {
if (objTree.ContainsKey(i)) { //if reset page number
objDictionary = PdfReader.GetPdfObjectRelease(objTree[i]);
//PdfName.S:Number Kind
if (objDictionary.Contains(PdfName.S)) {
chrLabelKind = ((PdfName)objDictionary.Get(PdfName.S)).ToString()(1);
//PdfName.S:/R,/r,/A,/a,/e,/D,ToString()(1)get alphabet of Index=1
} else {
chrLabelKind = 'e';
}
//PdfName.P:Prefix
if (objDictionary.Contains(PdfName.P)) {
strLabelPrefix = ((PdfString)objDictionary.Get(PdfName.P)).ToUnicodeString();
} else {
strLabelPrefix = "";
}
//PdfName.ST:Start Number
if (objDictionary.Contains(PdfName.ST)) {
intLableNumber = ((PdfNumber)objDictionary.Get(PdfName.ST)).IntValue;
} else {
intLableNumber = 1;
}
}
switch (chrLabelKind) {
case 'R':
//I,II,III
arrLabels[i] = strLabelPrefix + factories.RomanNumberFactory.GetUpperCaseString(intLableNumber);
break;
case 'r':
//i,ii,iii
arrLabels[i] = strLabelPrefix + factories.RomanNumberFactory.GetLowerCaseString(intLableNumber);
break;
case 'A':
//A,B,C
arrLabels[i] = strLabelPrefix + factories.RomanAlphabetFactory.GetUpperCaseString(intLableNumber);
break;
case 'a':
//a,b,c
arrLabels[i] = strLabelPrefix + factories.RomanAlphabetFactory.GetLowerCaseString(intLableNumber);
break;
case 'e':
//no number kind
arrLabels[i] = strLabelPrefix;
break;
default:
//1,2,3
arrLabels[i] = strLabelPrefix + intLableNumber;
break;
}
intLableNumber += 1;
}
} else {
for (i = 0; i <= intPageCount - 1; i++) {
arrLabels[i] = i + 1;
}
}
return arrLabels;
}