Specified cast is not valid - oledbdatareader

SqlDataReader reader;
string r="C:\\Users\\Shivam\\Documents\\";
if ((FileUpload1.PostedFile != null)&&(FileUpload1.PostedFile.ContentLength > 0))
{
r += System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
}
OleDbConnection oconn =
new OleDbConnection
(#"Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source="+r+";"
+ #"Extended Properties=""Excel 8.0;HDR=Yes;""");
oconn.Open();
conn.Open();
OleDbCommand dbcom = new OleDbCommand("SELECT * FROM [Sheet1$]", oconn);
OleDbDataReader dbreader = dbcom.ExecuteReader();
//dbread = dbreader;
int rni = dbreader.GetOrdinal ("RollNo");
int mki = dbreader.GetOrdinal ("marks");
int rowcount =0;
while(dbreader.Read())
{ rowcount++; }
//dbreader.Close();
//OleDbDataReader dbread = dbcom.ExecuteReader();
int[] rn = new int[rowcount];
int[] gr = new int[rowcount];
while (dbreader.Read())
{
int o = 0;
for(int i=0;i<rowcount;i++)
{
int q = (int)dbreader.GetValue(rni);
int p = (int)dbreader.GetValue(mki);
rn[i] = q;
gr[i] = p;
//roll[i] = valid(odr, 0);//Here we are calling the valid method
//marks[i] = valid(odr, 1);
//i++;
if (gr[i] >= 11)
{ o=i; }
}
if(o!=0)
{ break; }
TextBox4.Text += rn + "\t" + gr;
//Here using this method we are inserting the data into the database
x = TextBox2.Text.Substring(0, 1);
y = TextBox2.Text.Substring(1, 1);
//for (int s = 0; s < roll.Length; s++)
//{
//SqlDataAdapter sda = new SqlDataAdapter("select StudentID from Student where APID=" + int.Parse(y)+ "and Semester=" + int.Parse(z) + "and Roll_No=" + int.Parse(RollNo), conn);
//DataSet ds = new DataSet();
//sda.Fill(ds);
//GridView1.DataSource = ds;
//GridView1.DataBind();
SqlCommand command = new SqlCommand();
command.Connection = conn;
//command.Connection.Open();
command.CommandType = CommandType.Text;
int c = rn.Length;
for (int n = 0; n<rn.Length; n++)
{
command.CommandText = "Select StudentID from Student where APID=" + int.Parse(x) + "and Semester=" + int.Parse(y) + "and Roll_No=" + rn[n];
}
reader = command.ExecuteReader();
while (reader.Read())
{
TextBox4.Text = reader.GetInt32(0).ToString();
a = (int)reader["StudentID"];
for (int v = 0; v < rn.Length; v++)
{
insertdataintosql(rn[v], gr[v]);
}
}
//}
}
conn.Close();
oconn.Close();
The problem here is that the statements in the while(dbreader.read()) are not executed, rather directly conn.Close() is performed. And if I take another datareader with same command after closing the previous datareader, the error "Specified cast not valid" is thrown at "int q = (int)dbreader.GetValue(rni);". Please help me out...thanks in advance

DataReaders are forward-only. You can't "reuse" it.
All you are doing is allocating an array based on the number of records. Either run a COUNT query first to get the number of records, or re-allocate your array on the fly in the one loop.
OleDbCommand dbcom = new OleDbCommand("SELECT COUNT(*) as RowCount FROM [Sheet1$]", oconn);
dbreader = dbcom.ExecuteReader();
dbreader.Read();
rowcount = dbreader.GetOrdinal("RowCount");
dbcom.Close();
dbcom = new OleDbCommand("SELECT * FROM [Sheet1$]", oconn);
dbreader = dbcom.ExecuteReader();
... carry on with your 2nd loop
There is more to say about releasing resources properly. Best practice is to add parameter CommandBehavior.CloseConnection to ExecuteReader, create your data reader inside a using() construct and issue cmd.Dispose() at the end to ensure SQL connection resources are released properly.
.. though actually since it's a local file you're using it may not matter so much but generally speaking you should do that. Otherwise its very easy to find that an orphaned DataReader has not released its connection.

Related

How to NOT flatten the image applied in a pdf with Itext in c#?

I need to apply an image on all my pages from my PDF, but without flattening it ( I want to have the ability to move it in my PDF reader afterwards)
My code:
String basePath = "d:\\zPDF\\";
DirectoryInfo d = new DirectoryInfo(basePath);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.pdf"); //Getting Text files
List<string> listS = new List<string>();
foreach (FileInfo file in Files)
{
listS.Add(file.Name);
}
foreach (string s in listS)
{
using (System.IO.Stream inputPdfStream = new FileStream(basePath + s, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
//using (System.IO.Stream inputImageStream = new FileStream(basePath + "x1.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream inputImageStream2 = new FileStream(basePath + "x2.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream outputPdfStream = new FileStream(basePath + "zResult" + s, FileMode.Create, System.IO.FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
//stamper.FormFlattening = true;
//stamper.FreeTextFlattening = true;
int numberOfPages = reader.NumberOfPages;
Image myImage = Image.GetInstance(inputImageStream2);
float f-Image1, f-Image2;
for (int i = 1; i <= numberOfPages; i++)
{
int nr, plusMinus = 25;
Rectangle mediabox = reader.GetPageSize(i);
int getTOP = (int)mediabox.GetTop(0);
int getRight = (int)mediabox.GetRight(0);
var pdfContentByte = stamper.GetOverContent(i);
nr = getRight - 600;
f-Image1 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
nr = 40;
f-Image2 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
myImage.SetAbsolutePosition(f-Image1, f-Image2);
myImage.RotationDegrees = row1(-35, 35);
pdfContentByte.AddImage(myImage);
}
stamper.Close();
}
I've tried:
stamper.FormFlattening = false;
stamper.FreeTextFlattening = false;
but no results. The image is still flatten.
I think, after I've read some posts, that I need to set up my PdfStamper in useAppendMode() but I don't know how should I do this and, I don't know if this is this right direction.

Hundred thousands of datatable records to PDF in web API

I'm trying to create PDF from the DataTable in web api using ADO.Net. Unfortunately based on filters some times I may get very less records & able to download without any problem. Sometimes may be very huge like 200 thousand of records. When I'm checking in local my system its getting hang while converting the dt to PDF. My code is like below:
private FileContentResult ExportPDF(DataTable dataTable)
{
string Name = "Logs";
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
byte[] content = null;
try
{
string[] columnNames = (from dc in dataTable.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
int count = columnNames.Length;
object[] array = new object[count];
dataTable.Rows.Add(array);
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dataTable.Columns.Count;
int rows = dataTable.Rows.Count;
HeaderFooter header = new HeaderFooter(new Phrase(Name), false);
// Remove the border that is set by default
header.Border = iTextSharp.text.Rectangle.TITLE;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = Element.ALIGN_CENTER;
pdfDoc.Header = header;
// Header.
pdfDoc.Open();
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1; pdfTable.Width = 100;
pdfTable.Padding = 1; pdfTable.Spacing = 4;
//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Chunk chunkCols = new Chunk();
iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.Black);
chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);
}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
content = mStream.ToArray();
return File(content, "application/pdf", "LogReports.pdf");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

ADO.NET: How can we update a DataTable column values as fast as calculated columns does?

I have a small test program that creates a DataTable with 1M rows.
Then I add a calculated column (Expression column), it's super fast like a second.
Then I just try to add a new column and set values to it, it takes more than 10 seconds.
DataTable update is slow. How can I make it as fast as calculated column?
10 seconds does seem acceptable but that is just a test program to show the difference.
This can become worst depending on how many rows, columns, etc.
Anyway if calculated column is able to do it that fast, hopefully we can get same performance with normal updates.
It seems calculated columns is able to turn off some notifications or other things. I'm not sure.
Any idea? Advice? Maybe I'm missing something when updating the DataTable.
Thanks in advance
Below is the code sample I'm using:
using System;
using System.Data;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
try
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
Console.WriteLine("DataTable creation started ...");
DataTable data = new DataTable();
int nbrCols = 50;
for (int i = 0; i < nbrCols; i++)
{
data.Columns.Add(string.Concat("COL_", (i + 1)), typeof(double));
}
System.Random r = new System.Random();
data.BeginLoadData();
int nbrows = 1000000;
for (int i = 0; i < nbrows; i++)
{
DataRow newRow = data.NewRow();
for (int j = 0; j < nbrCols; j++)
{
newRow[j] = r.NextDouble();
}
data.Rows.Add(newRow);
}
data.EndLoadData();
watch.Stop();
Console.WriteLine("DataTable creation = " + watch.ElapsedMilliseconds / 1000.0);
int colIndexFlow1 = data.Columns.IndexOf("COL_1");
int colIndexFlow2 = data.Columns.IndexOf("COL_2");
/* Add a calculated columns */
watch.Restart();
data.Columns.Add("CALC_1", typeof(double), "COL_1 + COL_2");
data.AcceptChanges();
watch.Stop();
Console.WriteLine("Calculated Column creation = " + watch.ElapsedMilliseconds / 1000.0);
/* Add a new column */
watch.Restart();
data.BeginLoadData();
data.Columns.Add("NEW_1", typeof(double));
int colIdx = data.Columns.IndexOf("NEW_1");
foreach (DataRow row in data.Rows)
{
//double val = row.Field<double>("COL_1") + row.Field<double>("COL_2");
//row.SetField<double>(colIdx, val);
// Most of the time is spent to actually set the data
// Question is how can we make the update happening as fast as the update done when using a calculated column.
row.SetField<double>(colIdx, 2.0);
}
data.AcceptChanges();
data.EndLoadData();
watch.Stop();
Console.WriteLine("New Column creation = " + watch.ElapsedMilliseconds / 1000.0);
}
catch (Exception ex)
{
Console.WriteLine("Error=" + ex.Message);
}
finally
{
Console.ReadLine();
Console.WriteLine("Press any key to exit");
}
}
}
}

Add Object To Other Object Scripts that require an Object

Ok , I have problem with adding object let's first see what is this about.
I Have Map when i click at map i create Sphere on map.
then i serialized the point, msg and name .....
void Start () {
Ser = new Serial();
Ser.read();
for (int i =0 ; i < Ser.list.Count; i++)
{
Data d = new Data();
d = Ser.list[i];
GameObject a = GameObject.CreatePrimitive(PrimitiveType.Sphere);
a.name = d.Id;
a.transform.position = new Vector3(d.x,d.y,0);
a.transform.localScale =new Vector3(0.5f , 0.5f , 0.5f);
Follow putTarget = new Follow();
Data Pos_In_File = new Data();
Pos_In_File = Ser.list[i];
GUIText GText = new GUIText();
Vector3 SP = new Vector3();
GameObject TextObj = new GameObject("GUIText" + Convert.ToString(i));
GText = (GUIText)TextObj.AddComponent(typeof(GUIText));
GText.text = Pos_In_File.msg;
GText.material.color = new Color(0 , 0 , 1);
GText.fontSize = 20;
GText.fontStyle = FontStyle.Bold;
SP = Camera.main.WorldToViewportPoint(new Vector3(Pos_In_File.x , Pos_In_File.y , Pos_In_File.z));
TextObj.transform.position = SP;
TextObj.AddComponent(typeof(Follow));
GameObject OBJ = GameObject.Find(Pos_In_File.Id);
putTarget =GetComponent<Follow>();
putTarget.target = OBJ.transform;
}
}
now in last three lines i want to add OBJ to TextOBJ->Follow(Script)->target
What i am messing up ?
i asked this quastion long ago my software have been finnished a 10 month
and the i get through this problem is
void Start () {
Resources.UnloadUnusedAssets();
Ser = new Serial();
Screen.fullScreen = true;
Ser.read();
for (int i =0 ; i < Ser.list.Count; i++)
{
Data d = new Data();
d = Ser.list[i];
GameObject a = GameObject.CreatePrimitive(PrimitiveType.Sphere);
a.name = d.Id;
a.transform.position = new Vector3(d.x,d.y,0);
a.renderer.material.color = Color.green;
Data Pos_In_File = new Data();
Pos_In_File = Ser.list[i];
GUIText GText = new GUIText();
Vector3 SP = new Vector3();
GameObject TextObj = new GameObject(Pos_In_File.Id+"h");
GText = (GUIText)TextObj.AddComponent(typeof(GUIText));
GText.text = Pos_In_File.msg;
GText.material.color = new Color(0 , 0 , 1);
GText.fontSize = 20 + (int)Camera.main.transform.position.z;
GText.fontStyle = FontStyle.Bold;
SP = Camera.main.WorldToViewportPoint(new Vector3(Pos_In_File.x , Pos_In_File.y , Pos_In_File.z));
TextObj.transform.position = SP;
TextObj.AddComponent(typeof(Follow));
}

User input with linear and binary searching in java

I'm trying to write a program that asks the user to input the size of the array the user wants to create, and then asks the user to fill the array with elements, and then it should display the array with its elements and, ask the user to conduct a search for an integer. It should conduct a linear and binary search, while displaying how many probes it took to determine is the element is in the array. So far the only output i have gotten is that the element has not been found. If you could look at my code and see what the problem is, because i have tried for hours and i have changed everything i can think of. Any help would be greatly appreciated.
import java.util.Scanner;
public class Searching
{
public static int[] anArray = new int[100];
private int numberOfElements;
public int arraySize = numberOfElements;
public String linearSearch(int value)
{
int count = 0;
boolean valueInArray = false;
String indexOfValue = "";
System.out.print("The Value was Found in: ");
for(int i = 0; i < arraySize; i++)
{
if(anArray[i] == value)
{
valueInArray = true;
System.out.print(i + " ");
indexOfValue += i + " ";
}
count ++;
}
if(!valueInArray)
{
indexOfValue = " None found";
System.out.print(indexOfValue);
}
System.out.println("\nIt took " + count + " probes with a linear search to find");
return indexOfValue;
}
public void binarySearch(int value)
{
int min = 0;
int max = arraySize - 1;
int count = 0;
while(min <= max)
{
int mid = (max + min) / 2;
if(anArray[mid] < value) min = mid + 1;
else if(anArray[mid] > value) max = mid - 1;
else
{
System.out.println("\nFound a Match for " + value + " at Index " + mid);
min = max + 1;
}
count ++;
}
System.out.println("It took " + count + " probes with a binary search to find");
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("Input the number of elements in your Array");
int numberOfElements = scan.nextInt();
if(numberOfElements <= 0)
{
System.exit(0);
}
int[] anArray = new int[numberOfElements];
System.out.println("\nEnter " + numberOfElements + " Integers");
for(int i = 0; i < anArray.length; i ++)
{
System.out.println("Int # " + (i + 1) + ": ");
anArray[i] = scan.nextInt();
}
System.out.println("\nThe integers you entered are: ");
for(int i = 0; i < anArray.length; i ++) // for loop used to print out each element on a different line
{
System.out.println(anArray[i]);
}
System.out.println("Which element would you like to find?");
int value = scan.nextInt();
Wee3Q2JOSHBALBOA newArray = new Wee3Q2JOSHBALBOA();
newArray.linearSearch(3);
newArray.binarySearch(value);
}
}
hmm I am not sure you are using an array the correct way, you see an Array is a set size and I dont think you can expand like they way you are doing...
Instead try setting the size of the array to certain length.
Or use vectors