public GXAMICommandPromptTab(Control parentForm, GXAmiClient client, GXAmiDataCollector collector, string media, string name, string settings)
 {
     Settings = settings.Replace(Environment.NewLine, "");
     ParentDlg = parentForm;
     Media = media;
     MediaName = name;
     Client = client;
     Client.OnDeviceErrorsAdded += new DeviceErrorsAddedEventHandler(Client_OnDeviceErrorsAdded);
     Client.OnTasksAdded += new TasksAddedEventHandler(Client_OnTasksAdded);
     Collector = collector;
     InitializeComponent();
     CancelBtn.Dock = CommandPromptTB.Dock = DockStyle.Fill;
     if (Environment.OSVersion.Platform == PlatformID.Win32NT)
     {
         try
         {
             CreateCaret(CommandPromptTB.Handle, IntPtr.Zero, 10, CommandPromptTB.Font.Height);
             ShowCaret(CommandPromptTB.Handle);
         }
         catch
         {
             //It's OK if this fails.
         }
     }
 }        
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="collector"></param>
        public GXAmiCommandPromptForm(GXAmiClient client, GXAmiDataCollector collector)
        {            
            Client = client;
            DataCollector = collector;
            InitializeComponent();
            ConnectingPanel.Dock = DockStyle.Fill;
            string selected = null;
            if (!string.IsNullOrEmpty(Gurux.DeviceSuite.Properties.Settings.Default.CommandPrompSettings))
            {
                List<string> arr = new List<string>(Gurux.DeviceSuite.Properties.Settings.Default.CommandPrompSettings.Split(new char[]{';'}));
                if (arr.Count > 1)
                {
                    selected = arr[0];
                }
            }

            foreach (string media in collector.Medias)
            {
                //Gateway is not shown here.
                if (media != "Gateway")
                {
                    int pos = MediaCB.Items.Add(media);                    
                    if (selected != null && string.Compare(selected, media) == 0)
                    {
                        MediaCB.SelectedIndex = pos;
                    }
                }
            }
            if (MediaCB.SelectedIndex == -1)
            {
                MediaCB.SelectedIndex = 0;
            }
        }
 public GXAmiEventListener(GXAmiDataCollectorServer server, GXProxyClass pc, GXAmiClient dc)
 {
     Server = server;
     DC = dc;
     pc.OnUpdated += new PropertyUpdateEventHandler(OnUpdated);
     pc.OnError += new ErrorEventHandler(pc_OnError);
     pc.OnStateChange += new DeviceStateChangedEventHandler(pc_OnStateChange);
     pc.OnUpdateParameters += new UpdateparametersEventHandler(pc_OnUpdateParameters);
     pc.OnTrace += new TraceAddEventHandler(pc_OnTrace);
 }
 public GXAmiDataCollectorForm(GXAmiClient client, GXAmiDataCollector collector, DataCollectorActionType action)
 {
     Action = action;
     Client = client;
     InitializeComponent();
     Collector = collector;
     RefreshBtn.Text = Gurux.DeviceSuite.Properties.Resources.RefreshTxt;
     RefreshBtn.Enabled = action != DataCollectorActionType.Add;
     if (collector != null)
     {
         this.NameTB.Text = Collector.Name;
         this.IPAddressTB.Text = Collector.IP;
         this.DescriptionTB.Text = Collector.Description;
         if (Collector.Guid != Guid.Empty)
         {
             this.GuidTB.Text = Collector.Guid.ToString();
         }
         if (Collector.LastRequestTimeStamp.HasValue)
         {
             LastConnectedTB.Text = Collector.LastRequestTimeStamp.Value.ToString();
         }
         InternalCB.Checked = collector.Internal;
     }            
 }
        /// <summary>
		/// Initializes a new instance of the GXAmiImportForm class.
		/// </summary>
        public GXAmiImportForm(GXAmiClient client, GXDeviceManufacturerCollection manufacturers)
            : base(manufacturers, null)
		{
			InitializeComponent();
            Client = client;
		}
        /// <summary>
        /// Start GuruxAMI Data collector as console.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Update previous installed settings.
            if (Properties.Settings.Default.UpdateSettings)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpdateSettings = false;
                Properties.Settings.Default.Save();
            }
            bool trace = false;
            GXAmiDataCollectorServer collector = null;

            try
            {
                for (int pos = 0; pos != args.Length; ++pos)
                {
                    string tag = args[pos];
                    if (tag[0] == '/' || tag[0] == '-')
                    {
                        tag = tag.Substring(1).ToLower();
                        if (tag == "h")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostName = args[++pos];
                        }
                        if (tag == "p")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostPort = args[++pos];
                        }
                        //Register Data Collector again.
                        if (tag == "r")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = Guid.Empty;
                        }
                        //Trace messages
                        if (tag == "t")
                        {
                            trace = true;
                        }
                    }
                }

                string host = GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostName;
                if (string.IsNullOrEmpty(host))
                {
                    ShowHelp();
                    return;
                }
                Guid guid = GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid;
                Console.WriteLine("Starting Data Collector...");
                if (!host.StartsWith("http://"))
                {
                    host = "http://" + host + ":" + GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostPort + "/";
                }
                Console.WriteLine("Connecting " + host);
                GXAmiUser user = null;
                string    r, dcName = null;
                GuruxAMI.Client.GXAmiClient cl = null;
                if (guid == Guid.Empty)
                {
                    Console.WriteLine("Registering Data Collector to GuruxAMI Service: ");
                    int pos = 0;
                    do
                    {
                        Console.WriteLine("Enter user name:");
                        string username = Console.ReadLine();
                        if (username == "")
                        {
                            return;
                        }
                        Console.WriteLine("Enter password:"******"")
                        {
                            return;
                        }
                        cl = new GXAmiClient(host, username, password);
                        //Get info from registered user.
                        try
                        {
                            user = cl.GetUserInfo();
                            break;
                        }
                        catch (UnauthorizedAccessException)
                        {
                            continue;
                        }
                    }while(++pos != 3);
                    //If authorisation failed.
                    if (user == null)
                    {
                        return;
                    }
                    Console.WriteLine("Finding data collectors.");
                    GXAmiDataCollector[] dcs = cl.GetDataCollectors();
                    //If there are existing DCs...
                    if (dcs.Length != 0)
                    {
                        Console.WriteLine("Do you want to register new data collector or bind old? (n/b)");
                        do
                        {
                            r = Console.ReadLine().Trim().ToLower();
                            if (r == "n" || r == "b")
                            {
                                break;
                            }
                        }while (r == "");
                    }
                    else
                    {
                        r = "n";
                    }
                    //Old DC replaced.
                    if (r == "b")
                    {
                        Console.WriteLine("Select data collector number that you want to bind:");
                        pos = 0;
                        foreach (GXAmiDataCollector it in dcs)
                        {
                            ++pos;
                            Console.WriteLine(pos.ToString() + ". " + it.Name);
                        }
                        do
                        {
                            r = Console.ReadLine().Trim();
                            int sel = 0;
                            if (int.TryParse(r, out sel) && sel > 0 && sel <= pos)
                            {
                                guid = dcs[sel - 1].Guid;
                                break;
                            }
                        }while (true);
                    }
                    else
                    {
                        do
                        {
                            Console.WriteLine("Enter name of the data collector:");
                            dcName = Console.ReadLine().Trim();
                            if (dcName == "")
                            {
                                return;
                            }
                            if (cl.Search(new string[] { dcName }, ActionTargets.DataCollector, SearchType.Name).Length == 0)
                            {
                                GXAmiDataCollector tmp = new GXAmiDataCollector(dcName, "", "");
                                cl.AddDataCollector(tmp, cl.GetUserGroups(false));
                                guid = tmp.Guid;
                                break;
                            }
                            Console.WriteLine("Name exists. Give new one.");
                        }while (true);
                    }
                }
                collector = new GXAmiDataCollectorServer(host, guid);
                if (trace)
                {
                    collector.OnTasksAdded   += new TasksAddedEventHandler(OnTasksAdded);
                    collector.OnTasksClaimed += new TasksClaimedEventHandler(OnTasksClaimed);
                    collector.OnTasksRemoved += new TasksRemovedEventHandler(OnTasksRemoved);
                    collector.OnError        += new ErrorEventHandler(OnError);
                }
                collector.OnAvailableSerialPorts += new AvailableSerialPortsEventHandler(OnAvailableSerialPorts);
                GXAmiDataCollector dc          = collector.Init(dcName);
                //If new Data collector is added bind it to the user groups.
                if (guid == Guid.Empty && cl != null)
                {
                    cl.AddDataCollector(dc, cl.GetUserGroups(false));
                }
                if (dc != null)
                {
                    GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = dc.Guid;
                }
                Console.WriteLine(string.Format("Data Collector '{0}' started.", dc.Name));
                GuruxAMI.DataCollector.Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
                if (ex is UnauthorizedAccessException)
                {
                    Console.WriteLine("Unknown data collector.");
                    GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = Guid.Empty;
                    GuruxAMI.DataCollector.Properties.Settings.Default.Save();
                }
                else
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //Wait until user press enter.
            ConsoleKeyInfo key;

            while ((key = System.Console.ReadKey()).Key != ConsoleKey.Enter)
            {
                System.Console.Write("\b \b");
            }
            if (collector != null)
            {
                collector.Dispose();
            }
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="scheduleItem"></param>
        public GXAmiScheduleEditorDlg(GXAmiClient client, GXAmiSchedule schedule)
        {         
            Client = client;
            InitializeComponent();
            m_ScheduleItem = schedule;
            if (System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek == DayOfWeek.Sunday)
            {
                Point TmpLoc = new Point(DaySunCb.Location.X, DaySunCb.Location.Y);
                DaySunCb.Location = DayMonCb.Location;
                DayMonCb.Location = DayTueCb.Location;
                DayTueCb.Location = DayWedCb.Location;
                DayWedCb.Location = DayThuCb.Location;
                DayThuCb.Location = DayFriCb.Location;
                DayFriCb.Location = DaySatCb.Location;
                DaySatCb.Location = TmpLoc;
            }
            FillEnums();
            UpdateResouces();

            NameTb.Text = m_ScheduleItem.Name;
            if (m_ScheduleItem.TransactionStartTime != null)
            {
                TransactionStartTimeTp.Value = m_ScheduleItem.TransactionStartTime.Value;
            }
            else
            {
                TransactionStartTimeTp.Checked = false;
            }
            if (m_ScheduleItem.TransactionEndTime != null)
            {
                TransactionEndTimeTp.Value = m_ScheduleItem.TransactionEndTime.Value;
            }
            //Has to be done to uncheck, known issue in .NET
            TransactionEndTimeTp.Checked = true; //Has to be done to uncheck, known issue in .NET
            TransactionEndTimeTp.Checked = m_ScheduleItem.TransactionEndTime != null;

            if (m_ScheduleItem.TransactionEndTime != null)
            {
                TransactionEndTimeTp.Value = m_ScheduleItem.TransactionEndTime.Value;
            }
            if (m_ScheduleItem.TransactionCount == 0)
            {
                TransactionCountCb.Checked = false;
                TransactionCountTb.Text = "";
            }
            else
            {
                TransactionCountCb.Checked = true;
                TransactionCountTb.Text = m_ScheduleItem.TransactionCount.ToString();
            }
            UpdateFrequencyTp.Value = new DateTime(((long)m_ScheduleItem.UpdateInterval) * 10000000 + UpdateFrequencyTp.MinDate.Ticks);
            RepeatModeCb.SelectedItem = ScheduleRepeatToString(m_ScheduleItem.RepeatMode);
            DayOfMonthTb.Text = m_ScheduleItem.DayOfMonth.ToString();
            IntervalTb.Text = m_ScheduleItem.Interval.ToString();
            ActionCb.SelectedItem = ScheduleActionToString(m_ScheduleItem.Action);
            if (m_ScheduleItem.ScheduleStartTime != null)
            {
                ScheduleStartDateTp.Value = m_ScheduleItem.ScheduleStartTime.Value;
            }
            if (m_ScheduleItem.ScheduleEndTime != null)
            {
                ScheduleEndDateTp.Value = m_ScheduleItem.ScheduleEndTime.Value;
            }
            ScheduleEndDateTp.Checked = true; //Has to be done to uncheck, known issue in .NET
            ScheduleEndDateTp.Checked = m_ScheduleItem.ScheduleEndTime != null;
            UpdateTargetCheckTree();

            ErrorWaitTimeTp.Value = new DateTime(ErrorWaitTimeTp.MinDate.Ticks + ((long)m_ScheduleItem.FailWaitTime) * 10000);
            //ErrorWaitTimeTp.Value. = m_ScheduleItem.FailWaitTime/1000.0;
            ErrorTryCountTb.Text = m_ScheduleItem.FailTryCount.ToString();
            ConnectionDelayTimeTp.Value = new DateTime(ConnectionDelayTimeTp.MinDate.Ticks + ((long)m_ScheduleItem.ConnectionDelayTime) * 10000);
            MaxThreadCountTb.Text = m_ScheduleItem.MaxThreadCount.ToString();
            //ConnectionFailWaitTimeTb.Text = Convert.ToString(m_ScheduleItem.ConnectionFailWaitTime/1000.0);
            ConnectionFailWaitTimeTp.Value = new DateTime(ConnectionFailWaitTimeTp.MinDate.Ticks + ((long)m_ScheduleItem.ConnectionFailWaitTime) * 10000);
            ConnectionFailTryCountTb.Text = m_ScheduleItem.ConnectionFailTryCount.ToString();

            if (m_ScheduleItem.DayOfWeeks == null)
            {
                DayMonCb.Checked = DayTueCb.Checked = DayWedCb.Checked = DayThuCb.Checked = DayFriCb.Checked = DaySatCb.Checked = DaySunCb.Checked = false;
            }
            else
            {
                System.Collections.Generic.List<DayOfWeek> list = new System.Collections.Generic.List<DayOfWeek>();
                list.AddRange(m_ScheduleItem.DayOfWeeks);
                DayMonCb.Checked = list.Contains(DayOfWeek.Monday);
                DayTueCb.Checked = list.Contains(DayOfWeek.Tuesday);
                DayWedCb.Checked = list.Contains(DayOfWeek.Wednesday);
                DayThuCb.Checked = list.Contains(DayOfWeek.Thursday);
                DayFriCb.Checked = list.Contains(DayOfWeek.Friday);
                DaySatCb.Checked = list.Contains(DayOfWeek.Saturday);
                DaySunCb.Checked = list.Contains(DayOfWeek.Sunday);
            }
            OKBtn.Enabled = (m_ScheduleItem.Status & ScheduleState.Run) == 0;
        }
        /// <summary>
        /// Start GuruxAMI Data collector as console.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Update previous installed settings.
            if (Properties.Settings.Default.UpdateSettings)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpdateSettings = false;
                Properties.Settings.Default.Save();
            }
            bool trace = false;
            GXAmiDataCollectorServer collector = null;
            try
            {
                for (int pos = 0; pos != args.Length; ++pos)
                {
                    string tag = args[pos];
                    if (tag[0] == '/' || tag[0] == '-')
                    {
                        tag = tag.Substring(1).ToLower();
                        if (tag == "h")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostName = args[++pos];
                        }
                        if (tag == "p")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostPort = args[++pos];
                        }
                        //Register Data Collector again.
                        if (tag == "r")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = Guid.Empty;
                        }
                        //Trace messages
                        if (tag == "t")
                        {
                            trace = true;
                        }
                    }
                }

                string host = GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostName;
                if (string.IsNullOrEmpty(host))
                {
                    ShowHelp();
                    return;
                }
                Guid guid = GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid;
                Console.WriteLine("Starting Data Collector...");
                if (!host.StartsWith("http://"))
                {
                    host = "http://" + host + ":" + GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostPort + "/";
                }
                Console.WriteLine("Connecting " + host);
                GXAmiUser user = null;
                string r, dcName = null;
                GuruxAMI.Client.GXAmiClient cl = null;
                if (guid == Guid.Empty)
                {
                    Console.WriteLine("Registering Data Collector to GuruxAMI Service: ");                    
                    int pos = 0;
                    do
                    {
                        Console.WriteLine("Enter user name:");
                        string username = Console.ReadLine();
                        if (username == "")
                        {
                            return;
                        }
                        Console.WriteLine("Enter password:"******"")
                        {
                            return;
                        }
                        cl = new GXAmiClient(host, username, password);
                        //Get info from registered user.
                        try
                        {
                            user = cl.GetUserInfo();
                            break;
                        }
                        catch(UnauthorizedAccessException)
                        {
                            continue;
                        }                        
                    }while(++pos != 3);
                    //If authorisation failed.
                    if (user == null)
                    {
                        return;
                    }
                    Console.WriteLine("Finding data collectors.");                    
                    GXAmiDataCollector[] dcs = cl.GetDataCollectors();
                    //If there are existing DCs...
                    if (dcs.Length != 0)
                    {
                        Console.WriteLine("Do you want to register new data collector or bind old? (n/b)");
                        do
                        {
                            r = Console.ReadLine().Trim().ToLower();
                            if (r == "n" || r == "b")
                            {
                                break;
                            }
                        }
                        while (r == "");
                    }
                    else
                    {
                        r = "n";
                    }
                    //Old DC replaced.
                    if (r == "b")
                    {
                        Console.WriteLine("Select data collector number that you want to bind:");
                        pos = 0;
                        foreach (GXAmiDataCollector it in dcs)
                        {
                            ++pos;
                            Console.WriteLine(pos.ToString() + ". " + it.Name);
                        }
                        do
                        {
                            r = Console.ReadLine().Trim();
                            int sel = 0;
                            if (int.TryParse(r, out sel) && sel > 0 && sel <= pos)
                            {
                                guid = dcs[sel - 1].Guid;
                                break;
                            }
                        }
                        while (true);
                    }
                    else
                    {
                        do
                        {
                            Console.WriteLine("Enter name of the data collector:");
                            dcName = Console.ReadLine().Trim();
                            if (dcName == "")
                            {
                                return;
                            }
                            if (cl.Search(new string[] { dcName }, ActionTargets.DataCollector, SearchType.Name).Length == 0)
                            {
                                GXAmiDataCollector tmp = new GXAmiDataCollector(dcName, "", "");
                                cl.AddDataCollector(tmp, cl.GetUserGroups(false));
                                guid = tmp.Guid;
                                break;
                            }
                            Console.WriteLine("Name exists. Give new one.");
                        }
                        while (true);
                    }
                }
                collector = new GXAmiDataCollectorServer(host, guid);
                if (trace)
                {
                    collector.OnTasksAdded += new TasksAddedEventHandler(OnTasksAdded);
                    collector.OnTasksClaimed += new TasksClaimedEventHandler(OnTasksClaimed);
                    collector.OnTasksRemoved += new TasksRemovedEventHandler(OnTasksRemoved);
                    collector.OnError += new ErrorEventHandler(OnError);                    
                }
                collector.OnAvailableSerialPorts += new AvailableSerialPortsEventHandler(OnAvailableSerialPorts);
                GXAmiDataCollector dc = collector.Init(dcName);
                //If new Data collector is added bind it to the user groups.
                if (guid == Guid.Empty && cl != null)
                {
                    cl.AddDataCollector(dc, cl.GetUserGroups(false));
                }
                if (dc != null)
                {
                    GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = dc.Guid;
                }                
                Console.WriteLine(string.Format("Data Collector '{0}' started.", dc.Name));
                GuruxAMI.DataCollector.Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {                
                if (ex is UnauthorizedAccessException)
                {
                    Console.WriteLine("Unknown data collector.");
                    GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = Guid.Empty;
                    GuruxAMI.DataCollector.Properties.Settings.Default.Save();
                }
                else
                {
                    Console.WriteLine(ex.Message);
                }   
            }
            //Wait until user press enter.
            ConsoleKeyInfo key;
            while ((key = System.Console.ReadKey()).Key != ConsoleKey.Enter)
            {
                System.Console.Write("\b \b");
            }
            if (collector != null)
            {
                collector.Dispose();
            }            
        }
Beispiel #9
0
        void StartServer(object param)
        {
            bool initialize = (bool) param;
            GXDBService Server = null;
            try
            {
                this.BeginInvoke(new UpdateStatusEventHandler(OnUpdateStatusEventHandler), 0, "Starting GuruxAMI...");
                string baseUr = Gurux.DeviceSuite.Properties.Settings.Default.AmiHostName;
                bool useServer = Gurux.DeviceSuite.Properties.Settings.Default.AmiHostName.Contains("localhost") || Gurux.DeviceSuite.Properties.Settings.Default.AmiHostName.Contains("*");
                if (useServer)
                {
                    string connStr = null;
                    //If DB is set
                    if (!string.IsNullOrEmpty(Gurux.DeviceSuite.Properties.Settings.Default.AmiDatabaseHostName))
                    {
                        connStr = string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}",
                         Gurux.DeviceSuite.Properties.Settings.Default.AmiDatabaseHostName, Gurux.DeviceSuite.Properties.Settings.Default.AmiDatabaseName,
                         Gurux.DeviceSuite.Properties.Settings.Default.AmiDBUserName, Gurux.DeviceSuite.Properties.Settings.Default.AmiDBPassword);
                    }
                    try
                    {
                        OrmLiteConnectionFactory f = new OrmLiteConnectionFactory(connStr, false, ServiceStack.OrmLite.MySql.MySqlDialectProvider.Instance);
                        f.AutoDisposeConnection = true;
                        Server = new GXDBService(baseUr, f,
                            Gurux.DeviceSuite.Properties.Settings.Default.AmiDatabaseTablePrefix);
                        if (Server.IsDatabaseCreated())
                        {
                            Server.Update();
                        }
                    }
                    catch (System.Net.HttpListenerException)
                    {
                        //If GuruxAMI service is already started.
                        Server = null;
                    }
                }
                else
                {
                    baseUr = Gurux.DeviceSuite.Properties.Settings.Default.AmiHostName;
                }

                if (Client == null)
                {
                    if (baseUr.Contains("*"))
                    {
                        baseUr = baseUr.Replace("*", "localhost");
                    }
                    Client = new GXAmiClient(baseUr,
                        Gurux.DeviceSuite.Properties.Settings.Default.AmiUserName,
                        Gurux.DeviceSuite.Properties.Settings.Default.AmiPassword);
                }

                //Create schedule server.
                if (SchedulerServer == null)
                {
                    this.BeginInvoke(new UpdateStatusEventHandler(OnUpdateStatusEventHandler), -1, "Starting GuruxAMI schedule server...");
                    SchedulerServer = new GXAmiSchedulerServer(baseUr,
                        Gurux.DeviceSuite.Properties.Settings.Default.AmiUserName,
                        Gurux.DeviceSuite.Properties.Settings.Default.AmiPassword);                    
                }
                if (Client.IsDatabaseCreated())
                {                    
                    Client.OnDeviceProfilesAdded += new DeviceProfilesAddedEventHandler(Client_OnDeviceProfilesAdded);
                    Client.OnDeviceProfilesRemoved += new DeviceProfilesRemovedEventHandler(Client_OnDeviceProfilesRemoved);
                    Client.OnDataCollectorsAdded += new DataCollectorsAddedEventHandler(Client_OnDataCollectorsAdded);
                    Client.OnDataCollectorsRemoved += new DataCollectorsRemovedEventHandler(Client_OnDataCollectorsRemoved);
                    Client.OnDataCollectorsUpdated += new DataCollectorsUpdatedEventHandler(Client_OnDataCollectorsUpdated);
                    Client.OnDeviceErrorsAdded += new DeviceErrorsAddedEventHandler(Client_OnDeviceErrorsAdded);
                    Client.OnDeviceErrorsRemoved += new DeviceErrorsRemovedEventHandler(Client_OnDeviceErrorsRemoved);
                    Client.OnDeviceGroupsAdded += new DeviceGroupsAddedEventHandler(Client_OnDeviceGroupsAdded);
                    Client.OnDeviceGroupsRemoved += new DeviceGroupsRemovedEventHandler(Client_OnDeviceGroupsRemoved);
                    Client.OnDeviceGroupsUpdated += new DeviceGroupsUpdatedEventHandler(Client_OnDeviceGroupsUpdated);
                    Client.OnDevicesAdded += new DevicesAddedEventHandler(Client_OnDevicesAdded);
                    Client.OnDevicesRemoved += new DevicesRemovedEventHandler(Client_OnDevicesRemoved);
                    Client.OnDevicesUpdated += new DevicesUpdatedEventHandler(Client_OnDevicesUpdated);
                    Client.OnSystemErrorsAdded += new SystemErrorsAddedEventHandler(Client_OnSystemErrorsAdded);
                    Client.OnSystemErrorsRemoved += new SystemErrorsRemovedEventHandler(Client_OnSystemErrorsRemoved);
                    Client.OnTasksAdded += new TasksAddedEventHandler(Client_OnTasksAdded);
                    Client.OnTasksClaimed += new TasksClaimedEventHandler(Client_OnTasksClaimed);
                    Client.OnTasksRemoved += new TasksRemovedEventHandler(Client_OnTasksRemoved);
                    Client.OnValueUpdated += new ValueUpdatedEventHandler(Client_OnValueUpdated);
                    Client.OnDeviceStateChanged += new DeviceStateChangedEventHandler(Client_OnDeviceStateChanged);
                    Client.OnDataCollectorStateChanged += new DataCollectorsStateChangedEventHandler(Client_OnDataCollectorStateChanged);
                    Client.OnTraceStateChanged += new TraceStateChangedEventHandler(Client_OnTraceStateChanged);
                    Client.OnTraceAdded += new TraceAddedEventHandler(Client_OnTraceAdded);
                    Client.OnTraceClear += new TraceClearEventHandler(Client_OnTraceClear);
                    Client.OnSchedulesAdded += new SchedulesAddedEventHandler(Client_OnSchedulesAdded);
                    Client.OnSchedulesRemoved += new SchedulesRemovedEventHandler(Client_OnSchedulesRemoved);
                    Client.OnSchedulesUpdated += new SchedulesUpdatedEventHandler(Client_OnSchedulesUpdated);
                    Client.OnSchedulesStateChanged += new SchedulesStateChangedEventHandler(Client_OnSchedulesStateChanged);
                    Client.StartListenEvents();
                    SchedulerServer.Start();
                    //Get all DC automatically.
                    GXAmiDataCollector[] collectors = new GXAmiDataCollector[0];
                    if (Gurux.DeviceSuite.Properties.Settings.Default.GetDataCollectorsAutomatically)
                    {
                        this.BeginInvoke(new UpdateStatusEventHandler(OnUpdateStatusEventHandler), -1, "Starting GuruxAMI data collectors...");
                        collectors = Client.GetDataCollectors();
                        Client_OnDataCollectorsAdded(Client, collectors);
                    }
                    if (Gurux.DeviceSuite.Properties.Settings.Default.GetDevicesAutomatically)
                    {
                        this.BeginInvoke(new UpdateStatusEventHandler(OnUpdateStatusEventHandler), -1, "Starting GuruxAMI devices...");
                        DateTime start = DateTime.Now;
                        GXAmiDevice[] devices = Client.GetDevices(false, DeviceContentType.Main);                        
                        Client_OnDevicesAdded(Client, null, devices);
                        System.Diagnostics.Debug.WriteLine("Getting devices: " + (DateTime.Now - start).TotalSeconds.ToString());                      
                    }
                    //Get all tasks and show them.
                    Client_OnTasksAdded(Client, Client.GetTasks(TaskState.All, false));
                    //Get all schedules and show them.
                    Client_OnSchedulesAdded(Client, Client.GetSchedules());

                    //Get all device profiles and show them
                    GXAmiDeviceProfile[] profiles = Client.GetDeviceProfiles(true, false);
                    Client_OnDeviceProfilesAdded(Client, profiles);
                    this.BeginInvoke(new ServerStateChanged(OnServerStateChanged), true);

                    //Start Data Collectors.
                    if (Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors != null)
                    {
                        List<string> tmp = new List<string>(Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.Cast<string>());
                        foreach (string str in tmp)
                        {
                            Guid guid = new Guid(str);
                            try
                            {
                                GXAmiDataCollector dc = null;
                                foreach (GXAmiDataCollector it2 in collectors)
                                {
                                    if (it2.Guid == guid)
                                    {
                                        dc = it2;
                                        break;
                                    }
                                }
                                if (dc == null)
                                {
                                    dc = Client.GetDataCollectorByGuid(guid);
                                    //DC might be null if DC not found from the DB.
                                    if (dc != null)
                                    {
                                        Client_OnDataCollectorsAdded(Client, new GXAmiDataCollector[] { dc });
                                    }
                                    else
                                    {
                                        Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.Remove(str);
                                    }
                                }
                                if (dc != null)
                                {
                                    dc.Internal = true;
                                    StartDataCollector(guid);
                                }
                            }
                            //If DC is removed.
                            catch (UnauthorizedAccessException)
                            {
                                Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.Remove(str);
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("GuruxAMI database not created.");
                }
                Started.Set();
                this.BeginInvoke(new UpdateStatusEventHandler(OnUpdateStatusEventHandler), 1, Gurux.DeviceSuite.Properties.Resources.ReadyTxt);
            }
            catch (Exception ex)
            {
                if (initialize)
                {
                    this.BeginInvoke(new UpdateStatusEventHandler(OnUpdateStatusEventHandler), 1, Gurux.DeviceSuite.Properties.Resources.ReadyTxt);
                }
                else
                {
                    this.BeginInvoke(new UpdateStatusEventHandler(OnUpdateStatusEventHandler), 2, "GuruxAMI start failed: " + ex.Message);
                }
                Started.Set();
                if (Client != null)
                {
                    Client.Dispose();
                    Client = null;
                }
            }
            ClosingApplication.WaitOne();

            if (SchedulerServer != null)
            {
                SchedulerServer.Stop();
                SchedulerServer = null;
            }
            if (Server != null)
            {
                Server.Stop();
                Server = null;
            }
            if (Client != null)
            {
                Client.Dispose();
                Client = null;
            }
            foreach (GXAmiDataCollectorServer it in DataCollectors)
            {
                it.Close();
            }
            ServerThreadClosed.Set();
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="guid">Data Collector Guid.</param>
 public GXAmiDataCollectorServer(string baseUr, Guid guid)
 {
     DC = new GXAmiClient(baseUr, guid);
 }
 public void Dispose()
 {            
     if (DC != null)
     {
         //Close collector thread.                
         Closing.Set();
         TaskModified.Set();                
         if (Thread != null)
         {
             Thread.Join();
             Thread = null;
         }
         DC.Dispose();
         DC = null;
     }
 }
 void Connect(object sender, GXAsyncWork work, object[] parameters)
 {
     GXAmiClient cl = new GXAmiClient(Info.Address, this.NameTB.Text, this.PasswordTB.Text);
     cl.GetUserInfo();
     if (!work.IsCanceled)
     {
         Client = cl;
     }
 }
 public GXAmiDeviceSettingsForm(GXAmiClient client, GuruxAMI.Common.GXAmiDevice device, GXAmiDataCollector[] dcs)
 {
     InitializeComponent();            
     DataCollectors = dcs;
     AvailableMedias = new List<string>();                    
     Client = client;
     Device = device;
     ulong id = GetAllAvailableMediasFromDCs();
     if (Device != null)
     {
         MediaConnections.AddRange(Device.Medias);
     }
     this.CollectorsCB.Items.Add("");
     foreach (GXAmiDataCollector it in DataCollectors)
     {
         int pos2 = this.CollectorsCB.Items.Add(it);                
         if (id == it.Id)             
         {
             this.CollectorsCB.SelectedIndex = pos2;
         }
     }
     if (this.CollectorsCB.SelectedIndex == -1)
     {
         this.CollectorsCB.SelectedIndex = 0;
     }
     SettingsPanel.Dock = PropertyGrid.Dock = PresetList.Dock = CustomDeviceProfile.Dock = DockStyle.Fill;
     //GuruxAMI.Common.Device type can not be changed after creation. This is for secure reasons.
     PresetCB.Enabled = CustomRB.Enabled = PresetList.Enabled = CustomDeviceProfile.Enabled = Device == null;                  
     CustomDeviceProfile.Visible = false;            
     if (Device != null)
     {
         //Add redundant conections.
         for (int pos = 1; pos < Device.Medias.Length; ++pos)
         {
             AddConnection(Device.Medias[pos]);
         }            
         NameTB.Text = Device.Name;
         RefreshRateTp.Value = new DateTime(((long)Device.UpdateInterval) * 10000000 + RefreshRateTp.MinDate.Ticks);
         UpdateResendCnt(Device.ResendCount);
         UpdateWaitTime(Device.WaitTime);
         //Create UI Device so all assemblys are loaded.
         string path = Path.Combine(Gurux.Common.GXCommon.ApplicationDataPath, "Gurux");
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
             Gurux.Common.GXFileSystemSecurity.UpdateDirectorySecurity(path);
         }
         path = Path.Combine(path, "Gurux.DeviceSuite");
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
             Gurux.Common.GXFileSystemSecurity.UpdateDirectorySecurity(path);
         }
         path = Path.Combine(path, "DeviceProfiles");
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
             Gurux.Common.GXFileSystemSecurity.UpdateDirectorySecurity(path);
         }
         path = Path.Combine(path, Device.ProfileGuid.ToString());
         //Load Device template if not loaded yet.                                 
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
             Gurux.Common.GXFileSystemSecurity.UpdateDirectorySecurity(path);
             byte[] data = Client.GetDeviceProfilesData(Device.ProfileGuid);
             GXZip.Import(this, data, path + "\\");
         }
         path = Path.Combine(path, Device.ProfileGuid.ToString() + ".gxp");
         UIDevice = GXDevice.Load(path);                
     }
     else
     {
         RefreshRateTp.Value = new DateTime(((long)1) * 10000000 + RefreshRateTp.MinDate.Ticks);                
     }
     //Add disabled actions.
     m_DisActions = new DisabledAction(Device == null ? Gurux.Device.DisabledActions.None : (Gurux.Device.DisabledActions)Device.DisabledActions);
     tabControl1.TabPages.Add(m_DisActions.DisabledActionsTB);
     this.Text = Gurux.DeviceSuite.Properties.Resources.DeviceSettingsTxt;
     this.GeneralTab.Text = Gurux.DeviceSuite.Properties.Resources.GeneralTxt;
     //Update helps from the resources.
     this.helpProvider1.SetHelpString(this.NameTB, Gurux.DeviceSuite.Properties.Resources.DeviceNameHelp);
     this.helpProvider1.SetHelpString(this.MediaCB, Gurux.DeviceSuite.Properties.Resources.MediaListHelp);
     this.helpProvider1.SetHelpString(this.RefreshRateTp, Gurux.DeviceSuite.Properties.Resources.RefreshRateHelp);
     this.helpProvider1.SetHelpString(this.OkBtn, Gurux.DeviceSuite.Properties.Resources.OKHelp);
     this.helpProvider1.SetHelpString(this.CancelBtn, Gurux.DeviceSuite.Properties.Resources.CancelHelp);
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="client"></param>
 public GXAmiSchedulerServer(GXAmiClient client)
 {
     Client = client;
     sharedClient = true;
 }        
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="baseUr">Address of GuruxAMI server.</param>
 public GXAmiSchedulerServer(string baseUr, string userName, string password)
 {
     sharedClient = false;
     Client = new GXAmiClient(baseUr, userName, password);
 }