/// <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 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.
         }
     }
 }        
Esempio n. 3
0
        /// <summary>
        /// Stop listen events.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GXEventsUnregisterResponse Put(GXEventsUnregisterRequest request)
        {
            if (request.Instance.Equals(Guid.Empty))
            {
                throw new Exception("Guid is empty.");
            }
            Guid         guid = Guid.Empty;
            IAuthSession s    = this.GetSession(false);
            long         id;

            if (!long.TryParse(s.Id, out id))
            {
                if (!GXBasicAuthProvider.IsGuid(s.UserAuthName, out guid))
                {
                    throw new ArgumentException("Access denied.");
                }
            }
            AppHost host = this.ResolveService <AppHost>();

            host.RemoveEvent(request.Instance, request.DataCollectorGuid);
            if (guid != Guid.Empty)
            {
                //Notify that DC is disconnected.
                List <GXEventsItem> events = new List <GXEventsItem>();
                lock (Db)
                {
                    GXAmiDataCollector dc = Db.Select <GXAmiDataCollector>(q => q.Guid == guid)[0];
                    dc.State = Gurux.Device.DeviceStates.None;
                    Db.UpdateOnly(dc, p => p.StatesAsInt, p => p.Id == dc.Id);
                    events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.State, dc));
                }
                host.SetEvents(Db, this.Request, 0, events);
            }
            return(new GXEventsUnregisterResponse());
        }
 bool FindMediaFromCollector(string media, GXAmiDataCollector collector)
 {            
     if (collector == null)
     {
         return true;
     }
     foreach(string it in collector.Medias)
     {
         if (string.Compare(it, media, true) == 0)
         {
             return true;
         }
     }
     return false;
 }
Esempio n. 5
0
        public static GXAmiDataCollector AddDataCollector(IDbConnection Db)
        {
            GXAmiDataCollector dc = new GXAmiDataCollector();

            dc.Guid  = Guid.NewGuid();
            dc.MAC   = GetMACAddress();
            dc.Added = DateTime.Now.ToUniversalTime();
            Db.Insert(dc);
#if !SS4
            dc.Id = (ulong)Db.GetLastInsertId();
#else
            dc.Id = (ulong)Db.LastInsertId();
#endif
            return(dc);
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="collectors"></param>
 /// <param name="medias"></param>
 /// <param name="media"></param>
 public RedundantForm(GXClient client, GXAmiDataCollector[] collectors, GXAmiMediaType[] medias, GXAmiDeviceMedia media)
 {
     InitializeComponent();
     Client = client;
     Collectors = collectors;
     Medias = medias;
     SelectedMedia = media;
     UpdateCollectors();
     if (media.DataCollectorId == null)
     {
         UpdateMedias();
     }
     if (!string.IsNullOrEmpty(SelectedMedia.Settings))
     {
         Media.Settings = SelectedMedia.Settings;
         ((IGXPropertyPage)PropertiesForm).Initialize();
     }
 }
        /// <summary>
        /// Update new data collector state.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GXDataCollectorStateUpdateResponse Put(GXDataCollectorStateUpdateRequest request)
        {
            List <GXEventsItem> events = new List <GXEventsItem>();

            lock (Db)
            {
                foreach (var it in request.States)
                {
#if !SS4
                    GXAmiDataCollector dc = Db.GetById <GXAmiDataCollector>(it.Key);
#else
                    GXAmiDataCollector dc = Db.SingleById <GXAmiDataCollector>(it.Key);
#endif
                    dc.State = it.Value;
                    Db.UpdateOnly(dc, p => p.State, p => p.Id == it.Key);
                    events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.State, dc));
                }
            }
            AppHost host = this.ResolveService <AppHost>();
            host.SetEvents(Db, this.Request, 0, events);
            return(new GXDataCollectorStateUpdateResponse());
        }
        /// <summary>
        /// Update trace level for selected devices or Data Collectors.
        /// </summary>
        public GXTraceUpdateResponse Post(GXTraceUpdateRequest request)
        {
            List <GXEventsItem> events = new List <GXEventsItem>();

            lock (Db)
            {
                if (request.DataCollectorIDs != null)
                {
                    foreach (ulong id in request.DataCollectorIDs)
                    {
#if !SS4
                        GXAmiDataCollector it = Db.GetById <GXAmiDataCollector>(id);
#else
                        GXAmiDataCollector it = Db.SingleById <GXAmiDataCollector>(id);
#endif
                        it.TraceLevel = request.Level;
                        Db.UpdateOnly(it, p => p.TraceLevelAsInt, p => p.Id == id);
                        events.Add(new GXEventsItem(ActionTargets.Trace, Actions.Edit, it));
                    }
                }
                if (request.DeviceIDs != null)
                {
                    foreach (ulong id in request.DeviceIDs)
                    {
#if !SS4
                        GXAmiDevice it = Db.GetById <GXAmiDevice>(id);
#else
                        GXAmiDevice it = Db.SingleById <GXAmiDevice>(id);
#endif
                        it.TraceLevel = request.Level;
                        Db.UpdateOnly(it, p => p.TraceLevelAsInt, p => p.Id == id);
                        events.Add(new GXEventsItem(ActionTargets.Trace, Actions.Edit, it));
                    }
                }
            }
            AppHost host = this.ResolveService <AppHost>();
            host.SetEvents(Db, this.Request, 0, events);
            return(new GXTraceUpdateResponse());
        }
 /// <summary>
 /// Get trace level state.
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public GXTraceLevelResponse Get(GXTraceLevelRequest request)
 {
     lock (Db)
     {
         List <System.Diagnostics.TraceLevel> list = new List <System.Diagnostics.TraceLevel>();
         if (request.DataCollectors != null)
         {
             foreach (Guid guid in request.DataCollectors)
             {
                 GXAmiDataCollector it = Db.Select <GXAmiDataCollector>(q => q.Guid == guid)[0];
                 list.Add(it.TraceLevel);
             }
         }
         if (request.DeviceIDs != null)
         {
             foreach (ulong id in request.DeviceIDs)
             {
                 GXAmiDevice it = Db.Select <GXAmiDevice>(q => q.Id == id)[0];
                 list.Add(it.TraceLevel);
             }
         }
         return(new GXTraceLevelResponse(list.ToArray()));
     }
 }
 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;
     }            
 }
 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);
 }
Esempio n. 12
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();
            }
        }
 public GXDataCollectorUpdateResponse(GXAmiDataCollector[] collectors)
 {
     this.Collectors = collectors;
 }
Esempio n. 14
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();
            }            
        }
Esempio n. 15
0
 /// <summary>
 /// Add new Data collector. This is called when database is created and we want to add new DC.
 /// </summary>
 /// <param name="dc"></param>
 public void AddDataCollector(GXAmiDataCollector[] collectors)
 {
     if (Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors == null)
     {
         Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors = new System.Collections.Specialized.StringCollection();
     }
     foreach (GXAmiDataCollector dc in collectors)
     {
         if (dc.Internal)
         {
             if (string.IsNullOrEmpty(dc.Name))
             {
                 dc.Description = dc.Name = "Default data collector ";
             }
             dc.Medias = Gurux.Communication.GXClient.GetAvailableMedias(true);
             dc.SerialPorts = Gurux.Serial.GXSerial.GetPortNames();
             dc.MAC = GXAmiClient.GetMACAddressAsString();
             GXAmiDataCollectorServer cl = StartDataCollector(dc.Guid);
             cl.Update(dc);
             dc.Internal = true;                    
         }
     }
 }
 public GXDataCollectorsResponse(GXAmiDataCollector[] collectors)
 {
     Collectors = collectors;
 }
Esempio n. 17
0
 void Client_OnDataCollectorStateChanged(object sender, GXAmiDataCollector[] collectors)
 {
     if (this.InvokeRequired)
     {
         this.BeginInvoke(new DataCollectorsStateChangedEventHandler(OnDataCollectorStateChanged), sender, collectors);
     }
     else
     {
         OnDataCollectorStateChanged(sender, collectors);
     } 
 }
 void DC_OnDataCollectorsUpdated(object sender, GXAmiDataCollector[] collectors)
 {
     foreach (GXAmiDataCollector it in collectors)
     {
         if (it.Guid == this.DC.DataCollectorGuid)
         {
             TraceLevel = it.TraceLevel;
             break;
         }
     }
 }
Esempio n. 19
0
 /// <summary>
 /// Update DC.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="collectors"></param>
 void OnDataCollectorsUpdated(object sender, GXAmiDataCollector[] collectors)
 {
     try
     {
         foreach (GXAmiDataCollector it in collectors)
         {
             if (it.UnAssigned)
             {
                 ListViewItem node = UnassignedDCToListViewItem[it.Guid] as ListViewItem;
                 if (node != null)
                 {
                     node.Text = it.MAC;
                 }
             }
             else
             {
                 ListViewItem node = DCToListViewItem[it.Guid] as ListViewItem;
                 if (node != null)
                 {
                     //Update data.
                     bool Internal = (node.Tag as GXAmiDataCollector).Internal;
                     node.Tag = it;
                     it.Internal = Internal;
                     if (Internal)
                     {                                
                         if (Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors == null)
                         {
                             Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors = new StringCollection();
                         }
                         if (!Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.Contains(it.Guid.ToString()))
                         {
                             Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.Add(it.Guid.ToString());
                             StartDataCollector(it.Guid);
                         }                                
                     }
                     else if (Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors != null)
                     {
                         int pos = Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.IndexOf(it.Guid.ToString());
                         if (pos != -1)
                         {
                             Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.RemoveAt(pos);
                             foreach (GXAmiDataCollectorServer it2 in InternalDCs)
                             {
                                 if (it2.Guid == it.Guid)
                                 {
                                     it2.Close();
                                     InternalDCs.Remove(it2);
                                     break;
                                 }
                             }
                         }
                     }
                     if (it.Internal)
                     {
                         node.Text = it.Name + " [Internal]";
                     }
                     else
                     {
                         node.Text = it.Name;
                     }                            
                 }
             }
         }
     }
     catch (Exception ex)
     {
         GXCommon.ShowError(this.ParentComponent, Gurux.DeviceSuite.Properties.Resources.GuruxDeviceSuiteTxt, ex);
     }
 }
 /// <summary>
 /// Update data collector settings.
 /// </summary>
 /// <param name="dc"></param>
 public void Update(GXAmiDataCollector dc)
 {
     DC.Update(dc);
 }
Esempio n. 21
0
 /// <summary>
 /// Remove DC.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="collectors"></param>
 void OnDataCollectorsRemoved(object sender, GXAmiDataCollector[] collectors)
 {
     try
     {
         foreach (GXAmiDataCollector it in collectors)
         {
             if (it.UnAssigned)
             {
                 UnassignedDCList.Items.Remove(UnassignedDCToListViewItem[it.Guid] as ListViewItem);
                 UnassignedDCToListViewItem.Remove(it.Guid);
             }
             else
             {
                 DCList.Items.Remove(DCToListViewItem[it.Guid] as ListViewItem);
                 DCToListViewItem.Remove(it);
                 if (Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors != null)
                 {
                     foreach (string str in Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors)
                     {
                         if (it.Guid.ToString().Equals(str))
                         {
                             Gurux.DeviceSuite.Properties.Settings.Default.AmiDataCollectors.Remove(str);
                             break;
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         GXCommon.ShowError(this.ParentComponent, Gurux.DeviceSuite.Properties.Resources.GuruxDeviceSuiteTxt, ex);
     }
 }
Esempio n. 22
0
 /// <summary>
 /// Add new DC.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void NewDataCollectorMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         GXAmiUserGroup[] ugs = Client.GetUserGroups(false);
         GXAmiDataCollector dc = new GXAmiDataCollector();
         GXAmiDataCollectorForm dlg = new GXAmiDataCollectorForm(Client, dc, DataCollectorActionType.Add);
         if (dlg.ShowDialog(this.ParentComponent) == System.Windows.Forms.DialogResult.OK)
         {
             AddDataCollector(new GXAmiDataCollector[]{dc});
         }
     }
     catch (Exception ex)
     {
         GXCommon.ShowError(this.ParentComponent, Gurux.DeviceSuite.Properties.Resources.GuruxDeviceSuiteTxt, ex);
     }  
 }       
Esempio n. 23
0
 /// <summary>
 /// Search DC.
 /// </summary>
 void SearchDC()
 {
     try
     {
         DCSearchBtn.Enabled = false;
         object[] tmp = Client.Search(new string[] { DCSearchBtn.Text }, ActionTargets.DataCollector, SearchType.All);
         //Remove exists DCs.
         DCToListViewItem.Clear();
         DCList.Items.Clear();               
         GXAmiDataCollector[] dcs = new GXAmiDataCollector[tmp.Length];
         Array.Copy(tmp, dcs, tmp.Length);
         OnDataCollectorsAdded(null, dcs);
     }
     catch (Exception ex)
     {
         GXCommon.ShowError(this.ParentComponent, Gurux.DeviceSuite.Properties.Resources.GuruxDeviceSuiteTxt, ex);
     }
     DCSearchBtn.Enabled = true;
     DCSearchBtn.Focus();
 }
        /// <summary>
        /// Add new data collector.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GXDataCollectorUpdateResponse Put(GXDataCollectorUpdateRequest request)
        {
            GXAmiDataCollector[] collectors = request.Collectors;
            IAuthSession s = this.GetSession(false);
            long id;
            List<GXEventsItem> events = new List<GXEventsItem>();
            lock (Db)
            {
                string lastIP;
#if !SS4                
                lastIP = GuruxAMI.Server.AppHost.GetIPAddress(base.RequestContext);
#else
                lastIP = "";//TODO;
#endif                
                using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted))
                {
                    if (long.TryParse(s.Id, out id))
                    {
                        //Normal user can't change add new data collectors.
                        if (!GuruxAMI.Server.GXBasicAuthProvider.CanEditDevice(s))
                        {
                            throw new ArgumentException("Access denied.");
                        }
                        bool superAdmin = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s);
                        //If user want's to add new data collectors.
                        if (request.Collectors != null)
                        {
                            foreach (GXAmiDataCollector collector in request.Collectors)
                            {
                                if (collector.Id == 0)
                                {
                                    collector.Guid = Guid.NewGuid();
                                    collector.Added = DateTime.Now.ToUniversalTime();
                                    Db.Insert(collector);
#if !SS4
                                    collector.Id = (ulong)Db.GetLastInsertId();
#else
                                    collector.Id = (ulong)Db.LastInsertId();
#endif                                   
                                    events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, collector));
                                }
                                else
                                {
                                    //If DC is added to user group it's state is no longer unassigned.
                                    bool assigned = false;
                                    if (collector.UnAssigned && request.UserGroupIDs != null)
                                    {
                                        events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Remove, collector.Clone()));
                                        assigned = true;
                                        collector.UnAssigned = false;
                                    }                                    
                                    Db.UpdateOnly(collector, p => p.MAC, p => p.Id == collector.Id);
                                    Db.UpdateOnly(collector, p => p.UnAssigned, p => p.Id == collector.Id);
                                    Db.UpdateOnly(collector, p => p.Name, p => p.Id == collector.Id);
                                    Db.UpdateOnly(collector, p => p.Description, p => p.Id == collector.Id);
                                    //If DC is assigned remove it first and then add like assigned.
                                    if (assigned)
                                    {
                                        events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, collector));
                                    }
                                    else
                                    {
                                        events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Edit, collector));
                                    }
                                }
                                //If data collector is added to device group.
                                if (request.UserGroupIDs != null)
                                {
                                    foreach (long it in request.UserGroupIDs)
                                    {
                                        //Can user access user group.
                                        if (!superAdmin && !GXUserGroupService.CanAccess(Db, id, it))
                                        {
                                            throw new ArgumentException("Access denied.");
                                        }
                                        //Check that DC is not already added to the user group.
                                        List<GXAmiDataCollectorUserGroup> dcu = Db.Select<GXAmiDataCollectorUserGroup>(q => q.DataCollectorID == collector.Id && q.UserGroupID == it);
                                        if (dcu.Count == 0)
                                        {
                                            GXAmiDataCollectorUserGroup u = new GXAmiDataCollectorUserGroup();
                                            u.DataCollectorID = collector.Id;
                                            u.UserGroupID = it;
                                            Db.Insert(u);
#if !SS4
                                            GXAmiUserGroup ug = Db.QueryById<GXAmiUserGroup>(it);
#else
                                            GXAmiUserGroup ug = Db.SingleById<GXAmiUserGroup>(it);
#endif                                           
                                            events.Add(new GXEventsItem(ActionTargets.UserGroup, Actions.Edit, ug));
                                        }
                                    }
                                }
                            }
                        }
                        //User is adding collector by MAC address.
                        else if (request.MacAddress != null)
                        {
                            GXAmiDataCollector it = new GXAmiDataCollector();
                            collectors = new GXAmiDataCollector[] { it };
                            it.Guid = Guid.NewGuid();
                            s.UserAuthName = it.Guid.ToString();
                            it.Added = DateTime.Now.ToUniversalTime();
                            it.IP = lastIP;
                            it.UnAssigned = true;
                            if (request.MacAddress != null)
                            {
                                it.MAC = MacToString(request.MacAddress);
                            }
                            Db.Insert(it);
#if !SS4
                            it.Id = (ulong)Db.GetLastInsertId();
#else
                            it.Id = (ulong)Db.LastInsertId();
#endif                            
                            events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, it));
                        }
                        else
                        {
                            throw new ArgumentNullException("MAC Address.");
                        }
                    }
                    else
                    {
                        //DC is updating itself.
                        if (request.MacAddress == null)
                        {
                            Guid guid;
                            if (!GuruxAMI.Server.GXBasicAuthProvider.IsGuid(s.Id, out guid))
                            {
                                throw new ArgumentException("Access denied.");
                            }
                            List<GXAmiDataCollector> tmp = Db.Select<GXAmiDataCollector>(q => q.Guid == guid);
                            if (tmp.Count != 1)
                            {
                                throw new ArgumentException("Access denied.");
                            }
                            foreach (GXAmiDataCollector col in request.Collectors)
                            {
                                col.IP = lastIP;
                                Db.Update(col);
                                collectors = request.Collectors;
                                events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Edit, col));
                            }
                        }
                        else
                        {
                            List<GXAmiDataCollector> tmp = Db.Select<GXAmiDataCollector>(q => q.MAC == MacToString(request.MacAddress));
                            //If data collector is adding itself.
                            //Check if DC is already try to add itself.                    
                            if (tmp.Count == 0)
                            {
                                GXAmiDataCollector it = new GXAmiDataCollector();
                                collectors = new GXAmiDataCollector[] { it };
                                it.Guid = Guid.NewGuid();
                                s.UserAuthName = it.Guid.ToString();
                                it.Added = DateTime.Now.ToUniversalTime();
                                it.IP = lastIP;
                                it.UnAssigned = true;
                                if (request.MacAddress != null)
                                {
                                    it.MAC = MacToString(request.MacAddress);
                                }
                                Db.Insert(it);
#if !SS4
                                it.Id = (ulong)Db.GetLastInsertId();
#else
                                it.Id = (ulong)Db.LastInsertId();
#endif                                
                                events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, it));
                            }
                            else
                            {
                                collectors = new GXAmiDataCollector[] { tmp[0] };
                            }
                        }
                    }
                    //Accept changes.
                    trans.Commit();
                }
            }
            AppHost host = this.ResolveService<AppHost>();
            host.SetEvents(Db, this.Request, id, events);
            return new GXDataCollectorUpdateResponse(collectors);
        }
        /// <summary>
        /// Add new data collector.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GXDataCollectorUpdateResponse Put(GXDataCollectorUpdateRequest request)
        {
            GXAmiDataCollector[] collectors = request.Collectors;
            IAuthSession         s          = this.GetSession(false);
            long id;
            List <GXEventsItem> events = new List <GXEventsItem>();

            lock (Db)
            {
                string lastIP;
#if !SS4
                lastIP = GuruxAMI.Server.AppHost.GetIPAddress(base.RequestContext);
#else
                lastIP = "";//TODO;
#endif
                using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted))
                {
                    if (long.TryParse(s.Id, out id))
                    {
                        //Normal user can't change add new data collectors.
                        if (!GuruxAMI.Server.GXBasicAuthProvider.CanEditDevice(s))
                        {
                            throw new ArgumentException("Access denied.");
                        }
                        bool superAdmin = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s);
                        //If user want's to add new data collectors.
                        if (request.Collectors != null)
                        {
                            foreach (GXAmiDataCollector collector in request.Collectors)
                            {
                                if (collector.Id == 0)
                                {
                                    collector.Guid  = Guid.NewGuid();
                                    collector.Added = DateTime.Now.ToUniversalTime();
                                    Db.Insert(collector);
#if !SS4
                                    collector.Id = (ulong)Db.GetLastInsertId();
#else
                                    collector.Id = (ulong)Db.LastInsertId();
#endif
                                    events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, collector));
                                }
                                else
                                {
                                    //If DC is added to user group it's state is no longer unassigned.
                                    bool assigned = false;
                                    if (collector.UnAssigned && request.UserGroupIDs != null)
                                    {
                                        events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Remove, collector.Clone()));
                                        assigned             = true;
                                        collector.UnAssigned = false;
                                    }
                                    Db.UpdateOnly(collector, p => p.MAC, p => p.Id == collector.Id);
                                    Db.UpdateOnly(collector, p => p.UnAssigned, p => p.Id == collector.Id);
                                    Db.UpdateOnly(collector, p => p.Name, p => p.Id == collector.Id);
                                    Db.UpdateOnly(collector, p => p.Description, p => p.Id == collector.Id);
                                    //If DC is assigned remove it first and then add like assigned.
                                    if (assigned)
                                    {
                                        events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, collector));
                                    }
                                    else
                                    {
                                        events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Edit, collector));
                                    }
                                }
                                //If data collector is added to device group.
                                if (request.UserGroupIDs != null)
                                {
                                    foreach (long it in request.UserGroupIDs)
                                    {
                                        //Can user access user group.
                                        if (!superAdmin && !GXUserGroupService.CanAccess(Db, id, it))
                                        {
                                            throw new ArgumentException("Access denied.");
                                        }
                                        //Check that DC is not already added to the user group.
                                        List <GXAmiDataCollectorUserGroup> dcu = Db.Select <GXAmiDataCollectorUserGroup>(q => q.DataCollectorID == collector.Id && q.UserGroupID == it);
                                        if (dcu.Count == 0)
                                        {
                                            GXAmiDataCollectorUserGroup u = new GXAmiDataCollectorUserGroup();
                                            u.DataCollectorID = collector.Id;
                                            u.UserGroupID     = it;
                                            Db.Insert(u);
#if !SS4
                                            GXAmiUserGroup ug = Db.QueryById <GXAmiUserGroup>(it);
#else
                                            GXAmiUserGroup ug = Db.SingleById <GXAmiUserGroup>(it);
#endif
                                            events.Add(new GXEventsItem(ActionTargets.UserGroup, Actions.Edit, ug));
                                        }
                                    }
                                }
                            }
                        }
                        //User is adding collector by MAC address.
                        else if (request.MacAddress != null)
                        {
                            GXAmiDataCollector it = new GXAmiDataCollector();
                            collectors     = new GXAmiDataCollector[] { it };
                            it.Guid        = Guid.NewGuid();
                            s.UserAuthName = it.Guid.ToString();
                            it.Added       = DateTime.Now.ToUniversalTime();
                            it.IP          = lastIP;
                            it.UnAssigned  = true;
                            if (request.MacAddress != null)
                            {
                                it.MAC = MacToString(request.MacAddress);
                            }
                            Db.Insert(it);
#if !SS4
                            it.Id = (ulong)Db.GetLastInsertId();
#else
                            it.Id = (ulong)Db.LastInsertId();
#endif
                            events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, it));
                        }
                        else
                        {
                            throw new ArgumentNullException("MAC Address.");
                        }
                    }
                    else
                    {
                        //DC is updating itself.
                        if (request.MacAddress == null)
                        {
                            Guid guid;
                            if (!GuruxAMI.Server.GXBasicAuthProvider.IsGuid(s.Id, out guid))
                            {
                                throw new ArgumentException("Access denied.");
                            }
                            List <GXAmiDataCollector> tmp = Db.Select <GXAmiDataCollector>(q => q.Guid == guid);
                            if (tmp.Count != 1)
                            {
                                throw new ArgumentException("Access denied.");
                            }
                            foreach (GXAmiDataCollector col in request.Collectors)
                            {
                                col.IP = lastIP;
                                Db.Update(col);
                                collectors = request.Collectors;
                                events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Edit, col));
                            }
                        }
                        else
                        {
                            List <GXAmiDataCollector> tmp = Db.Select <GXAmiDataCollector>(q => q.MAC == MacToString(request.MacAddress));
                            //If data collector is adding itself.
                            //Check if DC is already try to add itself.
                            if (tmp.Count == 0)
                            {
                                GXAmiDataCollector it = new GXAmiDataCollector();
                                collectors     = new GXAmiDataCollector[] { it };
                                it.Guid        = Guid.NewGuid();
                                s.UserAuthName = it.Guid.ToString();
                                it.Added       = DateTime.Now.ToUniversalTime();
                                it.IP          = lastIP;
                                it.UnAssigned  = true;
                                if (request.MacAddress != null)
                                {
                                    it.MAC = MacToString(request.MacAddress);
                                }
                                Db.Insert(it);
#if !SS4
                                it.Id = (ulong)Db.GetLastInsertId();
#else
                                it.Id = (ulong)Db.LastInsertId();
#endif
                                events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.Add, it));
                            }
                            else
                            {
                                collectors = new GXAmiDataCollector[] { tmp[0] };
                            }
                        }
                    }
                    //Accept changes.
                    trans.Commit();
                }
            }
            AppHost host = this.ResolveService <AppHost>();
            host.SetEvents(Db, this.Request, id, events);
            return(new GXDataCollectorUpdateResponse(collectors));
        }
Esempio n. 26
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();
        }
Esempio n. 27
0
 /// <summary>
 /// Add new DC.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="collectors"></param>
 void OnDataCollectorsAdded(object sender, GXAmiDataCollector[] collectors)
 {
     try
     {
         List<ListViewItem> assigned = new List<ListViewItem>();
         List<ListViewItem> unAssigned = new List<ListViewItem>();
         foreach (GXAmiDataCollector it in collectors)
         {
             if (it.UnAssigned)
             {
                 ListViewItem node = new ListViewItem(new string[]{it.MAC, it.IP});
                 UnassignedDCToListViewItem.Add(it.Guid, node);
                 unAssigned.Add(node);
                 node.Tag = it;
             }
             else
             {
                 ListViewItem node = new ListViewItem(it.Name);
                 UpdateDCImage(node, it);
                 DCToListViewItem.Add(it.Guid, node);
                 assigned.Add(node);
                 node.Tag = it;
             }
         }
         if (assigned.Count != 0)
         {
             DCList.Items.AddRange(assigned.ToArray());
         }
         if (unAssigned.Count != 0)
         {
             UnassignedDCList.Items.AddRange(unAssigned.ToArray());
         }
     }
     catch (Exception ex)
     {
         GXCommon.ShowError(this.ParentComponent, Gurux.DeviceSuite.Properties.Resources.GuruxDeviceSuiteTxt, ex);
     }
 }
Esempio n. 28
0
 void UpdateDCImage(ListViewItem li, GXAmiDataCollector dc)
 {
     if (dc.State == DeviceStates.Connected)
     {
         li.ImageIndex = 5;
     }
     else
     {
         li.ImageIndex = 4;
     }
 }
Esempio n. 29
0
 void OnDataCollectorStateChanged(object sender, GXAmiDataCollector[] collectors)
 {
     foreach (GXAmiDataCollector it in collectors)
     {
         ListViewItem node = DCToListViewItem[it.Guid] as ListViewItem;
         if (node != null)
         {
             UpdateDCImage(node, it);
         }
     }
 }
Esempio n. 30
0
        public GuruxAMI.Common.Messages.GXEventsItem[] WaitEvents(IDbConnection Db, Guid listenerGuid, out Guid guid)
        {
            //Wait until event occurs.
            GXSession session;

            lock (Sessions)
            {
                session = GetSession(listenerGuid);
                //If session not found. This is happening when DC is connected to the server and
                //Server is restarted.
                if (session == null)
                {
                    guid = Guid.Empty;
                    return(new GuruxAMI.Common.Messages.GXEventsItem[0]);
                    //TODO: Check is this better. throw new System.Net.WebException("", System.Net.WebExceptionStatus.RequestCanceled);
                }
                session.Received.Set();
                //Update DC last request time stamp.
                foreach (GXEvent it in session.NotifyClients)
                {
                    if (it.DataCollectorGuid != Guid.Empty)
                    {
                        lock (Db)
                        {
                            GXAmiDataCollector item = Db.Select <GXAmiDataCollector>(q => q.Guid == it.DataCollectorGuid)[0];
                            item.LastRequestTimeStamp = DateTime.Now.ToUniversalTime();
                            Db.UpdateOnly(item, p => p.LastRequestTimeStamp, p => p.Guid == it.DataCollectorGuid);
                        }
                    }
                }

                //Search if there are new events that are occurred when client is executed previous action.
                bool found = false;
                foreach (GXEvent it in session.NotifyClients)
                {
                    if (it.Rows.Count != 0)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    Thread.Sleep(1);
                    session.Received.Reset();
                }
            }
            session.Received.WaitOne();
            lock (Sessions)
            {
                //Search occurred event.
                foreach (GXEvent it in session.NotifyClients)
                {
                    if (it.Rows.Count != 0)
                    {
                        guid = it.Instance;
                        GuruxAMI.Common.Messages.GXEventsItem[] rows = it.Rows.ToArray();
                        it.Rows.Clear();
                        return(rows);
                    }
                }
            }
            guid = Guid.Empty;
            return(new GuruxAMI.Common.Messages.GXEventsItem[0]);
        }
Esempio n. 31
0
        /// <summary>
        /// Start listen events.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GXEventsRegisterResponse Post(GXEventsRegisterRequest request)
        {
            if (request.SessionListener.Equals(Guid.Empty) ||
                request.Instance.Equals(Guid.Empty))
            {
                throw new Exception("Listener Guid is empty.");
            }
            if (request.Actions == Actions.None && request.Targets == ActionTargets.None)
            {
                return(new GXEventsRegisterResponse());
            }
            IAuthSession s          = this.GetSession(false);
            long         id         = 0;
            bool         superAdmin = false;
            Guid         guid       = request.DataCollectorGuid;

            //Guid is set if DC is retreaving new tasks.
            if (long.TryParse(s.Id, out id))
            {
                superAdmin = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s);
            }
            else
            {
                if (request.DataCollectorGuid.Equals(Guid.Empty))
                {
                    throw new Exception("Data collector Guid is empty.");
                }
            }
            AppHost host = this.ResolveService <AppHost>();
            //Check that there are no several DCs with same Guid.
            //Note! This might happend when DC is restarted wrong.
            //For this reason we are only give a warning.
            List <GXEventsItem> events = new List <GXEventsItem>();

            if (host.IsDCRegistered(guid))
            {
                lock (Db)
                {
                    GXAmiSystemError e = new GXAmiSystemError(1, ActionTargets.SystemError, Actions.State, new Exception("Data collector already exists."));
                    Db.Insert <GXAmiSystemError>(e);
                    events.Add(new GXEventsItem(ActionTargets.SystemError, Actions.Add, e));
                }
            }
            ulong   mask = (ulong)(((int)request.Targets << 16) | (int)request.Actions);
            GXEvent e1   = new GXEvent(id, superAdmin, guid, request.Instance, mask);

            host.AddEvent(request.SessionListener, e1);
            if (guid != Guid.Empty)
            {
                //Notify that DC is connected.
                lock (Db)
                {
                    GXAmiDataCollector dc = Db.Select <GXAmiDataCollector>(q => q.Guid == guid)[0];
                    dc.State = Gurux.Device.DeviceStates.Connected;
                    Db.UpdateOnly(dc, p => p.StatesAsInt, p => p.Id == dc.Id);
                    events.Add(new GXEventsItem(ActionTargets.DataCollector, Actions.State, dc));
                }
                host.SetEvents(Db, this.Request, 0, events);
            }
            return(new GXEventsRegisterResponse());
        }