コード例 #1
0
        /// <summary>
        /// Get showed device profiles.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceDlg_Load(object sender, EventArgs e)
        {
            if (Arguments.OnInitialize != null)
            {
                Arguments.OnInitialize(this, Arguments);
            }
            if (Arguments.DeviceProfiles.Count != 0)
            {
                ShowEarlierVersionsCB.Enabled = DownloadCB.Enabled = CustomCB.Enabled = false;
                if (Arguments.DeviceProfiles.Count == 0)
                {
                    throw new Exception(Gurux.Device.Properties.Resources.NoDevicesPublishedTxt);
                }
            }
            else
            {
                GXDeviceManufacturerCollection.Load(items);
                if (GXDeviceList.DeviceProfiles.Count == 0 && items.Count == 0)
                {
                    throw new Exception(Gurux.Device.Properties.Resources.NoDevicesPublishedTxt);
                }
            }
            if (!string.IsNullOrEmpty(Arguments.Settings))
            {
                try
                {
                    GXJsonParser parser = new GXJsonParser();
                    GXDeviceProfileFormSettings settings = parser.Deserialize<GXDeviceProfileFormSettings>(Arguments.Settings);
                    CustomCB.Checked = settings.Custom;
                    DownloadCB.Checked = settings.Download;
                    SearchTB.Text = settings.SearchText;
                    ShowEarlierVersionsCB.Checked = settings.Earlier;

                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    Arguments.Settings = null;
                }
            }
            ShowTemplates();
            if (DeviceProfiles.SelectedItems.Count == 0)
            {
                SearchTB.Select();
            }
        }
コード例 #2
0
        /// <summary>
        /// Load device list from xml file.
        /// </summary>
        /// <param name="path"></param>
        public void Load(string path)
        {
            try
            {
                NotifyLoadBegin();
                IsLoading = true;
                ++FreezeEvents;
                Clear();                
                GXDeviceList list;
                GXSite site;
                if (GXJsonParser.IsJSONFile(path))
                {
                    GXJsonParser parser = new GXJsonParser();
                    parser.OnCreateObject += new CreateObjectEventhandler(ParserOnCreateObject);
                    list = parser.LoadFile(path, typeof(GXDeviceList)) as GXDeviceList;
                    parser.OnCreateObject -= new CreateObjectEventhandler(ParserOnCreateObject);
                }
                else
                {
                    Type deviceType = null;                    
                    System.Collections.Generic.List<Type> types = new System.Collections.Generic.List<Type>();
                    if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                    {
                        foreach (GXProtocolAddIn it in GXDeviceList.Protocols.Values)
                        {
                            GetAddInInfo(it, out deviceType, types);
                        }
                    }
                    using (FileStream reader = new FileStream(path, FileMode.Open))
                    {
                        DataContractSerializer x = new DataContractSerializer(this.GetType(), types.ToArray());
                        list = (GXDeviceList)x.ReadObject(reader);
                        reader.Close();
                    }                       
                }
                list.m_sched = null;
                this.Name = list.Name;
                this.CustomUI = list.CustomUI;
                //Move items to other collection.
                this.DeviceGroups.AddRange(list.DeviceGroups);
                foreach (GXDeviceGroup it in this.DeviceGroups)
                {
                    it.Parent = this.DeviceGroups;
                }
                list.DeviceGroups.Clear();
                //Move items to other collection.
                this.Schedules.AddRange(list.Schedules);
                foreach (GXSchedule it in this.Schedules)
                {
                    it.Parent = this.Schedules;
                    site = it as GXSite;
                    site.NotifySerialized(false);
                }
                list.Schedules.Clear();
                this.DisabledActions = list.DisabledActions;

                NotifySerialized(false, this.DeviceGroups);                
                site = this as GXSite;
                site.NotifySerialized(false);
                foreach (GXSchedule schedule in this.Schedules)
                {
                    string[] items = null;
                    if (schedule.SerializedItems != null)
                    {
                        items = schedule.SerializedItems.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string it in items)
                        {
                            ulong id = ulong.Parse(it);
                            object target = FindItemByID(id);
                            schedule.Items.Add(target);
                        }
                    }
                    if (schedule.SerializedExcludedItems != null)
                    {
                        items = schedule.SerializedExcludedItems.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string it in items)
                        {
                            ulong id = ulong.Parse(it);
                            object target = FindItemByID(id);
                            schedule.ExcludedItems.Add(target);
                        }
                    }
                }
                //Find event listeners.
                foreach(GXDevice it in this.DeviceGroups.GetDevicesRecursive())
                {
                    IGXEventHandler handler;
                    if (!EventHandlers.ContainsKey(it.ProfileGuid))
                    {
                        handler = EventHandlers[it.ProfileGuid] = null;
                        foreach (Type type in it.GetType().Assembly.GetTypes())
                        {
                            if (typeof(IGXEventHandler).IsAssignableFrom(type))
                            {
                                handler = EventHandlers[it.ProfileGuid] = Activator.CreateInstance(type) as IGXEventHandler;
                                handler.Clients = this;
                                break;
                            }
                        }                        
                    }
                    else
                    {
                        handler = EventHandlers[it.ProfileGuid];
                    }
                    if (handler != null)
                    {
                        it.GXClient.AddEventHandler(handler, this);
                    }
                }
                this.FileName = path;                
                this.Dirty = false;
            }
            finally
            {
                IsLoading = false;
                --FreezeEvents;
                NotifyLoadEnd();
            }
        }
コード例 #3
0
 void ApplyChanges(GXDeviceProfile dp)
 {
     if (Device)
     {
         Arguments.Target = GXDevice.Create(dp.Protocol, dp.Name, "");
     }
     else
     {
         Arguments.Target = dp;
     }
     try
     {
         GXJsonParser parser = new GXJsonParser();
         GXDeviceProfileFormSettings settings = new GXDeviceProfileFormSettings();
         settings.Custom = CustomCB.Checked;
         settings.Download = DownloadCB.Checked;
         settings.SearchText = SearchTB.Text;
         settings.Earlier = ShowEarlierVersionsCB.Checked;
         Arguments.Settings = parser.Serialize(settings);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
     if (Arguments.OnSelect != null)
     {
         if (Arguments.UseThread)
         {
             DialogResult = DialogResult.None;
             Work = new GXAsyncWork(this, OnAsyncStateChange, OnSelect, null, "Selecting", null);
             Work.Start();
             return;
         }
         else
         {
             Arguments.OnSelect(Arguments.Target, Arguments);
         }
     }
     DialogResult = DialogResult.OK;
     Close();
 }
コード例 #4
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public GXWebService()
 {
     Parser  = new GXJsonParser();
     RestMap = new Hashtable();
 }
コード例 #5
0
ファイル: GXServer.cs プロジェクト: Gurux/Gurux.Service
        /// <summary>
        /// Parse query DTO and return response DTO as string.
        /// </summary>
        /// <param name="method">Http method.</param>
        /// <param name="path">Command to execute.</param>
        /// <param name="data">Command data.</param>
        /// <returns>DTO result as string.</returns>
        static string GetReply(Hashtable messageMap, IPrincipal user, GXServer server, string hostAddress, string method, string path, string data)
        {
            InvokeHandler    handler;
            string           command;
            GXRestMethodInfo mi;

            lock (messageMap)
            {
                mi = GXGeneral.GetTypes(messageMap, path, out command);
            }
            if (mi == null)
            {
                throw new HttpException(405, string.Format("Rest method '{0}' not implemented.", command));
            }
            switch (method.ToUpper())
            {
            case "GET":
                handler = mi.Get;
                break;

            case "POST":
                handler = mi.Post;
                break;

            case "PUT":
                handler = mi.Put;
                break;

            case "DELETE":
                handler = mi.Delete;
                break;

            default:
                handler = null;
                break;
            }
            if (handler == null)
            {
                throw new HttpException(405, string.Format("Method '{0}' not allowed for {1}", method, command));
            }
            object req = server.Parser.Deserialize("{" + data + "}", mi.RequestType);
            //Get Rest class from cache.
            GXRestService target = server.RestMap[mi.RestClassType] as GXRestService;

            if (target == null)
            {
                target = GXJsonParser.CreateInstance(mi.RestClassType) as GXRestService;
                server.RestMap[mi.RestClassType] = target;
            }
            target.Host            = server.Host;
            target.User            = user;
            target.Db              = server.Connection;
            target.UserHostAddress = hostAddress;
            object tmp = handler(target, req);

            if (tmp == null)
            {
                throw new HttpException(405, string.Format("Command '{0}' returned null.", command));
            }
            return(server.Parser.SerializeToHttp(tmp));
        }
コード例 #6
0
ファイル: GXServer.cs プロジェクト: Gurux/Gurux.Service
        /// <summary>
        /// Listen clients as long as server is up and running.
        /// </summary>
        /// <param name="parameter"></param>
        void ListenThread(object parameter)
        {
            IPrincipal          user;
            HttpListenerContext c        = null;
            GXServer            tmp      = parameter as GXServer;
            HttpListener        Listener = tmp.Listener;

            while (Listener.IsListening)
            {
                bool           accept = false;
                string         username, password;
                AutoResetEvent h      = new AutoResetEvent(false);
                IAsyncResult   result = Listener.BeginGetContext(delegate(IAsyncResult ListenerCallback)
                {
                    HttpListener listener = (HttpListener)ListenerCallback.AsyncState;
                    //If server is not closed.
                    if (listener.IsListening)
                    {
                        bool html = false;
                        try
                        {
                            c = listener.EndGetContext(ListenerCallback);
                        }
                        catch (Exception ex)
                        {
                            if (onError != null)
                            {
                                onError(this, new ErrorEventArgs(ex));
                            }
                            h.Set();
                            return;
                        }
                        if (c.Request.HttpMethod == "GET" && c.Request.AcceptTypes != null)
                        {
                            foreach (var it in c.Request.AcceptTypes)
                            {
                                if (it == "text/html")
                                {
                                    Thread thread = new Thread(new ParameterizedThreadStart(ShowServices));
                                    thread.Start(new object[] { tmp, c });
                                    html   = true;
                                    accept = true;
                                    break;
                                }
                                if (it.Contains("image"))
                                {
                                    html   = true;
                                    accept = true;
                                    break;
                                }
                            }
                        }
                        if (!html)
                        {
                            GXWebServiceModule.TryAuthenticate(tmp.MessageMap, c.Request, out username, out password);
                            //Anonymous access is allowed.
                            if (username == null && password == null)
                            {
                                accept = true;
                                user   = null;
                            }
                            else
                            {
                                user   = TryAuthenticate(username, password);
                                accept = user != null;
                            }

                            if (accept)
                            {
                                Thread thread = new Thread(new ParameterizedThreadStart(Process));
                                thread.Start(new object[] { tmp, c, user });
                            }
                            else
                            {
                                c.Response.StatusCode        = 401;
                                c.Response.StatusDescription = "Access Denied";
                                c.Response.AddHeader("WWW-Authenticate", "Basic Realm");
                                GXErrorWrapper err = new GXErrorWrapper(new HttpException(401, "Access Denied"));
                                using (TextWriter writer = new StreamWriter(c.Response.OutputStream, Encoding.ASCII))
                                {
                                    GXJsonParser parser        = new GXJsonParser();
                                    string data                = parser.Serialize(err);
                                    c.Response.ContentLength64 = data.Length;
                                    writer.Write(data);
                                }
                                c.Response.Close();
                            }
                        }
                        h.Set();
                    }
                }, Listener);
                EventWaitHandle.WaitAny(new EventWaitHandle[] { h, Closing });
                if (!accept || !Listener.IsListening)
                {
                    result.AsyncWaitHandle.WaitOne(1000);
                    Closed.Set();
                    break;
                }
            }
        }
コード例 #7
0
        public void ProcessRequest(HttpContext context)
        {
            InvokeHandler handler;

            if (context.Request.ContentType.Contains("json"))
            {
                switch (context.Request.HttpMethod)
                {
                case "GET":
                    handler = RestMethodInfo.Get;
                    break;

                case "POST":
                    handler = RestMethodInfo.Post;
                    break;

                case "PUT":
                    handler = RestMethodInfo.Put;
                    break;

                case "DELETE":
                    handler = RestMethodInfo.Delete;
                    break;

                default:
                    handler = null;
                    break;
                }
                if (handler == null)
                {
                    throw new HttpException(405, string.Format("Method '{0}' not allowed for {1}", context.Request.HttpMethod, RestMethodInfo.RequestType.Name));
                }
                object req;
                if (context.Request.HttpMethod == "POST")
                {
                    req = Parser.Deserialize(context.Request.InputStream, RestMethodInfo.RequestType);
                }
                else
                {
                    string data = "{" + context.Request.QueryString.ToString() + "}";
                    req = Parser.Deserialize(data, RestMethodInfo.RequestType);
                }
                //Get Rest class from cache.
                GXRestService target = RestMap[RestMethodInfo.RestClassType] as GXRestService;
                if (target == null)
                {
                    target = GXJsonParser.CreateInstance(RestMethodInfo.RestClassType) as GXRestService;
                    RestMap[RestMethodInfo.RestClassType] = target;
                }
                //Update user and DB info.

                //If proxy is used.
                string add = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                if (add == null)
                {
                    add = context.Request.UserHostAddress;
                }
                target.Host = Host;
                target.User = context.User;
                target.Db   = Connection;
                object tmp   = handler(target, req);
                string reply = Parser.Serialize(tmp);
                context.Response.Write(reply);
                context.Response.ContentType = "json";
            }
        }
コード例 #8
0
ファイル: GXDevice.cs プロジェクト: giapdangle/Gurux.Device
		/// <summary>
		/// Load device settings from the XML File.
		/// </summary>
		/// <param name="filePath">Path to the XML file.</param>
		static public GXDevice Load(string filePath)
		{
			if (!File.Exists(filePath))
			{
				System.Diagnostics.Debug.WriteLine(Resources.FailedToLoadFile + filePath);
				throw new FileNotFoundException(Resources.FailedToLoadFile + filePath);
			}
            GXDevice device = null;
            if (GXJsonParser.IsJSONFile(filePath))
            {
                GXJsonParser parser = new GXJsonParser();
                parser.OnCreateObject += new CreateObjectEventhandler(ParserOnCreateObject);
                device = parser.LoadFile(filePath, typeof(GXDevice)) as GXDevice;
                parser.OnCreateObject -= new CreateObjectEventhandler(ParserOnCreateObject);
                UpdateAttributes(device);
            }
            else
            {
                //If in old way.
                GXProtocolAddIn addIn;
                string protocolName = null, type = null;
                Guid deviceGuid;
                bool preset;
                GetProtocolInfo(filePath, out preset, out protocolName, out type, out deviceGuid);
                if (!GXDeviceList.Protocols.ContainsKey(protocolName))
                {
                    throw new Exception(Resources.InvalidProtocolAddIn + protocolName);
                }
                addIn = GXDeviceList.Protocols[protocolName];
                System.Collections.Generic.List<Type> types = new System.Collections.Generic.List<Type>();
                Type deviceType = null;
                GXDeviceList.GetAddInInfo(addIn, out deviceType, types);
                using (FileStream reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    DataContractSerializer x = new DataContractSerializer(deviceType, deviceType.Name, "", types.ToArray());
                    device = (GXDevice)x.ReadObject(reader);
                    //Update serializated target after load.
                    device.Keepalive.SerializedTarget = device.Keepalive.SerializedTarget;
                    reader.Close();
                }
                device.m_AddIn = addIn;
                UpdateAttributes(device);
                GXSite site = device as GXSite;
                site.NotifySerialized(false);
                foreach (GXCategory cat in device.Categories)
                {
                    foreach (GXProperty prop in cat.Properties)
                    {
                        site = prop as GXSite;
                        site.NotifySerialized(false);
                    }
                    site = cat as GXSite;
                    site.NotifySerialized(false);
                }
                foreach (GXTable table in device.Tables)
                {
                    foreach (GXProperty prop in table.Columns)
                    {
                        site = prop as GXSite;
                        site.NotifySerialized(false);
                    }
                    site = table as GXSite;
                    site.NotifySerialized(false);
                }                
            }
            return device;
		}