Why should we actually use Dependency Properties? - silverlight-4.0

This code doesn't work :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightPlainWCF.CustomersServiceRef;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace SilverlightPlainWCF
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.DataContext = Customers;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
public static readonly string CustomersPropertyName = "Customers";
// public DependencyProperty CustomersProperty = DependencyProperty.Register(CustomersPropertyName,typeof(ObservableCollection<Customer>)
// ,typeof(MainPage),new PropertyMetadata(null));
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
//get { return GetValue(CustomersProperty) as ObservableCollection<Customer>; }
//set
//{
// SetValue(CustomersProperty, value);
//}
get
{
return customers;
}
set
{
customers = value;
}
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
CustomersServiceClient objCustomersServiceClient = new CustomersServiceClient();
objCustomersServiceClient.GetAllCustomersCompleted += (s, res) =>
{
if (res.Error == null)
{
Customers = res.Result;
}
else
{
MessageBox.Show(res.Error.Message);
}
};
objCustomersServiceClient.GetAllCustomersAsync();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
// Do not load your data at design time.
// if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
// {
// //Load your data here and assign the result to the CollectionViewSource.
// System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
// myCollectionViewSource.Source = your data
// }
// Do not load your data at design time.
// if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
// {
// //Load your data here and assign the result to the CollectionViewSource.
// System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
// myCollectionViewSource.Source = your data
// }
}
private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
{
}
private void customerDataGrid_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
{
var Customer = Customers[e.Row.GetIndex()];
Debug.WriteLine(Customer);
}
private void customerDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
Whereas if i just change the above property of Customers to this :-
public static readonly string CustomersPropertyName = "Customers";
public DependencyProperty CustomersProperty = DependencyProperty.Register(CustomersPropertyName,typeof(ObservableCollection<Customer>)
,typeof(MainPage),new PropertyMetadata(null));
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
get { return GetValue(CustomersProperty) as ObservableCollection<Customer>; }
set
{
SetValue(CustomersProperty, value);
}
}
it works. Why is it that only with DependencyProperty the grid gets populated? Please explain me in little detail. Also, do i have to compulsorily use ObservableCollection or even List is fine?

Short answer: Dependency properties are wrappers which know how to 'dispatch changes'.
See Dependency Properties Overview

Related

how to use auto migration in entity framework core 2

I use entity framework core 2. I saw posts in stack-overflow but I can't resolve my problem.
I want to use auto migration in my project without console command.
Try this code:
using (var serviceScope = _scopeFactory.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
context.Database.Migrate();
}
}
Complete code:
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.Services.InitializeDb();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{//Add Code }
}
}
public interface IDbInitializer
{
void Initialize();
}
public class DbInitializer : IDbInitializer
{
private readonly IServiceScopeFactory _scopeFactory;
public DbInitializer(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void Initialize()
{
using (var serviceScope = _scopeFactory.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
context.Database.Migrate();
}
}
}
}
public static class DbContextOptionsExtensions
{
public static void InitializeDb(this IServiceProvider serviceProvider)
{
var scopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var dbInitialize = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
dbInitialize.Initialize();
}
}
}

Revit Synchronization event

Starting with this...
https://github.com/jeremytammik/RevitLookup/blob/master/CS/EventTrack/Events/ApplicationEvents.cs
I'm trying to add an event listener for a synchronization event. the code below throws an error stating that the m_app is null. Can i not subscribe to this event while Revit is starting up?
I was able to do this before with application.ViewActivated += ..... Im wondering if this has something to do with DB vs UI driven events and when they are allowed to be subscribed to? I just don't know.
namespace RevitModelHealth
{
public class checkHealth : IExternalApplication
{
// Document doc;
static public Autodesk.Revit.ApplicationServices.Application m_app = null;
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
m_app.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral);
return Result.Succeeded;
}
void m_app_DocumentSavingToCentral(object sender, Autodesk.Revit.DB.Events.DocumentSynchronizingWithCentralEventArgs e)
{
MessageBox.Show("asd","asd");
}
}
}
Here is updated code reflecting my response to the first answer. The message box opens when the document is loaded. No errors are thrown when I try to initialize the synchronization event handlers, however, neither of the message boxes open before or after a synchronization event.
public class checkHealth : IExternalApplication
{
// Document doc;
static public Autodesk.Revit.ApplicationServices.Application m_app;
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
application.ControlledApplication.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(app_DocOpened);
return Result.Succeeded;
}
public void app_DocOpened(object sender, DocumentOpenedEventArgs args)
{
MessageBox.Show("asd","asd");
m_app.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral);
m_app.DocumentSynchronizedWithCentral += new EventHandler<Autodesk.Revit.DB.Events.DocumentSynchronizedWithCentralEventArgs>(m_app_DocumentSavedToCentral);
}
void m_app_DocumentSavingToCentral(object sender, Autodesk.Revit.DB.Events.DocumentSynchronizingWithCentralEventArgs e)
{
MessageBox.Show("sync", "sync");
}
void m_app_DocumentSavedToCentral(object sender, Autodesk.Revit.DB.Events.DocumentSynchronizedWithCentralEventArgs e)
{
MessageBox.Show("Doone", "Done");
}
}
this worked.... Thanks largely in part to the SDK sample project EventsMonitor
namespace RevitModelHealth
{
public class checkHealth : IExternalApplication
{
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
application.ControlledApplication.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(app_syncStart);
application.ControlledApplication.DocumentSynchronizedWithCentral += new EventHandler<DocumentSynchronizedWithCentralEventArgs>(app_syncOver);
return Result.Succeeded;
}
public void app_syncStart(object o ,DocumentSynchronizingWithCentralEventArgs args)
{
MessageBox.Show("","Stasrting");
}
public void app_syncOver(object o,DocumentSynchronizedWithCentralEventArgs args)
{
MessageBox.Show("", "Over");
}
}
}
Try
application.ControlledApplication.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral)
in your OnStartup() method.
The call is failing because instance member m_app is initialized to null.
The UIApplication.ControlledApplication object that raises the DocumentSynchronizingWithCentralEventArgs is being accessible from the parameter to OnStartup.
You can try this:
public void app_DocOpened(object sender, DocumentOpenedEventArgs args)
{
MessageBox.Show("asd","asd");
Autodesk.Revit.ApplicationServices.Application m_app = args.Document.Application;
m_app.DocumentSynchronizingWithCentral += new EventHandler<DocumentSynchronizingWithCentralEventArgs>(m_app_DocumentSavingToCentral);
m_app.DocumentSynchronizedWithCentral += new EventHandler<Autodesk.Revit.DB.Events.DocumentSynchronizedWithCentralEventArgs>(m_app_DocumentSavedToCentral);
}

How do I resolve WebViewRenderer is obsolete

This is what i get as error "WebViewRenderer.WebViewRenderer() is Obsolete
"This constructor is obsolete as of version 2.5. Please use the WebViewRenderer(Context) instead
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using ZoomWebView;
using Xamarin.Forms.Platform.Android;
using ZoomWebView.Droid;
using System.ComponentModel;
using Android.Webkit;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
using Xamarin.Forms.Internals;
using System.Threading.Tasks;
[assembly: ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]
namespace ZoomWebView.Droid
{
public class MyWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
{
return;
}
var element = Element as MyWebView;
Control.Settings.TextZoom = element.ZoomInLevel;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(Control != null)
{
Control.Settings.BuiltInZoomControls = true;
Control.Settings.DisplayZoomControls = true;
}
var element = Element as MyWebView;
Control.Settings.TextZoom = element.ZoomInLevel;
base.OnElementPropertyChanged(sender, e);
}
}
I expected the Code to run Because i followed a particular series on youtube But it's not. Please is there any thing i am doing wrong ?
You need to add the context:
public MyWebViewRenderer(Context context) : base(context)
{
}
In your code:
namespace ZoomWebView.Droid
{
public class MyWebViewRenderer : WebViewRenderer
{
public MyWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
{
return;
}
var element = Element as MyWebView;
Control.Settings.TextZoom = element.ZoomInLevel;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(Control != null)
{
Control.Settings.BuiltInZoomControls = true;
Control.Settings.DisplayZoomControls = true;
}
var element = Element as MyWebView;
Control.Settings.TextZoom = element.ZoomInLevel;
base.OnElementPropertyChanged(sender, e);
}
}
}
The reason it happened is quite simple Xamarin.Forms as of v2.4 marked Xamarin.Forms.Forms Context property as obsolete. So to get global context for renderer's it is necessary that you call the base class of that renderer meaning in your constructor you do the following:
public MyWebViewRenderer(Context context) : base(context)
{
}
XF now recommends you use James Montemagno's Current Activity Plugin. If you need the current context

Table Not found - SQLITE error

I'm developing windows phone 8 application.
I'm having some difficulty with my sqlite prepare statement. I get an error saying my table does not exist, although I've checked in multiple places for it, and it does exist.
It did work until I added some new tables to the SQLite database and now it just doesn't recognise any of the tables - so I'm confused!
I have also tried hardcoding the full path.. e.g. C:\App\datbase.db etc
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using SQLitePCL;
namespace WP7.VideoScanZXing.SampleApp
{
public partial class Page1 : PhoneApplicationPage
{
string connLOCDAT = "Data Source =\\Resources\\DB\\MCRS_Data.sdf;Persist Security Info=False";
string connLOCLUDAT = "Data Source =\\Resources\\DB\\MCRSLU_MYCUBE.sdf;Persist Security Info=False";
public Page1()
{
InitializeComponent();
//check the isolated storage to see if the user has saved a username and password.
CheckIsoStore();
}
public void CheckIsoStore() {
if (IsolatedStorageSettings.ApplicationSettings.Contains("UsrEmail"))
{
//The user has saved details
//populate the email and password box automatically
//Dont forget to check the save details box too
tbEmail.Text = IsolatedStorageSettings.ApplicationSettings["UsrEmail"].ToString();
pbPassword.Password = IsolatedStorageSettings.ApplicationSettings["UsrPassword"].ToString();
cbSaveDetails.IsChecked = true;
}
}
public void failedLogin()
{
MessageBox.Show("Error: Email or Password are incorrect. Please try again.");
tbEmail.Focus();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
//validate user
string strEmail = tbEmail.Text;
string strPassword = pbPassword.Password.ToString();
//bool bolValidUser = false;
//validate username and password here!
if (bolValidUser(strEmail, strPassword) == true)
{
//user has been validated and can continue.
if (cbSaveDetails.IsChecked == true)
{
//save the users details here
IsolatedStorageSettings.ApplicationSettings["UsrEmail"] = strEmail;
IsolatedStorageSettings.ApplicationSettings["UsrPassword"] = strPassword;
IsolatedStorageSettings.ApplicationSettings.Save();
}
else {
IsolatedStorageSettings.ApplicationSettings.Remove("UsrEmail");
IsolatedStorageSettings.ApplicationSettings.Remove("UsrPassword");
IsolatedStorageSettings.ApplicationSettings.Save();
}
NavigationService.Navigate(new Uri("/MenuPage.xaml", UriKind.Relative));
}
else {
//redirect the user back to the home screen with a message
//NavigationService.Navigate(new Uri("/LoginPage.xaml?message=Login error ", UriKind.Relative));
failedLogin();
}
}
public static SQLiteConnection dbConn;
public bool bolValidUser(string Uname, string PWord)
{
dbConn = new SQLitePCL.SQLiteConnection(Windows.ApplicationModel.Package.Current.InstalledLocation.Path + #"\bizData.db", SQLiteOpen.READWRITE);
{
//StorageFile databaseFile = await .GetFileAsync("bizData.db");
//await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
//using (var statement = dbConn.Prepare(#"SELECT * FROM [MCRS_LU_Login] WHERE [Email] = " + Uname + " AND [Password] = " + PWord))
using (var statement = dbConn.Prepare(#"SELECT * FROM [BARCODES]"))
{
if (statement.Step() == SQLiteResult.ROW)
{
//new MessageDialog(Convert.ToString(statement.DataCount)).ShowAsync();
//if ()
string strLinkedUser;
strLinkedUser = statement[3].ToString();
IsolatedStorageSettings.ApplicationSettings["UsrADName"] = statement[0].ToString();
return true;
}
else
{
return false;
//await msgDialog.ShowAsync();
}
}
}
private void tbEmail_GotFocus(object sender, RoutedEventArgs e)
{
imgMail.Visibility = Visibility.Collapsed;
}
private void tbEmail_LostFocus(object sender, RoutedEventArgs e)
{
if(tbEmail.Text =="") {
imgMail.Visibility = Visibility.Visible;
}
}
private void pbPassword_LostFocus(object sender, RoutedEventArgs e)
{
if (pbPassword.Password == "")
{
imgPassword.Visibility = Visibility.Visible;
}
}
private void pbPassword_GotFocus(object sender, RoutedEventArgs e)
{
imgPassword.Visibility = Visibility.Collapsed;
}
}
}

NHibernate - Distributed transactions and providing your own connection result in exception

NHibernate is throwning an exception when particpating in a distirbuted transaction and you've opened a session by specifying your own connection object.
Unhandled Exception: System.InvalidOperationException: Disconnect cannot be call
ed while a transaction is in progress.
at NHibernate.AdoNet.ConnectionManager.Disconnect()
at NHibernate.Impl.SessionImpl.Close()
at NHibernate.Impl.SessionImpl.Dispose(Boolean isDisposing)
at NHibernate.Transaction.AdoNetWithDistrubtedTransactionFactory.<>c__Display
Class1.<EnlistInDistributedTransactionIfNeeded>b__0(Object sender, TransactionEv
entArgs e)
at System.Transactions.TransactionCompletedEventHandler.Invoke(Object sender,
TransactionEventArgs e)
at System.Transactions.TransactionStatePromotedCommitted.EnterState(InternalT
ransaction tx)
at System.Transactions.InternalTransaction.DistributedTransactionOutcome(Inte
rnalTransaction tx, TransactionStatus status)
at System.Transactions.Oletx.RealOletxTransaction.FireOutcome(TransactionStat
us statusArg)
at System.Transactions.Oletx.OutcomeEnlistment.InvokeOutcomeFunction(Transact
ionStatus status)
at System.Transactions.Oletx.OletxTransactionManager.ShimNotificationCallback
(Object state, Boolean timeout)
at System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback
(Object state, Boolean timedOut)
The following code will reproduce the issue; reference the current FluentNibernate, and NHibernate 2.1.2.4000.
using System;
using System.Data.SqlClient;
using System.Transactions;
using FluentNHibernate.Mapping;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Cfg;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var cfg =
Fluently.Configure().Database(
MsSqlConfiguration.MsSql2008.ConnectionString("Integrated Security=SSPI;Data Source=.;Initial Catalog=Test").DefaultSchema("dbo")
).Mappings(x => x.FluentMappings.AddFromAssemblyOf<MyTableMap>()).BuildConfiguration();
using (var sf = cfg.BuildSessionFactory())
{
using (var ts = new TransactionScope().PromoteToDtc())
{
using (var conn = new SqlConnection("Integrated Security=SSPI;Data Source=.;Initial Catalog=Test"))
{
conn.Open();
using (var session = sf.OpenSession(conn))
{
session.Save(new MyTable { String = "Hello!" });
}
}
ts.Complete();
}
Console.WriteLine("It saved!");
Console.ReadLine();
}
}
}
public class DummyEnlistmentNotification : IEnlistmentNotification
{
public static readonly Guid Id = new Guid("E2D35055-4187-4ff5-82A1-F1F161A008D0");
public void Prepare(PreparingEnlistment preparingEnlistment)
{
preparingEnlistment.Prepared();
}
public void Commit(Enlistment enlistment)
{
enlistment.Done();
}
public void Rollback(Enlistment enlistment)
{
enlistment.Done();
}
public void InDoubt(Enlistment enlistment)
{
enlistment.Done();
}
}
public static class TSExetensions
{
public static TransactionScope PromoteToDtc(this TransactionScope scope)
{
Transaction.Current.EnlistDurable(DummyEnlistmentNotification.Id, new DummyEnlistmentNotification(), EnlistmentOptions.None);
return scope;
}
}
public class MyTable
{
public virtual int Id { get; private set; }
public virtual string String { get; set; }
}
public sealed class MyTableMap : ClassMap<MyTable>
{
public MyTableMap()
{
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.String).Not.Nullable();
}
}
}
The issue is indeed with NHiberate. They're working on a patch. For reference, the issue can be found here