I have implemented the Table() function in order to save the results generated by the application. However, it seems that the Timer function in the application causes the application to write over the existing CSV file each time it runs. Rather than write over the existing CSV file, I would like to append the newest search results to the existing CSV file. Is there a way to do this? Is it easier to append the results if the results are stored in a different format such as JSON?
Timer timer;
import java.util.List;
Table table;
long lastID = Long.MAX_VALUE;
void setup() {
timer = new Timer(30000);
timer.start();
goTwitter();
table = new Table();
table.addColumn("id");
table.addColumn("latitude");
table.addColumn("longitude");
}
void draw(){
if (timer.isFinished()){
goTwitter();
timer.start();
}
}
void goTwitter(){
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Query query = new Query("#love");
int numberOfTweets = 300;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
if (numberOfTweets - tweets.size() > 100)
query.setCount(100);
else
query.setCount(numberOfTweets - tweets.size());
//long lastID = Long.MAX_VALUE;
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
println("Gathered " + tweets.size() + " tweets");
for (Status t: tweets)
if(t.getId() < lastID) lastID = t.getId();
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
query.setSinceId(lastID);
}
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
String user = t.getUser().getScreenName();
String msg = t.getText();
String time = "";
if (loc!=null) {
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);
TableRow newRow = table.addRow();
newRow.setString("id", user);
newRow.setDouble("latitude", lat);
newRow.setDouble("longitude", lon);
saveTable(table, "data2/syria_16500_5.csv");
}
}
println("lastID= " + lastID);
}
class Timer {
int savedTime;
int totalTime;
Timer (int tempTotalTime) {
totalTime = tempTotalTime;
}
void start(){
savedTime = millis();
}
boolean isFinished() {
int passedTime = millis() - savedTime;
if (passedTime > totalTime){
return true;
} else {
return false;
}
}
}
Well, there does not seem to be a direct implementation to append to a table, so you'll have to resort to a hack: load the table in processing, write to it and resave it, sort of like this:
processing.data.Table table;
void setup() {
File f = new File(sketchPath("") + "data2/syria_16500_5.csv");
println(f.getAbsolutePath());
if (!f.exists()) {
table = new processing.data.Table();
table.addColumn("id");
table.addColumn("latitude");
table.addColumn("longitude");
}
else
table = loadTable("data2/syria_16500_5.csv", "header, csv");
TableRow newRow = table.addRow();
newRow.setString("id", "asad");
newRow.setDouble("latitude", 234);
newRow.setDouble("longitude", 2523);
saveTable(table, "data2/syria_16500_5.csv");
}
The sketch first checks if the file exists. If it does not, it creates a new table, otherwise it loads the old table in with its header.
Be warned, this is not particularly safe... If you change your columns (say, in a text editor) and try to run the sketch again you will get an exception.
Related
I'm trying to do a check to see if the user has a local file. If the user does, I get bloodycrypto to make a md5 out of it. Then I compare the two values. One from the firebase file's metadata and the other from the byte array of the file digested. They never match. Does Firebase do something different when trying to generate the md5 of a file I upload?
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA)
trace("Local hash = " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("Network hash = " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
if (byteHash != storageMetaData.md5Hash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
Upon closer inspetion (thanks to Organis) firebase doesn't return a proper MD5. What is it? In my storage consol I don't see an md5 property, so is this autogenerated? The files were uploaded through my rest API based off phantom's guide.
Update: Following Organis' comment about the way Firebase handle's MD5s
var byteHash:ByteArray = new ByteArray();
byteHash.writeUTFBytes(MD5.hashBytes(fileBA));
var byteHashWithLength:ByteArray = new ByteArray();
byteHashWithLength.writeUTF(MD5.hashBytes(fileBA));
trace("Bytehash with length = " + Base64.encode(byteHashWithLength)); //ACAyMTMzYTdmYjczYTEzZDQ3ZDkzMTEyY2I1OWQyYTBmMg==
trace("Plain = " + Base64.encode(byteHash)); //OTNiODg1YWRmZTBkYTA4OWNkZjYzNDkwNGZkNTlmNzE=
trace("Storage md5 = " + storageMetaData.md5Hash); //UsoNl5sL1+aLiAhTOTBXyQ==
Trying to take the md5 I get and turn it into base64 results in consistent mismatching results. Is there an argument I am missing or applying incorrectly when I try to decode everything?
...So I would do something like
var storageHash:String = Base64.decode(storageMetaData.md5Hash).toString();
to follow your example right?
Try this code below to get your storageMetaData.md5Hash correctly decoded from Base64 :
Let me know result of trace("storage hash : " + storageHash); to check if you're getting an (expected) sequence of 32 hex values.
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA); //Local hash
var ba_storageHash:ByteArray = new ByteArray();
ba_storageHash = Base64.decode(storageMetaData.md5Hash); //update ByteArray
var storageHash:String = bytesToHexString(ba_storageHash); //Hex values of bytes shown as String
trace("Network hash : " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
trace("Local hash : " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("storage hash : " + storageHash); //what is result??
if (byteHash != storageHash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
// # Byte values (Hex) shown as (returned) String type
private function bytesToHexString(input:ByteArray) : String
{
var strOut:String = ""; var strRead:String = "";
input.position = 0;
var intBASize:uint = input.length;
for (var i:int = 0; i < intBASize; i++)
{
strRead = input.readUnsignedByte().toString(16);
if(strRead.length < 2) { strRead = "0" + strRead; } //# do padding
strOut += strRead ;
}
return strOut.toLowerCase(); //strOut.toUpperCase();
}
I have some code that generates a PDF. For some reason there is a black bordered cell showing up behind the image on this line:
sb.AppendLine("<tr><td>" + "~/images/Products/" + imageName + "</td><td>~/images/spacer.gif</td></tr>");
I have tried setting the border to 0 on the table, but I'm getting an error ") expected", or the html just breaks.
How can I ensure that there is no border shown around this cell?
Here are the two parts involved:
//add images
str = new StringBuilder();
str.Append("<table>");
if (HasRelatedImages(ContentId, ref str))
{
obj = new List<FieldIdentifier>();
obj.Add(new FieldIdentifier() { LabelName = "Images", Value = "" });
index = index + 1;
rows.Add(index, obj);
obj = new List<FieldIdentifier>();
obj.Add(new FieldIdentifier() { LabelName = "NewTable_Data", Value = str.Append("</table>").ToString() });
index = index + 1;
rows.Add(index, obj);
}
//end images
and
private Boolean HasRelatedImages(long productId, ref StringBuilder sb)
{
var imagemetadata = new List<ImageMetadata>();
int i = 0;
try
{
Database db = DatabaseFactory.CreateDatabase("Site.DbConnection");
DbCommand dbCommand = db.GetStoredProcCommand("[spSelectImages]");
db.AddInParameter(dbCommand, "#ContentID", DbType.Int64, productId);
IDataReader dr = db.ExecuteReader(dbCommand);
while (dr.Read())
{
string imageName = GetNullableDBStringValue(dr["ImageName"]);
string altText = GetNullableDBStringValue(dr["ALTText"]);
altText = HttpUtility.HtmlEncode(altText);
if (!string.IsNullOrEmpty(imageName) && System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/images/Products/" + imageName)))
{
i++;
sb.AppendLine("<tr><td>" + i.ToString() + "</td><td>" + (string.IsNullOrEmpty(altText) ? " " : altText) + "</td></tr>");
sb.AppendLine("<tr><td>" + "~/images/Products/" + imageName + "</td><td>~/images/spacer.gif</td></tr>");
}
}
dr.Close();
}
catch
{
}
if (i > 0) return true;
return false;
}
There was other code involved adding the border. No change was needed to this piece.
I want to extract some data like " email addresses " .. from table which are in PDF file and use this email addresses which I extract to send email to those people.
What I have found so far through searching the web:
I have to convert the PDF file to Excel to read the data easily and use them as I want.
I find some free dll like itextsharp or PDFsharp.
But I didn't find any snippet code help to do this in C#. is there any solution ?
You absolutely do not have to convert PDF to Excel.
First of all, please determine whether your PDF contains textual data, or it is scanned image.
If it contains textual data, then you are right about using "some free dll". I recommend iTextSharp as it is popular and easy to use.
Now the controversial part. If you don't need rock solid solution, it would be easiest to read all PDF to a string and then retrieve emails using regular expression.
Here is example (not perfect) of reading PDF with iTextSharp and extracting emails:
public string PdfToString(string fileName)
{
var sb = new StringBuilder();
var reader = new PdfReader(fileName);
for (int page = 1; page <= reader.NumberOfPages; page++)
{
var strategy = new SimpleTextExtractionStrategy();
string text = PdfTextExtractor.GetTextFromPage(reader, page, strategy);
text = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(text)));
sb.Append(text);
}
reader.Close();
return sb.ToString();
}
//adjust expression as needed
Regex emailRegex = new Regex("Email Address (?<email>.+?) Passport No");
public IEnumerable<string> ExtractEmails(string content)
{
var matches = emailRegex.Matches(content);
foreach (Match m in matches)
{
yield return m.Groups["email"].Value;
}
}
Using bytescout PDF Extractor SDK we can be able to extract the whole page to csv as below.
CSVExtractor extractor = new CSVExtractor();
extractor.RegistrationName = "demo";
extractor.RegistrationKey = "demo";
TableDetector tdetector = new TableDetector();
tdetector.RegistrationKey = "demo";
tdetector.RegistrationName = "demo";
// Load the document
extractor.LoadDocumentFromFile("C:\\sample.pdf");
tdetector.LoadDocumentFromFile("C:\\sample.pdf");
int pageCount = tdetector.GetPageCount();
for (int i = 1; i <= pageCount; i++)
{
int j = 1;
do
{
extractor.SetExtractionArea(tdetector.GetPageRect_Left(i),
tdetector.GetPageRect_Top(i),
tdetector.GetPageRect_Width(i),
tdetector.GetPageRect_Height(i)
);
// and finally save the table into CSV file
extractor.SavePageCSVToFile(i, "C:\\page-" + i + "-table-" + j + ".csv");
j++;
} while (tdetector.FindNextTable()); // search next table
}
public void Convert(string fileNames) {
int pageCount = 0;
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(fileNames);
pageCount = reader.NumberOfPages;
string ext = System.IO.Path.GetExtension(fileNames);
//string[] outfiles = new string[pageCount];
//Excel.Application app = new Excel.Application();
//app.Workbooks.Add("");
CSVExtractor extractor = new CSVExtractor();
//string outfilePDF1 = fileNames.Replace((System.IO.Path.GetFileName(fileNames)), (System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_rez" + ".csv"));
string outfilePDFExcel1 = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
(System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_rez" + ".xls"));
extractor.RegistrationName = "demo";
extractor.RegistrationKey = "demo";
string folderName = #"C:\Users\Dafina\Desktop\PDF_EditProject\PDF_EditProject\PDFs";
string pathString = System.IO.Path.Combine(folderName, System.IO.Path.GetFileName(fileNames).Replace(".pdf", "")) + "-CSVs";
System.IO.Directory.CreateDirectory(pathString);
for (int i = 0; i < pageCount; i++)
{
string outfilePDF = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
(System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_" + (i + 1).ToString()) + ext);
extractor.LoadDocumentFromFile(outfilePDF);
//string outfile = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
// (System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "_" + (i + 1).ToString()) + ".csv");
string outfile = fileNames.Replace((System.IO.Path.GetFileName(fileNames)),
(System.IO.Path.GetFileName(fileNames).Replace(".pdf", "") + "-CSVs\\" + "Sheet_" + (i + 1).ToString()) + ".csv");
extractor.SaveCSVToFile(outfile);
}
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
Console.WriteLine("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
string[] cvsFiles = Directory.GetFiles(pathString);
Array.Sort(cvsFiles, new AlphanumComparatorFast());
//string[] lista = new string[pageCount];
//for (int t = 0; t < pageCount; t++)
//{
// lista[t] = cvsFiles[t];
//}
//Array.Sort(lista, new AlphanumComparatorFast());
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
for (int i = 0; i < cvsFiles.Length; i++)
{
int sheet = i + 1;
xlWorkSheet = xlWorkBook.Sheets[sheet];
if (i < cvsFiles.Length - 1)
{
xlWorkBook.Worksheets.Add(Type.Missing, xlWorkSheet, Type.Missing, Type.Missing);
}
int sheetRow = 1;
Encoding objEncoding = Encoding.Default;
StreamReader readerd = new StreamReader(File.OpenRead(cvsFiles[i]));
int ColumLength = 0;
while (!readerd.EndOfStream)
{
string line = readerd.ReadLine();
Console.WriteLine(line);
try
{
string[] columns = line.Split((new char[] { '\"' }));
for (int col = 0; col < columns.Length; col++)
{
if (ColumLength < columns.Length)
{
ColumLength = columns.Length;
}
if (col % 2 == 0)
{
}
else if (columns[col] == "")
{
}
else
{
xlWorkSheet.Cells[sheetRow, col + 1] = columns[col].Replace("\"", "");
}
}
sheetRow++;
}
catch (Exception e)
{
string msg = e.Message;
}
}
int k = 1;
for (int s = 1; s <= ColumLength; s++)
{
xlWorkSheet.Columns[k].Delete();
k++;
}
releaseObject(xlWorkSheet);
readerd.Close();
}
xlWorkBook.SaveAs(outfilePDFExcel1, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkBook);
releaseObject(xlApp);
var dir = new DirectoryInfo(pathString);
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
dir.Delete(true);
}
Probably the Best code would be to use Third party dll
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
string pathToPdf = #"D:\abc\abc.pdf";
string pathToExcel = Path.ChangeExtension(pathToPdf, ".xls");
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
f.ExcelOptions.ConvertNonTabularDataToSpreadsheet = false;
// 'true' = Preserve original page layout.
// 'false' = Place tables before text.
f.ExcelOptions.PreservePageLayout = true;
// The information includes the names for the culture, the writing system,
// the calendar used, the sort order of strings, and formatting for dates and numbers.
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
ci.NumberFormat.NumberDecimalSeparator = ",";
ci.NumberFormat.NumberGroupSeparator = ".";
f.ExcelOptions.CultureInfo = ci;
f.OpenPdf(pathToPdf);
if (f.PageCount > 0)
{
int result = f.ToExcel(pathToExcel);
// Open the resulted Excel workbook.
if (result == 0)
{
System.Diagnostics.Process.Start(pathToExcel);
}
}
}
}
}
I am working on a wp8 project and need to find the location . I've used windows.device.geoloaction name space to find the lattitude and longitude now I need to find the address(country state and zip). I found this example but I am confused how to pass the coordinates that I obtained . Here is my code.
public async void FindTADeviceLocation()
{
////Declare Geolocator object
Geolocator geolocator = new Geolocator();
// Set user's accuracy
geolocator.DesiredAccuracy = PositionAccuracy.High;
//get the position of the user.
try
{
//The await guarantee the calls to be returned on the thread from which they were called
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(1),
timeout: TimeSpan.FromSeconds(10)
);
var geoQ = new ReverseGeocodeQuery();
geoQ.QueryCompleted += geoQ_QueryCompleted;
if (geoQ.IsBusy == true)
{
geoQ.CancelAsync();
}
// Set the geo coordinate for the query
geoQ.GeoCoordinate = geoposition.Coordinate;
geoQ.QueryAsync();
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
MessageBox.Show("position is unknown");
}
}
}
void geoQ_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Result.Count() > 0)
{
string showString = e.Result[0].Information.Name;
showString = showString + "\nAddress: ";
showString = showString + "\n" + e.Result[0].Information.Address.PostalCode + " " + e.Result[0].Information.Address.City;
showString = showString + "\n" + e.Result[0].Information.Address.Country + " " + e.Result[0].Information.Address.CountryCode;
showString = showString + "\nDescription: ";
showString = showString + "\n" + e.Result[0].Information.Description.ToString();
MessageBox.Show(showString);
}
}
I know the problem is in the line geoQ.GeoCoordinate = geoposition.Coordinate;
But how can I pass the coordinates to geoQ.GeoCoordinate?
Thanks in adwance
This is done. The geocordinate takes arguments of the type double. so all we've to do is to convert the cordiantes into double and pass it.
var currentLocationLatitude = Convert.ToDouble(geoposition.Coordinate.Latitude.ToString("0.0000000000000"));
var currentLocationLongitude = Convert.ToDouble(geoposition.Coordinate.Longitude.ToString("0.0000000000000"));
var geoQ = new ReverseGeocodeQuery();
geoQ.QueryCompleted += geoQ_QueryCompleted;
if (geoQ.IsBusy == true)
{
geoQ.CancelAsync();
}
// Set the geo coordinate for the query
geoQ.GeoCoordinate = new GeoCoordinate(currentLocationLatitude, currentLocationLongitude);
geoQ.QueryAsync();
Thanks
I am new to application block.
I am trying to get data from database. Following is the code snap.
JsonResponse.ashx:
public void ProcessRequest(HttpContext context)
{
HttpContext _context = HttpContext.Current;
context.Response.ContentType = "application/json";
int user_id = Convert.ToInt32(HttpContext.Current.Session["userid"]);
DateTime start = new DateTime(1970, 1, 1);
DateTime end = new DateTime(1970, 1, 1);
start = start.AddSeconds(double.Parse(context.Request.QueryString["start"]));
end = end.AddSeconds(double.Parse(context.Request.QueryString["end"]));
String result = String.Empty;
result += "[";
List<int> idList = new List<int>();
foreach (CalendarEvent cevent in EventDAO.getEvents(start, end, user_id))
{
result += convertCalendarEventIntoString(cevent);
idList.Add(cevent.id);
}
if (result.EndsWith(","))
{
result = result.Substring(0, result.Length - 1);
}
result += "]";
//store list of event ids in Session, so that it can be accessed in web methods
context.Session["idList"] = idList;
context.Response.Write(result);
}
private String convertCalendarEventIntoString(CalendarEvent cevent)
{
String allDay = "true";
if (ConvertToTimestamp(cevent.start).ToString().Equals(ConvertToTimestamp(cevent.end).ToString()))
{
if (cevent.start.Hour == 0 && cevent.start.Minute == 0 && cevent.start.Second == 0)
{
allDay = "true";
}
else
{
allDay = "false";
}
}
else
{
if (cevent.start.Hour == 0 && cevent.start.Minute == 0 && cevent.start.Second == 0
&& cevent.end.Hour == 0 && cevent.end.Minute == 0 && cevent.end.Second == 0)
{
allDay = "true";
}
else
{
allDay = "false";
}
}
return "{" +
"id: '" + cevent.id + "'," +
"title: '" + HttpContext.Current.Server.HtmlEncode(cevent.title) + "'," +
"start: " + ConvertToTimestamp(cevent.start).ToString() + "," +
"end: " + ConvertToTimestamp(cevent.end).ToString() + "," +
"allDay:" + allDay + "," +
"user_id:" + cevent.user_id + "," +
"description: '" + HttpContext.Current.Server.HtmlEncode(cevent.description) + "'" +
"},";
}
DA:
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
return SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
}
sqlhelper:
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 120;
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
//return the dataset
return ds;
}
I am getting error:
Cannot implicitly convert type 'System.Data.DataSet' to 'System.Collections.Generic.List'.
I am unable to understand what is the problem.
In getEvents method, you need to iterate through the records in the dataset and fill in the list that you would return in this method.
var dataset = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
foreach (var row in ds.Tables["FooTable"].Rows)
{
events.Add(new CalendarEvent(...));
}
return events;
That's because you try to return a dataset as List, which it isn't.
You need to convert the dataset to a list. A possible solution would be to change the getEvents method to something like this ->
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
var ds = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
return ds.Tables[0].AsEnumerable().Select(datarow => new CalendarEvent{ Title = datarow.Field<string>("Title), /*the rest of your params*/}).ToList();
}
Your problem is this piece of code:
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
return SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
}
You defined the type of this method as List<CalenderEvent> but you return a DataSet.
I do not know which datatables are contained in your dataset, but I assume there is one which represents your calenderevents.
This means you need to extract the data you want from your dataset and make a list out of it. Assuming there is one table in your dataset your new method would look something like this:
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, int user_id)
{
List<CalendarEvent> events = new List<CalendarEvent>();
SqlParameter[] sqlParam = new SqlParameter[3];
sqlParam[0] = new SqlParameter("#start", start);
sqlParam[1] = new SqlParameter("#end", end);
sqlParam[2] = new SqlParameter("#user_id", user_id);
var data = SqlHelper.ExecuteDataset(connectionString,CommandType.StoredProcedure, "GetData", sqlParam);
events = ds.Tables[0].AsEnumerable().Select(r => new CalenderEvent
{
//using dummy properties because I dont know
//your class
Property1 = r.Field<string>("Column1"),
Property2 = r.Field<string>("column2"),
//...
}).ToList();
return events;
}