ORA-06550 , wrong number or types of arguments in call to Oracle Stored Procedure - ado.net

I have a stored procedure which has one in parameter and one out parameter as follows:
create or replace procedure worker_name (w_id in number, w_first out worker.first_name%type) is
Begin
select first_name into w_first
from worker
where worker_id = w_id;
end;
Code to call this stored procedure:
public DataTable <b>GetEmployeeName</b>(int _employeeID)
{
ArrayList arrEmployeeName = new ArrayList();
OracleParameter paramEmployeeId = new OracleParameter(":employeeid", _employeeID);
arrEmployeeName.Add(paramEmployeeId);
DataLayer obj = new DataLayer();
DataTable tblEmployee = obj.<b>GetData</b>("macw_conv.worker_name", arrEmployeeName, "SP");
if (tblEmployee.Rows.Count > 0)
{
return tblEmployee;
}
return null;
}
public DataTable <b>GetData</b>(string query, ArrayList parameters,string queryType)
{
//DataTable dt = new DataTable();
try
{
_con =
new OracleConnection(Oradb);
_con.Open();
_cmd = new OracleCommand(query, _con);
if (_cmd.Connection.State == ConnectionState.Open)
{
if (queryType == "SP" && parameters != null)
{
_cmd.CommandType = CommandType.StoredProcedure;
if (parameters.Count > 0)
{
foreach (OracleParameter param in parameters)
{
_cmd.Parameters.Add(param);
}
}
}
}
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(_cmd);
da.Fill(ds);
if (ds.Tables.Count > 0)
{
return ds.Tables[0];
}
return null;
}
I guess I'm unable to see the obvious error. It's something about the data type mismatch between the out parameter in the stored procedure and output parameter in the code. Any kind of help is appreciated.
Thanks!
I figured out the issue: it was because the datatype of the variable that is saving the out parameter was not handled properly. I changed the code as follows:
try
{
_con = new OracleConnection(Oradb);
_cmd = _con.CreateCommand();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.CommandText = "macw_conv.worker_name";
OracleParameter inobj1 = _cmd.Parameters.Add("w_id", OracleDbType.Int32,50);
inobj1.Direction = ParameterDirection.Input;
inobj1.Value = _employeeID;
OracleParameter inobj2 = _cmd.Parameters.Add("w_last", OracleDbType.Int32, 50);
inobj2.Direction = ParameterDirection.Input;
inobj2.Value = String.IsNullOrEmpty(_lastName) ? null : _lastName;
OracleParameter outobj = _cmd.Parameters.Add("w_first", OracleDbType.Varchar2, 50);
outobj.Direction = ParameterDirection.Output;
_con.Open();
_cmd.ExecuteNonQuery();
_employeeName = ((OracleString) _cmd.Parameters[1].Value).ToString();
_cmd.Dispose();
_con.Close();
}
catch (OracleException ex)
{
Console.WriteLine(ex.Message);
}
return _employeeName;

Try
public DataTable GetEmployeeName(int _employeeID)
{
ArrayList arrEmployeeName = new ArrayList();
OracleParameter paramEmployeeId = new OracleParameter("employeeid", _employeeID);
arrEmployeeName.Add(paramEmployeeId);
OracleParameter paramEmployeeFirst = new OracleParameter("first", OracleDbType.Varchar2, ParameterDirection.Output);
arrEmployeeName.Add(paramEmployeeFirst);
DataLayer obj = new DataLayer();
DataTable tblEmployee = obj.GetData("macw_conv.worker_name(:1,:2)", arrEmployeeName, "SP");
if (tblEmployee.Rows.Count > 0)
{
return tblEmployee;
}
return null;
}

Related

RuntimeBinderException: Convert type System.Threading.Tasks.Task<object> to string

I do an example with signalR. But it doesn't function because of one mistake.
The one mistake (can not convert type system.threading.tasks.task< object> to string) is in this line:
return context.Clients.All.RecieveNotification(simple);
It is at the bottom of the code you can see below.
Below you see the method I wrote. There I do a connection with the database and get the content with a command/query.
Then a few checks and also SqlDependency.
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "SELECT eintrag FROM [dbo].[simple_column]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
simple = dt.Rows[0]["eintrag"].ToString();
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(simple);
}
And here I use the function:
var notifications = $.connection.notificationHub;
notifications.client.recieveNotification = function (simple) {
// Add the message to the page.
$('#dbMessage').text(simple);
};
I hope you can help me.
Thanks.

Copying fields in iTextSharp 5.4.5.0

I was under the impression that it is now possible to copy AcroFields using PdfCopy. In the release notes for iText 5.4.4.0 this is listed as possible now. However, when I try to do so it appears all the annotations (I think I am using that term correctly, still fairly new to iText...) for the fields are stripped out. It looks like the fields are there (meaning I can see the blue boxes that indicate an editable field), but they are not editable. If I try to bring the PDF up in Acrobat I get a message saying that "there are no fields, would you like Acrobat to discover them?" and most are found and marked and fields properly (check boxes aren't, but the text fields are).
I assume there is an additional step somewhere along the lines to re-add the annotations to the PdfCopy object, but I do not see a way to get the annotations from the PdfReader. I also cannot seem to find any documentation on how to do this (since AcroFields were for so long not supported in PdfCopy most of what I find is along that vein).
Due to sensitivity I cannot provide a copy of the PDF's in question, but using an altered version of a test program used earlier you can see the issue with the following code. It should generate a table with some check boxes in the four right columns. If I use the exact same code with PdfCopyFields in the MergePdfs method instead of PdfCopy it works as expected. This code does not produce any text fields, but in my main project they are part of the original parent PDF that is used as a template.
(Sorry for the long example, it has been cherry picked from a much larger application. You will need a PDF with a field named "TableStartPosition" somewhere in it and update RunTest with the correct paths for your local machine to get this to work.)
Has the PdfCopy functionality not made it into iTextSharp yet? I am using version 5.4.5.0.
class Program
{
Stream _pdfTemplateStream;
MemoryStream _pdfResultStream;
PdfReader _pdfTemplateReader;
PdfStamper _pdfResultStamper;
static void Main(string[] args)
{
Program p = new Program();
try
{
p.RunTest();
}
catch (Exception f)
{
Console.WriteLine(f.Message);
Console.ReadLine();
}
}
internal void RunTest()
{
FileStream fs = File.OpenRead(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\CoverPage.pdf");
_pdfTemplateStream = fs;
_pdfResultStream = new MemoryStream();
//PDFTemplateStream = new FileStream(_templatePath, FileMode.Open);
_pdfTemplateReader = new PdfReader(_pdfTemplateStream);
_pdfResultStamper = new PdfStamper(_pdfTemplateReader, _pdfResultStream);
#region setup objects
List<CustomCategory> Categories = new List<CustomCategory>();
CustomCategory c1 = new CustomCategory();
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[2]);
Categories.Add(c1);
CustomCategory c2 = new CustomCategory();
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[0]);
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
Categories.Add(c2);
List<CustomObject> Items = new List<CustomObject>();
CustomObject co1 = new CustomObject();
co1.Category = c1;
co1.Title = "Object 1";
Items.Add(co1);
CustomObject co2 = new CustomObject();
co2.Category = c2;
co2.Title = "Object 2";
Items.Add(co2);
#endregion
FillCoverPage(Items);
_pdfResultStamper.Close();
_pdfTemplateReader.Close();
List<MemoryStream> pdfStreams = new List<MemoryStream>();
pdfStreams.Add(new MemoryStream(_pdfResultStream.ToArray()));
MergePdfs(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\Outfile.pdf", pdfStreams);
_pdfResultStream.Dispose();
_pdfTemplateStream.Dispose();
}
internal void FillCoverPage(List<CustomObject> Items)
{
//Before we start we need to figure out where to start adding the table
var fieldPositions = _pdfResultStamper.AcroFields.GetFieldPositions("TableStartPosition");
if (fieldPositions == null)
{ throw new Exception("Could not find the TableStartPosition field. Unable to determine point of origin for the table!"); }
_pdfResultStamper.AcroFields.RemoveField("TableStartPosition");
var fieldPosition = fieldPositions[0];
// Get the position of the field
var targetPosition = fieldPosition.position;
//First, get all the available card sizes
List<string> availableSizes = CustomCategory.AvailableSizes;
//Generate a table with the number of available card sizes + 1 for the device name
PdfPTable table = new PdfPTable(availableSizes.Count + 1);
float[] columnWidth = new float[availableSizes.Count + 1];
for (int y = 0; y < columnWidth.Length; y++)
{
if (y == 0)
{ columnWidth[y] = 320; }
else
{ columnWidth[y] = 120; }
}
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
PdfContentByte canvas;
List<PdfFormField> checkboxes = new List<PdfFormField>();
//Build the header row
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
//Insert the global check boxes
PdfPCell[] globalRow = new PdfPCell[availableSizes.Count + 1];
Phrase tPhrase = new Phrase("Select/Unselect All");
PdfPCell tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
tCell.AddElement(tPhrase);
globalRow[0] = tCell;
for (int x = 0; x < availableSizes.Count; x++)
{
tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.Global.chk{0}", availableSizes[x].Replace(".", ""));
//f.FieldName = fieldName;
string js = string.Format("hideAll(event.target, '{0}');", availableSizes[x].Replace(".", ""));
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
globalRow[x + 1] = tCell;
checkboxes.Add(f);
}
table.Rows.Add(new PdfPRow(globalRow));
int status = 0;
int pageNum = 1;
for (int itemIndex = 0; itemIndex < Items.Count; itemIndex++)
{
tCell = new PdfPCell();
Phrase p = new Phrase(Items[itemIndex].Title);
tCell.AddElement(p);
tCell.HorizontalAlignment = Element.ALIGN_LEFT;
PdfPCell[] cells = new PdfPCell[availableSizes.Count + 1];
cells[0] = tCell;
for (int availCardSizeIndex = 0; availCardSizeIndex < availableSizes.Count; availCardSizeIndex++)
{
if (Items[itemIndex].Category.CategorySizesInUse.Contains(availableSizes[availCardSizeIndex]))
{
string str = availableSizes[availCardSizeIndex];
tCell = new PdfPCell();
tCell.PaddingLeft = 10f;
tCell.PaddingRight = 10f;
cells[availCardSizeIndex + 1] = tCell;
cells[availCardSizeIndex].HorizontalAlignment = Element.ALIGN_CENTER;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.chk{0}.{1}", availableSizes[availCardSizeIndex].Replace(".", ""), itemIndex + 1);
//f.FieldName = fieldName; <-- This causes the checkbox to be double-named (i.e. InkSaver.Global.chk0.InkSaver.Global.chk0
string js = string.Format("hideCardSize(event.target, {0}, '{1}');", itemIndex + 1, availableSizes[availCardSizeIndex]);
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
checkboxes.Add(f);
}
else
{
//Add a blank cell
tCell = new PdfPCell();
cells[availCardSizeIndex + 1] = tCell;
}
}
//Test if the column text will fit
table.Rows.Add(new PdfPRow(cells));
canvas = _pdfResultStamper.GetUnderContent(pageNum);
ColumnText ct2 = new ColumnText(canvas);
ct2.AddElement(new PdfPTable(table));
ct2.Alignment = Element.ALIGN_LEFT;
ct2.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
status = ct2.Go(true);
if ((status != ColumnText.NO_MORE_TEXT) || (itemIndex == (Items.Count - 1)))
{
ColumnText ct3 = new ColumnText(canvas);
ct3.AddElement(table);
ct3.Alignment = Element.ALIGN_LEFT;
ct3.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
ct3.Go();
foreach (PdfFormField f in checkboxes)
{
_pdfResultStamper.AddAnnotation(f, pageNum);
}
checkboxes.Clear();
if (itemIndex < (Items.Count - 1))
{
pageNum++;
_pdfResultStamper.InsertPage(pageNum, _pdfTemplateReader.GetPageSize(1));
table = new PdfPTable(availableSizes.Count + 1);
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
}
}
}
}
private PdfPCell[] GetTableHeaderRow(List<string> AvailableSizes)
{
PdfPCell[] sizeHeaders = new PdfPCell[AvailableSizes.Count + 1];
Phrase devName = new Phrase("Device Name");
PdfPCell deviceHeader = new PdfPCell(devName);
deviceHeader.HorizontalAlignment = Element.ALIGN_CENTER;
deviceHeader.BackgroundColor = BaseColor.GRAY;
sizeHeaders[0] = deviceHeader;
for (int x = 0; x < AvailableSizes.Count; x++)
{
PdfPCell hCell = new PdfPCell(new Phrase(AvailableSizes[x]));
hCell.HorizontalAlignment = Element.ALIGN_CENTER;
hCell.BackgroundColor = BaseColor.GRAY;
sizeHeaders[x + 1] = hCell;
}
return sizeHeaders;
}
public void MergePdfs(string filePath, List<MemoryStream> pdfStreams)
{
//Create output stream
FileStream outStream = new FileStream(filePath, FileMode.Create);
Document document = null;
if (pdfStreams.Count > 0)
{
try
{
int PageCounter = 0;
//Create Main reader
PdfReader reader = new PdfReader(pdfStreams[0]);
PageCounter = reader.NumberOfPages;//This is if we have multiple pages in the cover page, we need to adjust the offset.
//rename fields in the PDF. This is required because PDF's cannot have more than one field with the same name
RenameFields(reader, PageCounter++);
//Create Main Doc
document = new Document(reader.GetPageSizeWithRotation(1));
//Create main writer
PdfCopy Writer = new PdfCopy(document, outStream);
//PdfCopyFields Writer = new PdfCopyFields(outStream);
//Open document for writing
document.Open();
////Add pages
Writer.AddDocument(reader);
//For each additional pdf after first combine them into main document
foreach (var PdfStream in pdfStreams.Skip(1))
{
PdfReader reader2 = new PdfReader(PdfStream);
//rename PDF fields
RenameFields(reader2, PageCounter++);
// Add content
Writer.AddDocument(reader);
}
//Writer.AddJavaScript(PostProcessing.GetSuperscriptJavaScript());
Writer.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (document != null)
document.Close();
foreach (var Strm in pdfStreams)
{
try { if (null != Strm) Strm.Dispose(); }
catch { }
}
//pdfStamper.Close();
outStream.Close();
}
}
}
private void RenameFields(PdfReader reader, int PageNum)
{
int tempPageNum = 1;
//rename all fields
foreach (string field in reader.AcroFields.Fields.Keys)
{
if (((reader.AcroFields.GetFieldType(field) == 1) || (reader.AcroFields.GetFieldType(field) == 2)) && (field.StartsWith("InkSaver")))
{
//This is a InkSaver button, set the name so its subclassed
string classPath;
if (reader.AcroFields.GetFieldType(field) == 2)
{
classPath = field.Substring(0, field.LastIndexOf("."));
if (field.StartsWith("InkSaver.chk"))
{
int a = field.LastIndexOf(".");
string sub = field.Substring(a + 1, (field.Length - a - 1));
int pageNum = int.Parse(sub);
int realPageNum = pageNum + tempPageNum;//PostProcessing.Instance.CoverPageLength;
PageNum = realPageNum;
}
}
else
{
classPath = field.Substring(0, field.LastIndexOf("."));
}
string newID = classPath + ".page" + PageNum.ToString();
bool ret = reader.AcroFields.RenameField(field, newID);
}
else
{
reader.AcroFields.RenameField(field, field + "_" + PageNum.ToString());// field + Guid.NewGuid().ToString("N"));
}
}
}
}
public class ChildFieldEvent : IPdfPCellEvent
{
protected PdfWriter writer;
protected PdfFormField parent;
protected string checkBoxName;
internal ChildFieldEvent(PdfWriter writer, PdfFormField parent, string CheckBoxName)
{
this.writer = writer;
this.parent = parent;
this.checkBoxName = CheckBoxName;
}
public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb)
{
createCheckboxField(rect);
}
private void createCheckboxField(Rectangle rect)
{
RadioCheckField bt = new RadioCheckField(this.writer, rect, this.checkBoxName, "Yes");
bt.CheckType = RadioCheckField.TYPE_SQUARE;
bt.Checked = true;
this.parent.AddKid(bt.CheckField);
}
}
internal class CustomCategory
{
internal static List<string> AvailableSizes
{
get
{
List<string> retVal = new List<string>();
retVal.Add("1");
retVal.Add("2");
retVal.Add("3");
retVal.Add("4");
return retVal;
}
}
internal CustomCategory()
{
CategorySizesInUse = new List<string>();
}
internal List<string> CategorySizesInUse { get; set; }
}
internal class CustomObject
{
internal string Title { get; set; }
internal CustomCategory Category { get;set; }
}
Please take a look at the MergeForms example. Your example is too long for me to read, but at first sight, I'm missing the following line:
copy.setMergeFields();
By the way, in MergeForms2, the fields are also renamed before the form is merged.

How to implement boolean retrieval using hitcollector in below scenario

I am running my code on TREC documents and right now implementing scoring scheme to get number of relevant documents. However now i want to implement boolean retrieval, I am trying to use HitCollector.
below is my code..
public class BatchSearch {
private BatchSearch() {}
/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
String usage =
"Usage:\tjava BatchSearch [-index dir] [-simfn similarity] [-field f] [-queries file]";
if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)\n");
System.exit(0);
}
String index = "index";
String field = "contents";
String queries = null;
String simstring = "default";
for(int i = 0;i < args.length;i++) {
if ("-index".equals(args[i])) {
index = args[i+1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i+1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i+1];
i++;
} else if ("-simfn".equals(args[i])) {
simstring = args[i+1];
i++;
}
}
Similarity simfn = null;
if ("default".equals(simstring)) {
simfn = new DefaultSimilarity();
} else if ("bm25".equals(simstring)) {
simfn = new BM25Similarity();
} else if ("dfr".equals(simstring)) {
simfn = new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH2());
} else if ("lm".equals(simstring)) {
simfn = new LMDirichletSimilarity();
}
if (simfn == null) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)");
System.out.println("bm25: BM25Similarity (standard parameters)");
System.out.println("dfr: Divergence from Randomness model (PL2 variant)");
System.out.println("lm: Language model, Dirichlet smoothing");
System.exit(0);
}
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(simfn);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
} else {
in = new BufferedReader(new InputStreamReader(new FileInputStream("queries"), "UTF-8"));
}
QueryParser parser = new QueryParser(Version.LUCENE_41, field, analyzer);
while (true) {
String line = in.readLine();
if (line == null || line.length() == -1) {
break;
}
line = line.trim();
if (line.length() == 0) {
break;
}
String[] pair = line.split(" ", 2);
Query query = parser.parse(pair[1]);
doBatchSearch(in, searcher, pair[0], query, simstring);
}
reader.close();
}
/**
* This function performs a top-1000 search for the query as a basic TREC run.
*/
public static void doBatchSearch(BufferedReader in, IndexSearcher searcher, String qid, Query query, String runtag)
throws IOException {
// Collect enough docs to show 5 pages
TopDocs results = searcher.search(query, 1000);
ScoreDoc[] hits = results.scoreDocs;
HashMap<String, String> seen = new HashMap<String, String>(1000);
int numTotalHits = results.totalHits;
int start = 0;
int end = Math.min(numTotalHits, 1000);
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
String docno = doc.get("docno");
// There are duplicate document numbers in the FR collection, so only output a given
// docno once.
if (seen.containsKey(docno)) {
continue;
}
seen.put(docno, docno);
System.out.println(qid+" Q0 "+docno+" "+i+" "+hits[i].score+" "+runtag);
}
}
}
The scoring is done in doBatchSearch and now i want to implement HitCollector here.

Execute stored procedure in Entity Framework, return List<DataTable> or DataSet

How do I modify the below method to return a List< DataTable> or a DataSet? I want to make it generic so it can return multiple resultsets from the database.
public static DataTable ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
var dt = new DataTable();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
reader.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dt;
}
I ended up doing it like this -
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var connectionString = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;
var ds = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
}
}
}
return ds;
}
reader.NextResult() should technically work. Here is the modified version:
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
DataSet dataSet = new DataSet();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
do
{
DataTable dt = new DataTable();
dt.Load(reader);
dataSet.Tables.Add(dt);
}
while (reader.NextResult());
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dataSet;
}

saving email attachments as binary to the database using c#

I can get email attachments from exchange server 2003 (MAPI.Attachment). How can I save the pdf attachment file as binary into the database?
Here's some code to understand better. For testing purposes I am saving the attachment pdf file into a filesystem. How ca I go about saving that into a database? Or how can I convert that into a byte array? Also, how can I get the size of the file since I need that when I declare the byte array "fileData"...
byte[] fileData = new byte[10000];
string[] fileTokens = new string[2];
string[] result = new string[3];
message.Unread = false;
emailSubject = message.Subject.ToString();
emailBody = message.Text.ToString();
MAPI.Attachments test = null;
test = (MAPI.Attachments)message.Attachments;
int attachmentCount = (int)test.Count;
for (int loopCounter = 1; loopCounter <= attachmentCount; loopCounter++)
{
MAPI.Attachment test2 = (MAPI.Attachment)test.get_Item(loopCounter);
bool temp = (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0);
if (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0)
{
//test2.ReadFromFile(fileData);
test2.WriteToFile("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
}
RequestHistorySet historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);
bool res = historySet.Update();
message.Unread = false;
message.Update();
And here's the Update function from historySet Class
public bool Update()
{
using (SqlConnection mySqlConnection = ...))
{
// Set up the Command object
SqlCommand myCommand = new SqlCommand("CONNECTION STRING..", mySqlConnection);
// Set up the OriginalName parameter
SqlParameter prmId = new SqlParameter("#id", SqlDbType.Int);
prmId.Value = id;
myCommand.Parameters.Add(prmId);
SqlParameter prmRequsetDate = new SqlParameter("#requestDate", SqlDbType.DateTime);
prmRequsetDate.Value = requestDate;
myCommand.Parameters.Add(prmRequsetDate);
// Set up the FileData parameter
SqlParameter prmFileData = new SqlParameter("#uplodedQuote_File ", SqlDbType.VarBinary);
prmFileData.Value = fileData;
prmFileData.Size = fileData.Length;
myCommand.Parameters.Add(prmFileData);
SqlParameter prmFileExtension = new SqlParameter("#uplodedQuote_Ext", SqlDbType.NVarChar);
prmFileExtension.Value = fileExtension;
myCommand.Parameters.Add(prmFileExtension);
// Execute the command, and clean up.
mySqlConnection.Open();
bool result = myCommand.ExecuteNonQuery() > 0;
mySqlConnection.Close();
return result;
}
}
As of now this is what I have done. I save it to a filesystem and then read from there.
test2.WriteToFile("d:\\data\\" + test2.Name);
fileData = FileToByteArray("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
TryToDelete("d:\\data\\" + test2.Name);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);