I am using this code to try and retrieve steps made in the last 14 hours.
YApp myApp = (mYApp) ctx;
mGoogleApiClient = myApp.getMyUser();
mGoogleApiClient.reconnect();
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -16);
long startTime = cal.getTimeInMillis();
PendingResult<DataReadResult> pendingResult =
Fitness.HistoryApi.readData(mGoogleApiClient, new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build());
DataReadResult dataReadResult = pendingResult.await();
DataSet ds = dataReadResult.getDataSet(DataType.AGGREGATE_STEP_COUNT_DELTA);
My datareadresult returns success but when I try and read the results into the dataset I get this error
java.lang.IllegalArgumentException: Attempting to read data for com.google.step_count.delta, which was not requested
I have tried all manner of DataTypes but receive the same error everytime, what am I doing wrong?!
For anyone else that gets frustrated over this :)
mYApp myApp = (mYApp) ctx;
mGoogleApiClient = myApp.getMyUser();
mGoogleApiClient.reconnect();
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -12);
long startTime = cal.getTimeInMillis();
PendingResult<DataReadResult> pendingResult =
Fitness.HistoryApi.readData(mGoogleApiClient, new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build());
DataReadResult dataReadResult = pendingResult.await();
if (dataReadResult.getBuckets().size() > 0) {
Log.i(TAG, "Number of returned buckets of DataSets is: "
+ dataReadResult.getBuckets().size());
for (Bucket bucket : dataReadResult.getBuckets()) {
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
for (DataPoint dp : dataSet.getDataPoints()) {
Log.i(TAG, "Data point:");
Log.i(TAG, "\tType: " + dp.getDataType().getName());
Log.i(TAG, "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
Log.i(TAG, "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
for(Field field : dp.getDataType().getFields()) {
Log.i(TAG, "\tField: " + field.getName() +
" Value: " + dp.getValue(field));
}
}
}
}
} else if (dataReadResult.getDataSets().size() > 0) {
Log.i(TAG, "Number of returned DataSets is: "
+ dataReadResult.getDataSets().size());
for (DataSet dataSet : dataReadResult.getDataSets()) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
for (DataPoint dp : dataSet.getDataPoints()) {
Log.i(TAG, "Data point:");
Log.i(TAG, "\tType: " + dp.getDataType().getName());
Log.i(TAG, "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
Log.i(TAG, "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)));
for (Field field : dp.getDataType().getFields()) {
Log.i(TAG, "\tField: " + field.getName() +
" Value: " + dp.getValue(field));
}
}
}
}
Just to clarify
PendingResult<DataReadResult> pendingResult =
Fitness.HistoryApi.readData(mGoogleApiClient, new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build());
Retruns a DataReadResult with a list of buckets.
PendingResult<DataReadResult> pendingResult =
Fitness.HistoryApi.readData(mGoogleApiClient, new DataReadRequest.Builder()
.read(DataType.TYPE_STEP_COUNT_DELTA)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build());
Returns a DataReadResult with a DataSet that can be fetched with
dataReadResult.getDataSet(DataType.TYPE_STEP_COUNT_DELTA);
Related
good work
v.b.net I will start a new project on my project and my purpose in this project from the database to extract data from certain tables and I want to save as csv
"##FILE VERSION##","251" "##TABLEDEF START##"
"MESAJ=String,50,""MESAJ"","""",50,Data,"""""
"ID=Integer,0,""ID"","""",10,Data,"""""
"SUBEIND=Integer,0,""SUBEIND"","""",10,Data,"""""
"KASAIND=Integer,0,""KASAIND"","""",10,Data,""""" "##INDEXDEF START##"
"##INDEXDEF END##" "##TABLEDEF END##"
"MESAJ","ID","SUBEIND","KASAIND", "YeniFirma","112","100","101",
"YeniCari","100","100","101", "YeniStok","101","100","101", –
Send your sql dataset result as a parameter to this function. It create csv format for you.
public string ConvertToCSV(DataSet objDataSet)
{
StringBuilder content = new StringBuilder();
if (objDataSet.Tables.Count >= 1)
{
System.Data.DataTable table = objDataSet.Tables[0];
if (table.Rows.Count > 0)
{
DataRow dr1 = (DataRow)table.Rows[0];
int intColumnCount = dr1.Table.Columns.Count;
int index = 1;
foreach (DataColumn item in dr1.Table.Columns)
{
content.Append(String.Format("\"{0}\"", item.ColumnName));
if (index < intColumnCount)
content.Append(",");
else
content.Append("\r\n");
index++;
}
foreach (DataRow currentRow in table.Rows)
{
string strRow = string.Empty;
for (int y = 0; y <= intColumnCount - 1; y++)
{
strRow += "\"" + currentRow[y].ToString() + "\"";
if (y < intColumnCount - 1 && y >= 0)
strRow += ",";
}
content.Append(strRow + "\r\n");
}
}
}
This function send a mail:
public void sendMail(string csv)
{
var sendMailThread = new Thread(() =>
{
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv));
Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
attachment.Name = DateTime.Now.ToShortDateString() + "Report.csv";
MailMessage ePosta = new MailMessage();
ePosta.From = new MailAddress("xx");
ePosta.To.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.CC.Add("xxx");
ePosta.Attachments.Add(attachment);
ePosta.Subject = DateTime.Now + " Subject";
ePosta.Body = DateTime.Now + " body message.";
SmtpClient smtp = new SmtpClient();
smtp.Credentials = new System.Net.NetworkCredential("xxx", "xxx");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
object userState = ePosta;
smtp.SendAsync(ePosta, (object)ePosta);
});
sendMailThread.Start();
}
I have built an SSIS package which reads CSV from certain folder. But now I need to download same csv from exchange server.Also Outlook is not installed on my machine. Will I be able to download CSV from exchange server and how ? Thanks!
I have used some of the code from the link http://sqlandbilearning.blogspot.com.au/2014/07/download-email-attachment-using-ssis.html but i have added some new code for removing TCP binding error using ServicePointManager as well as added search filter for retrieving specific emails and this code also takes care of multiple attachment from different emails to be saved on file system.
public void Main()
{
string filePath = "";
string fileName = "";
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
DateTime now = DateTime.Now;
DateTime beginRecievedTime = new DateTime(now.Year, now.Month, now.Day, 7, 55, 0);
DateTime finishRecievedTime = new DateTime(now.Year, now.Month, now.Day, 8, 15, 0);
EmailMessage latestEmail = null;
try
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.UseDefaultCredentials = true;
//service.Credentials = new WebCredentials("username", "password");
service.Url = new Uri("");
// 10 mails per page in DESC order
ItemView view = new ItemView(10);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Scheduled search"));
SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginRecievedTime);
searchFilterCollection.Add(greaterthanfilter);
SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, finishRecievedTime);
searchFilterCollection.Add(lessthanfilter);
SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
//Find mails
FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Inbox, filter, view);
Dictionary<EmailMessage, string> emailsMap = new Dictionary<EmailMessage, string>();
foreach (Item item in fir.Items)
{
item.Load(); //Load the entire message with attachment
EmailMessage email = item as EmailMessage;
if (email != null)
{
if (email.HasAttachments == true && email.Attachments.Count == 1)
{
if (email.Subject.StartsWith("Scheduled search") == true)
{
filePath = Path.Combine(Dts.Variables["User::SourceFolderPath"].Value.ToString()
, email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name);
// fileName = email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
// email.Attachments[0].Name.ToString();
emailsMap.Add(email, filePath);
}
}
}
}
if (emailsMap.Count > 0) {
foreach (var item in emailsMap) {
//Save attachment
EmailMessage email = item.Key;
filePath = item.Value;
FileAttachment fileAttachment = email.Attachments[0] as FileAttachment;
fileAttachment.Load(filePath);
string extractPath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.Attachments[0].Name;
System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath);
fileName = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
email.Attachments[0].Name.ToString();
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
}
// Dts.Variables["User::SourceFileName"].Value = fileName;
Dts.TaskResult = (int)ScriptResults.Success;
}
catch(System.Runtime.InteropServices.COMException ex)
{
if (Dts.Variables.Locked == true)
{
Dts.Variables.Unlock();
}
//An error occurred.
Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
I have a schedule nodejs script. Basically, it has schedule and command tables. Schedule table have many command row. The nodejs script checks the schedule table every 5 seconds. If it is the scheduled time matching up current time. I insert the command row (from schedule table) to command table.
The bug is
I run my script on my laptop and testing local copy of the database on my laptop. A single command in schedule table is only inserted once.
I run my script on my laptop and testing RDS (remote mysql server) on my laptop. A single command in schedule table is only inserted twice, but one of them, SchduleId is null. (Why ScheduleId is NULL?)
Full code
var config = require("./config.js");
var Promise = require('bluebird');
var mysql = require('promise-mysql');
var ON_DEATH = require('death');
var g_pool = null;
function connect_db() {
g_pool = mysql.createPool(config.db_config);
}
function close_db() {
g_pool.end(function (err) {
// all connections in the pool have ended
});
}
// http://thecodeship.com/web-development/alternative-to-javascript-evil-setinterval/
function interval(func, wait, times){
var interv = function(w, t) {
return function() {
if(typeof t === "undefined" || t-- > 0) {
setTimeout(interv, w);
try {
func.call(null);
}
catch(e) {
t = 0;
throw e.toString();
}
}
};
}(wait, times);
setTimeout(interv, wait);
}
function get_current_utc_time() {
var curr_date_obj = new Date();
var time_utc = "";
// somehow the date format is not accurate.
//var time_utc = dateFormat(now, "yyyy-mm-dd h:MM:ss", true);
var year = curr_date_obj.getUTCFullYear();
var month = add_zero(curr_date_obj.getUTCMonth() + 1); // count from 0
var date = add_zero(curr_date_obj.getUTCDate()); // count from 1
var hr = add_zero(curr_date_obj.getUTCHours());
var min = add_zero(curr_date_obj.getUTCMinutes());
// we ignore the second
var sec = "00";
time_utc = year + "-" + month + "-" + date + " " + hr + ":" + min + ":" + sec;
console.log("-current utc-");
console.log(time_utc);
return time_utc;
};
// http://www.w3schools.com/jsref/jsref_getutchours.asp
function add_zero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function insert_into_pending_cmd(msg_obj) {
console.log();
console.log("-insert_into_pending_cmd-");
var schedule_id = msg_obj.schedule_id;
var device_name = msg_obj.device_name;
var cmd = msg_obj.cmd;
var is_pending = msg_obj.is_pending;
if(is_pending) {
return Promise.resolve();
}
else {
var curr_time = get_current_utc_time();
var sql = "insert into Command set CommandDate = " + "'" + curr_time + "'" + "," + "RemoteName = " + "'" + device_name + "'" + "," + "CommandJSON = " + "'" + cmd + "'" + "," + "CommandComplete = 0" + "," + "ScheduleId = " + "'" + schedule_id + "'";
return g_pool.query(sql).then(function(){
return Promise.resolve();
});
}
}
function is_schedule_cmd_already_pending(msg_obj) {
console.log();
console.log("-is_schedule_cmd_already_pending-");
var schedule_id = msg_obj.schedule_id;
var device_name = msg_obj.device_name;
var cmd = msg_obj.cmd;
var is_run = msg_obj.is_run;
var local_msg_obj = {};
if(is_run) {
var sql = "select count(*) as num from Command where ScheduleId = " + "'" + schedule_id + "'" + " and CommandComplete = 0 and (UNIX_TIMESTAMP(UTC_TIMESTAMP()) - UNIX_TIMESTAMP(CommandDate)) < 600 and (UNIX_TIMESTAMP(UTC_TIMESTAMP()) - UNIX_TIMESTAMP(CommandDate)) > 0";
return g_pool.query(sql).then(function(rows){
var num = rows[0].num;
if(num == 0) {
local_msg_obj = {
schedule_id: schedule_id,
device_name: device_name,
cmd: cmd,
is_pending: false
};
return Promise.resolve(local_msg_obj);
}
else {
local_msg_obj = {
schedule_id: schedule_id,
device_name: device_name,
cmd: cmd,
is_pending: true
};
return Promise.resolve(local_msg_obj);
}
});
}
else {
local_msg_obj = {
schedule_id: schedule_id,
device_name: device_name,
cmd: cmd,
is_pending: true
};
return Promise.resolve(local_msg_obj);
}
}
function is_matchup_schedule_time(row) {
// get all field
var schedule_id = row.ScheduleId;
var device_name = row.ScheduleRemoteName;
var day_code = row.ScheduleDaycode;
var schedule_time = row.ScheduleTime;
var cmd = row.ScheduleCommandJSON;
// get hour and min
var schedule_time_arr = schedule_time.split(":");
var schedule_hour = schedule_time_arr[0];
var schedule_min = schedule_time_arr[1];
// print
console.log();
console.log();
console.log("- schedule_id, device_name, day_code, schedule_time, schedule_hr, schedule_min, cmd -");
console.log(schedule_id);
console.log(device_name);
console.log(day_code);
console.log(schedule_time);
console.log(schedule_hour);
console.log(schedule_min);
console.log(cmd);
// curr date obj
var curr_date_obj = new Date();
var curr_date_code = add_zero(curr_date_obj.getUTCDay());
// print current
console.log();
console.log("- curr_date_code, curr_h, curr_min - ");
console.log(curr_date_code);
console.log(add_zero(curr_date_obj.getUTCHours()));
console.log(add_zero(curr_date_obj.getUTCMinutes()));
// var
var msg_obj = {};
// Match up day
if(day_code == curr_date_code) {
console.log();
console.log(".. match up day ..");
// Match up hour
var curr_hour = add_zero(curr_date_obj.getUTCHours());
if(schedule_hour == curr_hour) {
console.log();
console.log("~~ match up hour ~~");
// Match up min
var curr_min = add_zero(curr_date_obj.getUTCMinutes());
if(schedule_min == curr_min) {
console.log();
console.log("## match up d-h-m, run ##");
msg_obj = {
schedule_id: schedule_id,
device_name: device_name,
cmd: cmd,
is_run: true
};
return Promise.resolve(msg_obj);
}
}
}
else {
}
//
msg_obj = {
schedule_id: schedule_id,
device_name: device_name,
cmd: cmd,
is_run: false
};
return Promise.resolve(msg_obj);
}
// NOTE -------------
function process_schedule_rows(rows) {
return Promise.mapSeries(rows, function(row) {
return is_matchup_schedule_time(row)
.then(is_schedule_cmd_already_pending)
.then(insert_into_pending_cmd)
.catch(function(e){
throw e;
})
});
}
function do_schedule() {
console.log();
console.log("---- start do_schedule ----");
g_pool.query("select * from Schedule order by ScheduleId asc")
.then(process_schedule_rows)
.catch(function(e){
throw e;
});
}
// main func
function main() {
console.log("db host:");
console.log(config.db_host);
connect_db();
interval(function(){
do_schedule();
}, 5000, undefined);
// Clean up
ON_DEATH(function(signal, err) {
console.log();
console.log("-- script interupted --");
console.log("close db");
// close db
close_db();
process.exit();
});
}
// run main func
main();
update 1
I have updated the code to recursive and the insertion still happen twice.
function do_schedule() {
console.log();
console.log("---- start do_schedule ----");
g_pool.query("select * from Schedule order by ScheduleId asc")
.then(process_schedule_rows)
.delay(2000)
.then(do_schedule)
.catch(function(e){
throw e;
});
}
update 2
Currently, the script is checking whether a command is already inserted into the database, if it is, it moves to the next task. If it isn't, it insert the command into pending table.
The script is checking every 2s, it may be too fast for mysql checking whether there is already command.
Well, I set it to 2 min, the same issue still occur. i.g insert twice.
function do_schedule() {
console.log();
console.log("---- start do_schedule ----");
g_pool.query("select * from Schedule order by ScheduleId asc")
.then(process_schedule_rows)
.delay(120000) <------------
.then(do_schedule)
.catch(function(e){
throw e;
});
}
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;
}