LayoutSerializationCallback not be called - c#

I'm using AvalonDock and I would serialize and deserialize my layout. But the callback (where I use the ContentId for create an instance of correct object) is not always called. For this reason the loaded not work correctly. I have tried to add one "try-catch", but not thrown exception.
This is my code:
` var layoutSerializer = new XmlLayoutSerializer(manager);
layoutSerializer.LayoutSerializationCallback += (s, e) =>
{
MyClass item;
if (items.TryGetValue(e.Model.ContentId, out item))
{
e.Content = item;
var tool = item as IMyClassToolApp;
var anchorable = e.Model as LayoutAnchorable;
var document = item as IMyClassDocumentApp;
var layoutDocument = e.Model as LayoutDocument;
if (tool != null && anchorable != null)
{
addToolCallback(tool);
tool.IsVisible = anchorable.IsVisible;
tool.IsSelected = e.Model.IsSelected;
return;
}
if (document != null && layoutDocument != null)
{
addDocumentCallback(document);
// Nasty hack to get around issue that occurs if documents are loaded from state,
// and more documents are opened programmatically.
layoutDocument.GetType().GetProperty("IsLastFocusedDocument").SetValue(layoutDocument, false, null);
document.IsVisible = true;
document.IsSelected = layoutDocument.IsSelected;
return;
}
}
e.Cancel = true;
};
try
{
layoutSerializer.Deserialize(stream);
}
catch
{
return false;
}`
Thank you for your help!

Are you sure your stream is O.K? If for example configuration file does not exist LayoutSerializationCallback method will not be called.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "MainWindow_Loaded");
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
#"Jofta\Analyzer\configs\AvalonDock.config");
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
XmlLayoutSerializer serializer = new XmlLayoutSerializer(this.dockingManager);
serializer.LayoutSerializationCallback += this.Serializer_LayoutSerializationCallback;
serializer.Deserialize(filePath);
}
MainWindow.logger.Debug("Exiting: {0}", "MainWindow_Loaded");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "MainWindow_Loaded");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}
private void Serializer_LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "serializer_LayoutSerializationCallback");
if (e.Model.ContentId == ObjectExplorerViewModel.AnchorableContentId)
{
e.Content = Workspace.Instance.ObjectExplorer;
return;
}
// ...
// ...
MainWindow.logger.Debug("Exiting: {0}", "serializer_LayoutSerializationCallback");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "serializer_LayoutSerializationCallback");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}

Related

DisplayActionSheet keeps appearing even though i'm choosing an item xamarin.forms UWP

i have a DisplayActionSheet that appears on Entry Focus. the thing is that after it appears and i choose an item, the DisplayActionSheet doesn't disappear it keeps popping up and i choose again and again and it keeps popping up. i don't understand why because it works well on both android and ios, but on UWP, it seems to be different. here is the code:
async private void edlevel_Focused(object sender, FocusEventArgs e)
{
urlClass urldata = new urlClass();
string uri = urldata.url + "/GetAllEdlevels/4";
try
{
HttpResponseMessage responsepost = await client.GetAsync(uri);
if (responsepost.IsSuccessStatusCode == true)
{
string outcome = await responsepost.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<edlevels>>(outcome);
string[] edlevels_lst = new string[result.Count];
for (int i = 0; i < result.Count; i++)
{
edlevels_lst[i] = result[i].edlevel;
}
string action = await DisplayActionSheet("Education Levels", "OK", null, edlevels_lst);
if (action == "OK")
{
edlevel.Text = "";
}
else
{
edlevel.Text = action;
}
if(!string.IsNullOrEmpty(edlevel.Text))
{
if (edlevel.Text.Trim() == "Kgs" || edlevel.Text.Trim() == "Nursery")
{
discount.IsToggled = false;
discount.IsEnabled = false;
}
else
{
discount.IsEnabled = true;
}
}
}
else
{
await DisplayAlert("Operation Failed", "Response Failed!", "Cancel");
}
}
catch (System.Net.WebException exp)
{
bool ans = await DisplayAlert("Connection Failed", "Please Check Your Internet Connection!", "Retry", "Cancel");
if (ans == true)
edlevel_Focused(sender, e);
}
catch (Exception exp)
{
bool ans = await DisplayAlert("Connection Failed", "Lost Connection!", "Retry", "Cancel");
if (ans == true)
edlevel_Focused(sender, e);
}
}
what am i doing wrong?
Actually, you can use the label with adding a TapGesture. When you click the label twice you will triger the Tapped method.
<StackLayout>
<Label Text="tap GestureRecognizers">
<Label.GestureRecognizers>
<TapGestureRecognizer
Tapped="OnTapGestureRecognizerTapped"
NumberOfTapsRequired="2" />
</Label.GestureRecognizers>
</Label>
</StackLayout>
In the cs file:
void OnTapGestureRecognizerTapped(object sender, EventArgs args)
{
urlClass urldata = new urlClass();
string uri = urldata.url + "/GetAllEdlevels/4";
try
{
HttpResponseMessage responsepost = await client.GetAsync(uri);
if (responsepost.IsSuccessStatusCode == true)
{
string outcome = await responsepost.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<edlevels>>(outcome);
string[] edlevels_lst = new string[result.Count];
for (int i = 0; i < result.Count; i++)
{
edlevels_lst[i] = result[i].edlevel;
}
string action = await DisplayActionSheet("Education Levels", "OK", null, edlevels_lst);
if (action == "OK")
{
edlevel.Text = "";
}
else
{
edlevel.Text = action;
}
if(!string.IsNullOrEmpty(edlevel.Text))
{
if (edlevel.Text.Trim() == "Kgs" || edlevel.Text.Trim() == "Nursery")
{
discount.IsToggled = false;
discount.IsEnabled = false;
}
else
{
discount.IsEnabled = true;
}
}
}
else
{
await DisplayAlert("Operation Failed", "Response Failed!", "Cancel");
}
}
catch (System.Net.WebException exp)
{
bool ans = await DisplayAlert("Connection Failed", "Please Check Your Internet Connection!", "Retry", "Cancel");
if (ans == true)
edlevel_Focused(sender, e);
}
catch (Exception exp)
{
bool ans = await DisplayAlert("Connection Failed", "Lost Connection!", "Retry", "Cancel");
if (ans == true)
edlevel_Focused(sender, e);
}
}

StackOverFlowException raised when this line such as "logDirectory = new DirectoryInfo(m_logFileDirectory);" was excuting

StackOverFlowExceprion raised, when logDirectory = new DirectoryInfo(m_logFileDirectory); line was executing. How can I solve the problem? Please help me.
This procedure writeLogToFile write a logMessge to File to logDirectory.
It is part of Log write program.
private void writeLogToFile(string logMessge)
{
DirectoryInfo logDirectory = null;
try
{
Monitor.Enter(m_lock);
logDirectory = new DirectoryInfo(m_logFileDirectory);
if (!logDirectory.Exists)
{
logDirectory.Create();
}
if (m_streamWriter == null) newLogFile();
if (m_logFileAutoSeperate && (m_streamWriter.BaseStream.Length > m_logFileSize * 1024))
{
newLogFile();
m_streamWriter.WriteLine(logMessge);
}
else
{
m_streamWriter.WriteLine(logMessge);
}
// stream writer uses internal buffer.
// if directWriting option is true, the file will be write(flush) once.
if (directWriting) m_streamWriter.Flush();
}
catch (StackOverflowException sofex)
{
AppExceptionHandler.writeException(sofex);
}
catch (AppException aex)
{
AppExceptionHandler.writeException(aex);
}
catch (Exception ex)
{
AppExceptionHandler.writeException(ex);
}
finally
{
Monitor.Exit(m_lock);
}
}
From the comments, this is what newLogFile looks like:
private void newLogFile()
{
try
{
Monitor.Enter(m_lock);
if (m_streamWriter != null)
{
endLogging();
m_streamWriter.Flush();
m_streamWriter.Close();
}
m_logFileNameSuffix = getLogFileNewSuffix();
m_streamWriter = File.AppendText(getLogFileName());
startLogging();
}
}

Selenium, When I use tabs, chrome keep maxmize even if you minimize it

I make a program and it keeps open and close tabs
SO when a new tab opened or closed, chrome show up again even if it minimize
I need to keep it minimized
This is my code:
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());
try
{
try
{
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10);
driver.Navigate().GoToUrl(url);
}
catch (Exception r)
{
((IJavaScriptExecutor)driver).ExecuteScript("return window.stop");
}
var streamdiv = obj.FindElement(driver, "content-audio_html5_api", Assistances.FindElementBy.ID, true);
if (streamdiv != null)
{
var streamurl = streamdiv.FindElement(By.XPath(".//source")).GetAttribute("src");
if ((streamurl != "" || streamurl != null) && streamurl != url.Remove(url.IndexOf('s'), 1))
{
row["streamURL"] = streamurl;
}
}
}
catch (Exception er)
{
row["streamURL"] = "";
}
try
{
string logo_url = driver.FindElement(By.XPath("//div[#class='song-image']//a//img")).GetAttribute("src");
row["logo_URL"] = logo_url;
obj.DownloadImage(logo_url);
}
catch (Exception e)
{
}
driver.Close();
driver.SwitchTo().Window(driver.WindowHandles.First());

Cannot open file immediately after downloading from OneDrive

after downloading a JPG file from OneDrive successfully under Windows 8.1, I am not able to open it and use the stream as image source immediately. Instead, my app must run in a waiting loop to retry the opening until the exception "Error HRESULT E_FAIL has been returned from a call to a COM component" does not occur anymore. Or the app must inform the user to retry the action. After about one second or so, the file can be opened and the stream can be used as image source. This problem occurs if the JPG file was initially not available offline and my app downloads it. I want to know if anybody has a better solution for that problem. Here is some of my code:
private async void LoadFileButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpe");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".gif");
Stream stream = null;
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
var basicProperties = await file.GetBasicPropertiesAsync();
var props = await basicProperties.RetrievePropertiesAsync(
new string[] { "System.OfflineAvailability", "System.StorageProviderFileRemoteUri" });
if (props.ContainsKey("System.OfflineAvailability"))
{
var offline = (uint)props["System.OfflineAvailability"];
if (offline == 0)
{
if (file.Provider.DisplayName == "OneDrive")
{
if (props.ContainsKey("System.StorageProviderFileRemoteUri"))
{
var uri = (string)props["System.StorageProviderFileRemoteUri"];
var res = await GameStorage.DownloadOneDriveFile(file, uri, _downloadProgressBar);
if (res is string)
{
await App.InformUserAsync(res.ToString(), _title.Text);
return;
}
stream = (Stream)res;
}
}
else
{
await App.InformUserAsync(String.Format(
App.GetString("MakeFileOfflinePrompt", "GameManagement"),
file.Path), _title.Text);
return;
}
}
}
if (stream == null)
{
stream = await file.OpenStreamForReadAsync();
}
await _photoClipper.SetDisplayImageStreamAsync(stream);
_clipPhotoButton.IsEnabled = true;
}
}
internal static async Task<object> DownloadOneDriveFile(StorageFile file, string url,
ProgressBar progressBar = null)
{
if (progressBar != null)
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 1;
}
if (__liveClient == null)
{
var msg = await ConnectLive();
if (!String.IsNullOrEmpty(msg))
{
return msg;
}
}
var uri = new Uri(WebUtility.UrlDecode(url));
var pathElements = uri.LocalPath.Split(new char[] { '/' },
StringSplitOptions.RemoveEmptyEntries);
var parentId = "folder." + pathElements[0];
IDictionary<string, object> props = null;
for (var i = 1; i < pathElements.Length; i++)
{
props = await FindOneDrivePathElement(parentId, pathElements[i]);
if (props == null)
{
return String.Format(App.GetString("OneDrivePathElementNotFound",
"GameManagement"), pathElements[i], uri);
}
parentId = props["id"].ToString();
if (progressBar != null) progressBar.Value += 1;
}
try
{
var operation = await __liveClient.CreateBackgroundDownloadAsync(parentId +
"/content", file);
LiveDownloadOperationResult result = null;
if (progressBar != null)
{
progressBar.Value = 10;
var progressHandler = new Progress<LiveOperationProgress>(
(progress) => { progressBar.Value = progress.ProgressPercentage; });
var cts = new CancellationTokenSource();
result = await operation.StartAsync(cts.Token, progressHandler);
}
else
{
result = await operation.StartAsync();
}
var trialsCount = 0;
string openErr = null;
Stream stream = null;
while (trialsCount < 5)
{
try
{
stream = await result.File.OpenStreamForReadAsync();
break;
}
catch (Exception ex)
{
openErr = ex.Message;
}
trialsCount += 1;
await App.SuspendAsync(1000);
}
if (stream != null)
{
return stream;
}
return String.Format(App.GetString("OneDriveCannotOpenDownloadedFile",
"GameManagement"), file.Path, openErr);
}
catch (Exception ex)
{
return String.Format(App.GetString("OneDriveCannotDownloadFile",
"GameManagement"), file.Path, ex.Message);
}
finally
{
if (progressBar != null)
{
progressBar.Visibility = Visibility.Collapsed;
}
}
}
private static async Task<IDictionary<string, object>> FindOneDrivePathElement(
string parentId, string childName)
{
var res = await __liveClient.GetAsync(parentId + "/files");
if (res.Result.ContainsKey("data"))
{
var items = (IList<object>)res.Result["data"];
foreach (var item in items)
{
var props = (IDictionary<string, object>)item;
if (props.ContainsKey("name"))
{
var name = props["name"].ToString();
if (name == childName)
{
if (props.ContainsKey("id"))
{
return props;
}
}
}
}
}
return null;
}
I have tried again to open a "available online-only" file and as by a miracle the exception "Error HRESULT E_FAIL" did not occur any more. For what ever reason, I don't know. But, I really do not need to handle that scenario by myself. Thanks.

MsftDiscFormat2Data Event Handler

I have successfully integrated IMAPI2 using Interop.cs into my application. I can burn CD/DVDs without any problem. However, the event handler for MsftDiscFormat2Data update does not work, so I can't get my progress bar moving.
Here is the code I found at codeproject website:
private void backgroundBurnWorker_DoWork(object sender, DoWorkEventArgs e)
{
MsftDiscRecorder2 discRecorder = null;
MsftDiscFormat2Data discFormatData = null;
try
{
//
// Create and initialize the IDiscRecorder2 object
//
discRecorder = new MsftDiscRecorder2();
var burnData = (BurnData)e.Argument;
discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId);
//
// Create and initialize the IDiscFormat2Data
//
discFormatData = new MsftDiscFormat2Data
{
Recorder = discRecorder,
ClientName = ClientName,
ForceMediaToBeClosed = _closeMedia
};
//
// Set the verification level
//
var burnVerification = (IBurnVerification)discFormatData;
burnVerification.BurnVerificationLevel = _verificationLevel;
//
// Check if media is blank, (for RW media)
//
object[] multisessionInterfaces = null;
if (!discFormatData.MediaHeuristicallyBlank)
{
multisessionInterfaces = discFormatData.MultisessionInterfaces;
}
//
// Create the file system
//
IStream fileSystem;
if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem))
{
e.Result = -1;
return;
}
//
// add the Update event handler
//
discFormatData.Update += discFormatData_Update;
//
// Write the data here
//
try
{
discFormatData.Write(fileSystem);
e.Result = 0;
}
catch (COMException ex)
{
e.Result = ex.ErrorCode;
MessageBox.Show(ex.Message, "IDiscFormat2Data.Write failed",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
if (fileSystem != null)
{
Marshal.FinalReleaseComObject(fileSystem);
}
}
//
// remove the Update event handler
//
discFormatData.Update -= discFormatData_Update;
if (_ejectMedia)
{
discRecorder.EjectMedia();
}
}
catch (COMException exception)
{
//
// If anything happens during the format, show the message
//
MessageBox.Show(exception.Message);
e.Result = exception.ErrorCode;
}
finally
{
if (discRecorder != null)
{
Marshal.ReleaseComObject(discRecorder);
}
if (discFormatData != null)
{
Marshal.ReleaseComObject(discFormatData);
}
}
}
void discFormatData_Update([In, MarshalAs(UnmanagedType.IDispatch)] object sender, [In, MarshalAs(UnmanagedType.IDispatch)] object progress)
{
//
// Check if we've cancelled
//
if (backgroundBurnWorker.CancellationPending)
{
var format2Data = (IDiscFormat2Data)sender;
format2Data.CancelWrite();
return;
}
var eventArgs = (IDiscFormat2DataEventArgs)progress;
_burnData.task = BURN_MEDIA_TASK.BURN_MEDIA_TASK_WRITING;
// IDiscFormat2DataEventArgs Interface
_burnData.elapsedTime = eventArgs.ElapsedTime;
_burnData.remainingTime = eventArgs.RemainingTime;
_burnData.totalTime = eventArgs.TotalTime;
// IWriteEngine2EventArgs Interface
_burnData.currentAction = eventArgs.CurrentAction;
_burnData.startLba = eventArgs.StartLba;
_burnData.sectorCount = eventArgs.SectorCount;
_burnData.lastReadLba = eventArgs.LastReadLba;
_burnData.lastWrittenLba = eventArgs.LastWrittenLba;
_burnData.totalSystemBuffer = eventArgs.TotalSystemBuffer;
_burnData.usedSystemBuffer = eventArgs.UsedSystemBuffer;
_burnData.freeSystemBuffer = eventArgs.FreeSystemBuffer;
//
// Report back to the UI
//
backgroundBurnWorker.ReportProgress(0, _burnData);
}
Unfortunately, the update handler gets never called. I looked up everywhere on internet but could not find a solution. I saw some people with same problem but no one was able to answer.
The original code from Eric, http://www.codeproject.com/KB/miscctrl/imapi2.aspx?msg=2695517,
does work for some reason.
Can someone please help me?
I know, it's too late, but I've got the same problem with update callbacks.
Open Project->Properties->Application->Assembly Information and tick "Make Assembly COM-visible".

Categories