aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Integration/Emergency/IEmergencyNotificationProvider.cs
blob: 9d8f0d421393dd405a7db608392ea1dffc0f00c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Integration.Emergency
{
    /// <summary>
    /// Represents a machine emergency notification provider.
    /// </summary>
    public interface IEmergencyNotificationProvider
    {
        /// <summary>
        /// Gets or sets a value indicating whether to enable emergency detection and notification.
        /// </summary>
        bool IsEnabled { get; set; }

        /// <summary>
        /// Gets or sets the address/port of the detection device.
        /// </summary>
        String Address { get; set; }

        /// <summary>
        /// Gets or sets the current emergency status.
        /// </summary>
        EmergencyStatus Status { get; set; }

        /// <summary>
        /// Occurs when the emergency status has changed.
        /// </summary>
        event EventHandler<EmergencyStatusChangedEventArgs> StatusChanged;
    }
}
; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.BL.Entities;
using Tango.Core;
using Tango.Settings;

namespace Tango.BL
{
    [DbConfigurationType(typeof(ObservablesContextConfiguration))]
    public partial class ObservablesContext
    {
        private List<ObservableModifiedEventArgs> _pending_notifications = new List<ObservableModifiedEventArgs>();
        private ObservablesContextAdapter _adapter;
        private static DataSource _override_datasource;

        /// <summary>
        /// Initializes a new instance of the <see cref="ObservablesContext"/> class.
        /// </summary>
        public ObservablesContext()
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ObservablesContext" /> class.
        /// </summary>
        /// <param name="path">The server file path.</param>
        /// <param name="isFile">if set to <c>true</c> will try to connect to an .mdf file.</param>
        public ObservablesContext(DataSource dataSource) : base(dataSource.ToConnection(), true)
        {
            Database.SetInitializer<ObservablesContext>(null);
            Configuration.LazyLoadingEnabled = false;
            _adapter = new ObservablesContextAdapter(this);
        }

        /// <summary>
        /// Creates a default remote database context by the address specified in <see cref="SettingsManager.Default.DataBase.SQLServerAddress" />.
        /// </summary>
        /// <returns></returns>
        public static ObservablesContext CreateDefault()
        {
            return new ObservablesContext(_override_datasource != null ? _override_datasource : SettingsManager.Default.GetOrCreate<CoreSettings>().DataSource);
        }

        /// <summary>
        /// Creates a default remote database context.
        /// </summary>
        /// <returns></returns>
        public static ObservablesContext CreateDefault(DataSource dataSource)
        {
            return new ObservablesContext(dataSource);
        }

        /// <summary>
        /// Creates a default remote database context.
        /// </summary>
        /// <returns></returns>
        public static ObservablesContext CreateDefault(String address, String catalog, DataSourceType type)
        {
            return new ObservablesContext(new DataSource()
            {
                Address = address,
                Catalog = catalog,
                IntegratedSecurity = true,
                Type = type
            });
        }

        /// <summary>
        /// Creates a default remote database context.
        /// </summary>
        /// <returns></returns>
        public static ObservablesContext CreateDefault(String address, DataSourceType type)
        {
            return CreateDefault(address, "Tango", type);
        }

        /// <summary>
        /// Creates a default remote database context.
        /// </summary>
        /// <returns></returns>
        public static ObservablesContext CreateDefault(String address)
        {
            return CreateDefault(address, "Tango", DataSourceType.SQLServer);
        }

        /// <summary>
        /// Saves all changes made in this context to the underlying database.
        /// </summary>
        /// <returns>
        /// The number of objects written to the underlying database.
        /// </returns>
        public override int SaveChanges()
        {
            var result = base.SaveChanges();
            RaisePendingNotifications();
            return result;
        }

        /// <summary>
        /// Asynchronously saves all changes made in this context to the underlying database.
        /// </summary>
        /// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to complete.</param>
        /// <returns>
        /// A task that represents the asynchronous save operation.
        /// The task result contains the number of objects written to the underlying database.
        /// </returns>
        /// <remarks>
        /// Multiple active operations on the same context instance are not supported.  Use 'await' to ensure
        /// that any asynchronous operations have completed before calling another method on this context.
        /// </remarks>
        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            var result = base.SaveChangesAsync(cancellationToken);
            RaisePendingNotifications();
            return result;
        }

        /// <summary>
        /// Raises the pending notifications.
        /// </summary>
        private void RaisePendingNotifications()
        {
            Task.Factory.StartNew(() =>
            {
                foreach (var e in _pending_notifications.DistinctBy(x => x.NotifiedEntity))
                {
                    try
                    {
                        e.NotifiedEntity.RaiseModified(e.Context, e.ModifiedEntity, e.NotifiedEntity);
                    }
                    catch { }
                }

                _pending_notifications.Clear();
            });
        }

        /// <summary>
        /// Extension point allowing the user to override the default behavior of validating only
        /// added and modified entities.
        /// </summary>
        /// <param name="entityEntry">DbEntityEntry instance that is supposed to be validated.</param>
        /// <returns>
        /// true to proceed with validation; false otherwise.
        /// </returns>
        protected override bool ShouldValidateEntity(DbEntityEntry entityEntry)
        {
            if (entityEntry.State == EntityState.Modified && entityEntry.Entity is IObservableEntity)
            {
                IObservableEntity modified = entityEntry.Entity as IObservableEntity;

                //Good chance to update "LAST_UPDATED" field!
                modified.LastUpdated = DateTime.UtcNow;

                foreach (var toNotify in ObservableEntitiesContainer.RegisteredEntities.ToList().Where(x => x.Guid == modified.Guid).ToList())
                {
                    _pending_notifications.Add(new ObservableModifiedEventArgs(this, modified, toNotify));
                }
            }

            return base.ShouldValidateEntity(entityEntry);
        }

        /// <summary>
        /// Gets an instance of <see cref="ObservablesContextAdapter"/> which wraps this instance.
        /// </summary>
        public ObservablesContextAdapter Adapter
        {
            get { return _adapter; }
        }

        /// <summary>
        /// Overrides the default data source that is read from the core settings.
        /// </summary>
        /// <param name="dataSource">The data source.</param>
        public static void OverrideSettingsDataSource(DataSource dataSource)
        {
            _override_datasource = dataSource;
        }

        /// <summary>
        /// Gets the actual data source (settings or overridden).
        /// </summary>
        /// <returns></returns>
        public static DataSource GetActualDataSource()
        {
            return _override_datasource != null ? _override_datasource : SettingsManager.Default.GetOrCreate<CoreSettings>().DataSource;
        }
    }
}