Error on loading user control - c#

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.

Related

Observe and delete (screenshot), if a screenshot is taken while using my App in Iphone

I am trying to observe if a screenshot is taken while using my App on Iphone. If a screenshot is taken while using my App, I would like that screenshot to be deleted.
I also understand that during deletion, user needs to give permission for deletion.
I used an Observer method successfully to check if a screenshot is taken while using my app.
I am stuck at a point where I need to access that screenshot and delete it, of course with user permission.
```public override void OnActivated(UIApplication application)
{
try
{
// Start observing screenshot notification
if (_screenshotNotification == null)
{
_screenshotNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.UserDidTakeScreenshotNotification,
(NSNotification n) => {
Console.WriteLine("UserTookScreenshot");
var photosOptions = new PHFetchOptions();
photosOptions.SortDescriptors = new NSSortDescriptor[] { new
NSSortDescriptor("creationDate", false) };
photosOptions.FetchLimit = 1;
var photo = PHAsset.FetchAssets(photosOptions);
Console.WriteLine(photo);
var filePath = photo.Path;
System.IO.File.Delete(filePath);
n.Dispose();
}
);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}```
I know the above code does not work with deleting the current screenshot taken while using my App. It gives a general idea on what I want to achieve.
How can I delete the screenshot taken while using my APP from Iphone instantly (with user permission)? I would also like to know if it is possible.
Yes it is possible, you obviously have to properly manage the permissions for the image. In order to do this, first you have to add an observer to detect the screenshot as shown here
First: declare an NSObject variable on your AppDelegate. In the example below I added _screenshotNotification.
Second: On the AppDelegate’s OnActivated (app moving to active state), add code to start observing the UIApplication.UserDidTakeScreenshotNotification and then do something once the notification is posted.
Third: On the AppDelegate’s OnResignActivation (app moving to inactive state), add code to remove the observer.
Then you have to actually find the file & delete, so you in the page you are trying to do it, just add the Foundation & Photos using statements and then try this. (I converted the Swift from here but haven't tested it)
var fetchOptions = new PHFetchOptions();
fetchOptions.SortDescriptors[0] = new Foundation.NSSortDescriptor("creationDate", true);
var fetchResult = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);
if (fetchResult != null)
{
var lastAsset = (fetchResult.LastObject as PHAsset);
var arrayToDelete = new PHAsset[1] { lastAsset };
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { PHAssetChangeRequest.DeleteAssets(arrayToDelete); },
async (bool success, NSError errorMessage) => { }); //Handle Completion Here Appropriately
}
I don't think it is possible.
From iOS 11, when you take a screenshot, the snap minimizes itself in the bottom left corner of the screen. From here, save or delete the screenshot is decided by the user.(as the image below)
You can read more information form this article: how-take-screenshot-iphone-or-ipad-ios-11
Here comes the problem how do you know whether user has save the screenshot or not?
If the user saved, you can delete the screenShot form the photoLibrary.
While if the user dose not save the screenshot, what your deleted is not the screenshot.
Try this:
func didTakeScreenshot() {
self.perform(#selector(deleteAppScreenShot), with: nil, afterDelay: 1, inModes: [])
}
#objc func deleteAppScreenShot() {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors?[0] = Foundation.NSSortDescriptor(key: "creationDate", ascending: true)
let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
guard let lastAsset = fetchResult.lastObject else { return }
PHPhotoLibrary.shared().performChanges {
PHAssetChangeRequest.deleteAssets([lastAsset] as NSFastEnumeration)
} completionHandler: { (success, errorMessage) in
if !success, let errorMessage = errorMessage {
print(errorMessage.localizedDescription)
}
}
}

Properties.Settings.Default.variableName = textboxt.Text

private void Enable(TextBox temp, String system)
{
if (File.Exists(temp.Text))
{
Properties.Settings.Default.system = temp.Text;
}
else
do something here;
}
Basically I'm trying to take a text box with some file path, check if it exists, if exists set the value of the Properties.Settings.Default.system to temp.text.
However I don't know how to use a variable name to reference the existing settings property.
Fairly new to this so any help is appreciated.
Thanks!
Credit to Mike Debela for the answer.... But if ran into a situation where you don't know the system, this code will help prevent some errors.
private void Enable(TextBox Temp, string system)
{
// check that the property even exists
bool propertyExists = Properties.Settings.Default.Properties.Cast<SettingsProperty>().Any(p => p.Name == system);
if (propertyExists)
{
Properties.Settings.Default[system] = Temp.Text;
}
else
{
// create a new property
var p = new SettingsProperty(system);
p.PropertyType = typeof(string);
p.DefaultValue = Temp.Text;
Properties.Settings.Default.Properties.Add(p);
}
Properties.Settings.Default.Save();
}

Sys.WebForms.PageRequestManagerServerErrorException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker

Story:
I have a strange error when I try to save something I got this error message
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
I really don’t know what that is and why is it appear, it appears only when I try to save something my insert and update is working, only when I try to save something in db from my Telerik grid
if (this.annualVacationList != null)
{
List<AnnualVacation> vacationToSave = this.annualVacationList;
IEnumerable<AnnualVacation> existing = paramUser.AnnualVacations;
foreach (AnnualVacation toSave in vacationToSave)
{
AnnualVacation existingItem = existing.Where(x => x.AnnualVacationId == toSave.AnnualVacationId).SingleOrDefault();
if (existingItem == null)
{
ctx.AddToAnnualVacations(toSave);
}
else
{
existingItem.FromDate = toSave.FromDate;
existingItem.ToDate = toSave.ToDate;
existingItem.WorkingTime = toSave.WorkingTime;
existingItem.VacationDays = toSave.VacationDays;
}
}
}
ctx.SaveChanges();
}
After debugging I have seen that the code brake down in the Project.Name.Designer.cs
..... O.o
public void AddToAnnualVacations(AnnualVacation annualVacation)
{
base.AddObject("AnnualVacations", annualVacation);
}
Heey
I got it by myself somehow viewstates are not Detaching the context and that was the problem I have just created
var tmp = new AnnualVacation
{
FromDate = toSave.FromDate,
ToDate = toSave.ToDate,
WorkingTime = toSave.WorkingTime,
VacationDays = toSave.VacationDays,
UserId = toSave.UserId
};
in the same if query that is above (if(existing Item==null)) and it works
but still thanks for everyone that tried to help me ^^

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!

Monotouch EKEvent Notes not being saved

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 ?

Categories

Resources