Monotouch EKEvent Notes not being saved - c#

What am I doing wrong here? currentEvent.Title prints correctly. currentEvent.Notes is always blank..
public void CalendarEvents()
{
EKEventStore store = new EKEventStore();
EKCalendar calendar = store.DefaultCalendarForNewEvents;
// Query the event
if (calendar != null)
{
// Add a new event
EKEvent newEvent = EKEvent.FromStore(store);
newEvent.Title = "Lunch at McDonalds";
newEvent.Calendar = calendar;
newEvent.StartDate = DateTime.Now.Date;
newEvent.EndDate = DateTime.Now.Date.AddDays(4);
newEvent.Availability = EKEventAvailability.Free;
newEvent.Notes = "hello";
store.SaveEvent(newEvent, EKSpan.ThisEvent, new IntPtr());
// Searches for every event in the next year
NSPredicate predicate = store.PredicateForEvents(NSDate.Now,DateTime.Now.AddDays(360),new EKCalendar[] {calendar});
store.EnumerateEvents(predicate, delegate(EKEvent currentEvent, ref bool stop)
{
// Perform your check for an event type
Console.WriteLine(currentEvent.Title);
Console.WriteLine(currentEvent.Notes);
});
}
}

The API likely has changed because the above won't compile 'as-is'. So I updated your:
store.SaveEvent(newEvent, EKSpan.ThisEvent, new IntPtr());
to
NSError error;
store.SaveEvent(newEvent, EKSpan.ThisEvent, out error);
Otherwise, using the latest MonoTouch, I get both strings displayed in the "Application Output" (app running on device).
Lunch at McDonalds
hello
Maybe that was fixed when the API was modified ?

Related

Unable to get a string out of a method

I am really new to coding, never studied it or something similar, just learning it myself, never done it before, but I am trying to create my first real application right new.
However, I have some problems for 2 days which I just can't figure out, so I hope you can help me out.
Alright, so before the youtubedlCurrentWorker_Process() is created, I did define 'public string CurrentYouTubeDLVersion'.
How ever, when a button in my application executes the youtubedlCompareVersion_Process(), the CurrentYouTubeDLVersion string is empty, when it comes at the compare point.
Below is just a little part of my code.
Why is the string CurrentYouTubeDLVersion empty in the CompareVersion while the GetCurrentVersion ran before it?
Even if I double click "CurrentYouTubeDLVersion" in Visual Studio, it won't show a link to the one in the GetCurrentVersion_Process.
namespace MediaDownloader
{
public partial class updates : UserControl
{
public string LatestYoutubeDLVersion;
public string CurrentYouTubeDLVersion;
public void youtubedlGetCurrentVersion_Process()
{
if (File.Exists(YouTubeDLPath))
{
//Here I get the current version of youtube-dl.exe, to get the version number, we have to run youtube-dl.exe --version
Process youtubedl = new Process();
youtubedl.StartInfo.CreateNoWindow = true;
youtubedl.StartInfo.UseShellExecute = false;
youtubedl.StartInfo.RedirectStandardOutput = true;
youtubedl.StartInfo.RedirectStandardError = true;
youtubedl.StartInfo.FileName = YouTubeDLPath;
youtubedl.StartInfo.Arguments = " --version";
youtubedl.Start();
string CurrentYouTubeDLVersion = youtubedl.StandardOutput.ReadToEnd();
this.Dispatcher.Invoke((Action)(() =>
{
CurrentYouTubeDLVersionText.Text = "Current youtube-dl.exe version: " + CurrentYouTubeDLVersion;
YouTubeDLVersionStatusText.Text = null;
UpdateYouTubeDL.IsEnabled = false;
}));
}
public void youtubedlCompareVersion_Process()
{
youtubedlGetCurrentVersion_Process();
string LatestYoutubeDLVersion = WebClient.DownloadString("https://yt-dl.org/latest/version");
MessageBox.Show("Latest:" + LatestYoutubeDLVersion + "Current " + CurrentYouTubeDLVersion);
int YouTubeDLUptodate = CurrentYouTubeDLVersion.CompareTo(LatestYoutubeDLVersion);
if (YouTubeDLUptodate < 1)
{
YouTubeDLVersionStatusText.Text = "Your youtube-dl.exe is out of date, please click the button below to update.";
UpdateYouTubeDL.IsEnabled = true;
}
else
{
YouTubeDLVersionStatusText.Text = "youtube-dl.exe is up to date!";
UpdateYouTubeDL.IsEnabled = false;
}
}
}
Inside the youtubedlGetCurrentVersion_Process method, you're creating a new CurrentYouTubeDLVersion string, and it's completely separate from the public CurrentYouTubeDLVersion you added to the top of the class.
string CurrentYouTubeDLVersion = youtubedl.StandardOutput.ReadToEnd();
Assign to the class-level variable you made, instead of creating a new string:
CurrentYouTubeDLVersion = youtubedl.StandardOutput.ReadToEnd();
Then the value will be available to you in youtubedlCompareVersion_Process.
Take out the 'string' in front of CurrentYouTubeDLVersion and it should work
public youtubedlGetCurrentVersion_Process()
{
/* removed code to make easier to read */
//string CurrentYouTubeDLVersion = youtubedl.StandardOutput.ReadToEnd();
CurrentYouTubeDLVersion = youtubedl.StandardOutput.ReadToEnd();
/* removed code to make easier to read */
}

VS Extension - disabling errors from embedded code editor

I want to show c# source code with syntax highlighting and theme coloring inside a wpf control. This is for preview only and I don't need any editing capabilities.
I found some code samples on how to embed a code editor which receives a file path to load.
I loaded it with a temp file I created - and it works, well almost...
The problem is that the loaded code have parsing errors which shows up in the error list.
Is there a way to set those errors to not appear in the error list?
Here is the code:
IVsInvisibleEditorManager invisibleEditorManager = (IVsInvisibleEditorManager)ServiceProvider.GlobalProvider.GetService(typeof(SVsInvisibleEditorManager));
ErrorHandler.ThrowOnFailure(invisibleEditorManager.RegisterInvisibleEditor(csTempFilePath, pProject: null,dwFlags: (uint)_EDITORREGFLAGS.RIEF_ENABLECACHING,
pFactory: null, ppEditor: out this.invisibleEditor));
//The doc data is the IVsTextLines that represents the in-memory version of the file we opened in our invisibe editor, we need
//to extract that so that we can create our real (visible) editor.
IntPtr docDataPointer = IntPtr.Zero;
Guid guidIVSTextLines = typeof(IVsTextLines).GUID;
ErrorHandler.ThrowOnFailure(this.invisibleEditor.GetDocData(fEnsureWritable: 1, riid: ref guidIVSTextLines, ppDocData: out docDataPointer));
try
{
IVsTextLines docData = (IVsTextLines)Marshal.GetObjectForIUnknown(docDataPointer);
//Get the component model so we can request the editor adapter factory which we can use to spin up an editor instance.
IComponentModel componentModel = (IComponentModel)ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel));
IVsEditorAdaptersFactoryService editorAdapterFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
//Create a code window adapter.
this.codeWindow = editorAdapterFactoryService.CreateVsCodeWindowAdapter(OleServiceProvider);
IVsCodeWindowEx codeWindowEx = (IVsCodeWindowEx)this.codeWindow;
INITVIEW[] initView = new INITVIEW[1];
codeWindowEx.Initialize((uint)_codewindowbehaviorflags.CWB_DISABLESPLITTER,
VSUSERCONTEXTATTRIBUTEUSAGE.VSUC_Usage_Filter,
szNameAuxUserContext: "",
szValueAuxUserContext: "",
InitViewFlags: 0,
pInitView: initView);
ErrorHandler.ThrowOnFailure(this.codeWindow.SetBuffer((IVsTextLines)docData));
//Get our text view for our editor which we will use to get the WPF control that hosts said editor.
ErrorHandler.ThrowOnFailure(this.codeWindow.GetPrimaryView(out this.textView));
//Get our WPF host from our text view (from our code window).
IWpfTextViewHost textViewHost = editorAdapterFactoryService.GetWpfTextViewHost(this.textView);
textViewHost.TextView.Options.SetOptionValue(DefaultTextViewHostOptions.ChangeTrackingId, false);
textViewHost.TextView.Options.SetOptionValue(DefaultTextViewOptions.ViewProhibitUserInputId, true);
var dte = ContainerFactory.GetContainer().Resolve<DTE2>();
var projectItem = dte.Solution.FindProjectItem(csTempFilePath);
projectItem.Properties.Item("BuildAction").Value = prjBuildAction.prjBuildActionNone;
return textViewHost.HostControl;
}
finally
{
if (docDataPointer != IntPtr.Zero)
{
//Release the doc data from the invisible editor since it gave us a ref-counted copy.
Marshal.Release(docDataPointer);
}
}
I've tried to remove the errors from the error list manually. But it didn't work - I think it's because i can only remove errors that I added previously. Here is the code I tried using to remove the errors:
public void RemoveTempFileErrors()
{
var provider = new ErrorListProvider(ServiceProvider.GlobalProvider)
{
ProviderName = "MyProvider",
ProviderGuid = new Guid("41C0915D-A0F4-42B2-985F-D1CC5F65BFFC") // my provider guid
};
var vsTaskList1 = (IVsTaskList) Package.GetGlobalService(typeof (IVsTaskList));
uint providerCookie;
vsTaskList1.RegisterTaskProvider(provider, out providerCookie);
vsTaskList1.RefreshTasks(providerCookie);
var vsTaskList2 = (IVsTaskList2)Package.GetGlobalService(typeof(IVsTaskList));
provider.SuspendRefresh();
IVsEnumTaskItems enumerator;
vsTaskList1.EnumTaskItems(out enumerator);
IVsTaskItem[] arr = new IVsTaskItem[1];
while (enumerator.Next(1, arr, null) == 0)
{
string doc;
arr[0].Document(out doc);
if (doc == csTempFilePath)
{
vsTaskList2.RemoveTasks(providerCookie, 1, arr);
}
}
provider.ResumeRefresh();
provider.Refresh();
vsTaskList1.UnregisterTaskProvider(providerCookie);
}
I solved it partially -
The parsing errors were caused because the code was a method without a class. So i wrapped the method in a class and used an elision buffer to show only the method without the wrapper class
The elision buffer code goes like this:
var subsetSnapshot = new SnapshotSpan(textSnapshot.Lines.First().EndIncludingLineBreak, textSnapshot.Lines.Last().Start);
var projectionBufferFactory = componentModel.GetService<IProjectionBufferFactoryService>();
var projBuffer = projectionBufferFactory.CreateElisionBuffer(null,
new NormalizedSnapshotSpanCollection(subsetSnapshot), ElisionBufferOptions.None);
IVsTextBuffer bufferAdapter = editorAdapterFactoryService.CreateVsTextBufferAdapterForSecondaryBuffer(OleServiceProvider, projBuffer);
projTextView = editorAdapterFactoryService.CreateVsTextViewAdapter(OleServiceProvider);
projTextView.Initialize((IVsTextLines)bufferAdapter, IntPtr.Zero,
(uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
new[] { new INITVIEW { fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 0 } };
IWpfTextViewHost projTextViewHost = editorAdapterFactoryService.GetWpfTextViewHost(projTextView);

Error on loading user control

i want to load my own designed User Control to the form but when i drag and place the user Control it produces the Error. Please Kindly refer my Screen Shot and help me to solve this issue.
The error where in code is i mentioned as line no:
private void populateTransfers(bool all)
{
AccountTransfer[] accounts;
//List<ReferenceData._account> headers = ReferenceData.getIndentHeader_account();
if (all)
accounts = accountClient.getAllPendingTransfers();
else
accounts = accountClient.getPendingTransfers(Program.loggedInUser.account.id);//line no:47
if (accounts != null)
{
var query = from a in accounts
select new
{
Id = a.id,
Name=a.name,
Status = a.status,
Date = a.ludt.ToShortDateString()
};
this.gridPendingTransfers.DataSource = query.ToList();
this.gridPendingTransfers.RefreshDataSource();
}
else
{
CexAppUtil.ShowEmptyGrid("No pending transfers", this.gridPendingTransfers);
}
private void initializeData()
{
if (Program.loggedInUser != null && Program.loggedInUser.isAdmin())
{
pendingTransferOptionsPanel.Visible = true;
showAllPendingTransfers.Visible = true;
if (showAllPendingTransfers.Checked) populateTransfers(true);
else populateTransfers(false);
}
else
{
pendingTransferOptionsPanel.Visible = false;
showAllPendingTransfers.Visible = false;
populateTransfers(false);//line no:167
}
}
Please help me to solve this problem.
Thanks-in Advance.
You can debug and find the error in your custom control by starting a new instance of visual studio and attach the debugger to the process of the first instance.
After that you can add your new control and see which object is null.
Are doing some work in constructor? Delete all code from constructor instead of InitilizeComponents(). Then make a new Initilize Method where you copy the code from constructor. This method you call in form.load or sth. Try it out ;) – # Sebi
Thank to every-one.

Out of Memory at line XXXX

can anyone help me how to resolve the out of memory error on my asp page? im using linq to sql.. after adding data several data.. like more than 10 rows. in the grid. an out of memory error occurs.. attached herewith is my add function..
public ServiceDetail checkservicedetailid()
{
string ServiceName = ViewState["Tab"].ToString();
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(a => a.ServiceName == ServiceName && a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID).SingleOrDefault();
return checkservicedetailid;
}
public IEnumerable<ServiceDetail> get(Expression<Func<ServiceDetail, Boolean>> express)
{
return ServiceDetailsDB.ServiceDetails.Where(express);
}
protected void btnSaveEmptyOC_Click(object sender, EventArgs e)
{
try
{
if (checkservicedetailid() != null)
{
CashExpense tblCashExpenses = new CashExpense();
Guid CashExpensesID = Guid.NewGuid();
tblCashExpenses.CashExpensesID = CashExpensesID;
tblCashExpenses.ServiceDetailsID = checkservicedetailid().ServiceDetailsID;
tblCashExpenses.Description = txtDescriptionEmptyOC.Text;
tblCashExpenses.Quantity = Decimal.Parse(txtQTYEmptyOC.Text);
tblCashExpenses.UnitCost = Decimal.Parse(txtUnitCostEmptyOC.Text);
tblCashExpenses.CreatedBy = User.Identity.Name;
tblCashExpenses.DateCreated = DateTime.Now;
tblCashExpenses.CashExpensesTypeID = "OTHER";
CashExpenses_worker.insert(tblCashExpenses);
CashExpenses_worker.submit();
//Clear items after saving
txtDescriptionEmptyOC.Text = "";
txtQTYEmptyOC.Text = "";
txtUnitCostEmptyOC.Text = "";
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOC2, "SaveEmptyOC", this.Page);
MyAuditProvider.Insert(this.GetType().ToString(), ViewState["MarginAnalysisID"].ToString(), MessageCenter.Mode.ADD, MessageCenter.CashExpenseMaintenace.InsertOC2, Page.Request, User);
divOtherCost.Visible = false;
grd_othercost.Visible = true;
btnaddothercost.Visible = true;
}
else
{
//Displays a Message on the Validation Summary (Service Id does not exist)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.SaveServiceDetailOC, "SaveEmptyOC", this.Page);
}
}
catch
{
//Displays a Message on the Validation Summary (Error on Saving)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOCError, "SaveEmptyOC", this.Page);
}
finally
{
//Rebinds the Grid
populategrd_othercost();
}
}
I'm guessing from your code here:
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID
).SingleOrDefault();
that .get() is taking a Func<SomeType, bool>, and you are doing something like:
var row = dbCtx.SomeTable.Where(predicate);
(please correct me here if I'm incorrect)
This, however, is using LINQ-to-Objects, meaning: it is loading every row from the table to the client and testing locally. That'll hurt memory, especially if a different db-context is created for each row. Additionally, the checkmarginanalysisid() call is being executed per row, when presumably it doesn't change between rows.
You should be testing this with an Expression<Func<SomeType, bool>> which would be translated to TSQL and executed at the server. You may also need to remove untranslatable methods, i.e.
var marginAnalysisId = checkmarginanalysisid().MarginAnalysisID;
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == marginAnalysisId
).SingleOrDefault();
where that is get(Expression<Func<SomeType, bool>>).
I tried all of the solution given to me both by my peers as well as the solution provided here, from GC.Collect, to disposing linq datacontext after use etc. however the error keeps on occurring, i then tried to remove the update panel, Ive read a site that showed how ridiculous update panel when it comes to handling data esp when a function is done repeatedly. And poof! the memory problem is gone!

How to delete all event entries from a specific calendar from Google calendar API .NET

I am trying editing a tool to allow a user to select from a list of their calendars and then clear all event entries / add new ones based on Microsoft project tasks.
Heres the original tool: http://daball.github.com/Microsoft-Project-to-Google-Calendar/
I am completely unexperienced with Google APIs / the calendar API, and am having some trouble. The program I'm editing keeps track of which CalendarEntry the user has selected from a list of their calendars. What I am currently trying to do is create a EventFeed which gives me the EventEntries of that selected calendar, so I can then delete all of them. The purpose of this is to allow someone to use this tool to also update the calendar from the project file whenever changes are made. Here's my function attempting the delete.
private void clearPreviousCalendarEntries(CalendarEntry calendarEntry)
{
EventQuery query = new EventQuery();
query.Uri = new Uri(calendarEntry.Links[0].AbsoluteUri);
EventFeed feed = (EventFeed)calendarService.Query(query);
AtomFeed batchFeed = new AtomFeed(feed);
foreach (EventEntry entry in feed.Entries)
{
entry.Id = new AtomId(entry.EditUri.ToString());
entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
batchFeed.Entries.Add(entry);
}
EventFeed batchResultFeed = (EventFeed)calendarService.Batch(batchFeed, new Uri(feed.Batch));
foreach (EventEntry entry in batchResultFeed.Entries)
{
if (entry.BatchData.Status.Code != 200 && entry.BatchData.Status.Code != 201)
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Problem deleteing " + entry.Title.Text + " error code: " + entry.BatchData.Status.Code);
else
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Deleted " + entry.Title.Text);
}
}
My feed doesn't return the results I was hoping for, but to be honest I'm not sure how to request the events correctly.
query.Uri = new Uri(calendarEntry.Links[0].AbsoluteUri); is something I grabbed from the portion of the program which is adding event to a specific calendar
AtomEntry insertedEntry = calendarService.Insert(new Uri(calendarEntry.Links[0].AbsoluteUri), eventEntry);
These posts are definitely related to what I'm looking for but I haven't arrived at a solution
google-calendar-get-events-from-a-specific-calendar
how can i retrieve a event exclusive from a calendar that i created (not default one)?
Try something like this:
CalendarService myService = new CalendarService("your calendar name");
myService.setUserCredentials(username, password);
CalendarEntry calendar;
try
{
calendar = (CalendarEntry)myService.Get(http://www.google.com/calendar/feeds/default/owncalendars/full/45kk8jl9nodfri1qgepsb65fnc%40group.calendar.google.com);
foreach (AtomEntry item in calendar.Feed.Entries)
{
item.Delete();
}
}
catch (GDataRequestException)
{
}
You can find "Calendar ID" (something like this: 45kk8jl9nodfri1qgepsb65fnc%40group.calendar.google.com) from Calendar Details page inside Google Calendar.
this is a related post:
google calendar api asp.net c# delete event
this is a useful doc:
http://code.google.com/intl/it-IT/apis/calendar/data/2.0/developers_guide_dotnet.html
A way I eventually arrived at was gathering the calendarID from the URI of the calendar, and then creating a new EventQuery using that id. Here's the new version of the code above
private void clearPreviousCalendarEntries(CalendarEntry calendarEntry)
{
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Clearing previous calender entries");
String calendarURI = calendarEntry.Id.Uri.ToString();
//The last part of the calendarURI contains the calendarID we're looking for
String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/")+1);
EventQuery query = new EventQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/" + calendarID + "/private/full");
EventFeed eventEntries = calendarService.Query(query);
AtomFeed batchFeed = new AtomFeed(eventEntries);
foreach (AtomEntry entry in eventEntries.Entries)
{
entry.Id = new AtomId(entry.EditUri.ToString());
entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
batchFeed.Entries.Add(entry);
}
EventFeed batchResultFeed = (EventFeed)calendarService.Batch(batchFeed, new Uri(eventEntries.Batch));
//check the return values of the batch operations to make sure they all worked.
//the insert operation should return a 201 and the rest should return 200
bool success = true;
foreach (EventEntry entry in batchResultFeed.Entries)
{
if (entry.BatchData.Status.Code != 200 && entry.BatchData.Status.Code != 201)
{
success = false;
listBoxResults.SelectedIndex = listBoxResults.Items.Add("The batch operation for " +
entry.Title.Text + " failed.");
}
}
if (success)
{
listBoxResults.SelectedIndex = listBoxResults.Items.Add("Calendar event clearing successful!");
}
}
I'm not particular happy with this, it seems odd to use string manipulation to gather the info and chop together my own query. But it works and I have been struggling to find a way to get this done.

Categories

Resources