Beispiel #1
0
        /// <summary>
        /// Checks if server is available.
        /// </summary>
        /// <param name="WebServerToCheck"> Web server to check. </param>
        /// <returns>
        /// True - if there is a  connection.
        /// Otherwise it will return false
        /// </returns>
        public static bool CheckForInternetConnection(string WebServerToCheck)
        {
            // Get the url from server properties
            Uri Url = new Uri(WebServerToCheck);

            WebRequest  WebReq;
            WebResponse Response;

            // Make an empty request.
            WebReq = WebRequest.Create(Url);

            try
            {
                // Get the response.
                Response = WebReq.GetResponse();
                Response.Close();

                // Server is available.
                return(true);
            }
            catch
            {
                // Server is unavailable.
                return(false);
            }
            finally
            {
                WebReq   = null;
                Response = null;
                Url      = null;
            }
        }
Beispiel #2
0
        public static bool IsConnectedToInternet(Uri urlToCheck)
        {
            try
            {
                if (urlToCheck == null)
                {
                    urlToCheck = new System.Uri("http://www.microsoft.com");
                }


                System.Net.WebRequest  WebReq;
                System.Net.WebResponse Resp;
                WebReq = System.Net.WebRequest.Create(urlToCheck);

                try
                {
                    Resp = WebReq.GetResponse();
                    Resp.Close();
                    WebReq = null;
                    return(true);
                }

                catch
                {
                    WebReq = null;
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #3
0
        private void GetProjects()
        {
            var getParentIdjsonUrl =
                string.Format(
                    "{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=getprojects&startIndex=0&fetchSize=1&sortBy=sequence&sortOrder=ascend&action=1&solutionId=-1&filterOption=1",
                    _protocol, Params.SBMHostPort);

            var     getParentIdresponse    = WebReq.Make(getParentIdjsonUrl, ssoBase64: _ssoBase64, contentLength: 0);
            JObject getParentIdjObject     = JObject.Parse(getParentIdresponse);
            JToken  getParentIdprojectList = getParentIdjObject["projectList"];
            var     parentId = getParentIdprojectList.First["id"].Value <string>();

            var jsonUrl =
                string.Format(
                    "{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=getprojects&startIndex=0&fetchSize=99999&sortBy=sequence&sortOrder=ascend&searchString=&action=1&solutionId=-1&parentId={2}&projectId=-1",
                    _protocol, Params.SBMHostPort, parentId);

            var response = WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, contentLength: 0);

            JObject jObject     = JObject.Parse(response);
            JToken  projectList = jObject["projectList"];

            _objectExcahnge.Add("SBM.RolesPerProject", new Dictionary <string, SBMRolesPerProject>());
            foreach (var project in projectList)
            {
                var ids = new SBMRolesPerProject {
                    id = project["id"].Value <int>(), solutionId = project["solutionId"].Value <string>()
                };
                ((Dictionary <string, SBMRolesPerProject>)_objectExcahnge["SBM.RolesPerProject"]).Add(project["name"].Value <string>(), ids);
            }
        }
        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (progressBar1.Value < 100)
            {
                progressBar1.Value = progressBar1.Value + 2;
            }
            if (progressBar1.Value == 100)
            {
                Principal frmPrincipal = new Principal();
                frmPrincipal.Show(); // abre o form principal
                timer1.Stop();       // para o relógio
                this.Hide();         //fecha a janela após completar os 100%
            }

            if (progressBar1.Value == 10)
            {
                System.Uri             Url = new System.Uri("http://www.google.com"); //é sempre bom por um site que costuma estar sempre on para testar a conexão
                System.Net.WebRequest  WebReq;
                System.Net.WebResponse Resp;
                WebReq = System.Net.WebRequest.Create(Url);

                try
                {
                    Resp = WebReq.GetResponse();
                    Resp.Close();
                    WebReq = null;
                }
                catch
                {
                    timer1.Stop();  // para o relógio em caso de erro
                    MessageBox.Show("Não existe conexão com a internet.");
                    this.Dispose(); // encerra o sistema
                }
            }
        }
Beispiel #5
0
        public static bool IsConnected()
        {
            bool fail;

            System.Uri Url = new System.Uri("http://www.google.com"); //é sempre bom por um site que costuma estar sempre on, para n haver problemas

            System.Net.WebRequest WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                fail = true; //consegue conexão à internet
                return fail;
            }

            catch
            {
                WebReq = null;
                fail = false; //falhou a conexão à internet
                return fail;
            }
        }
        public static int IsConnected()
        {
            int fail;

            System.Uri Url = new System.Uri("http://www.microsoft.com"); //é sempre bom por um site que costuma estar sempre on, para n haver problemas

            System.Net.WebRequest  WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                fail   = 0; //consegue conexão à internet
                return(fail);
            }

            catch
            {
                MessageBox.Show("Não existe nenhuma ligação à internet.\n\nLiga-te à internet e tenta de novo.", "Erro de ligação!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                WebReq = null;
                fail   = 1; //falhou a conexão à internet
                return(fail);
            }
        }
Beispiel #7
0
        public static bool IsConnected()
        {
            bool fail;

            System.Uri Url = new System.Uri("http://www.microsoft.com"); //é sempre bom por um site que costuma estar sempre on, para n haver problemas

            System.Net.WebRequest  WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                fail   = true; //consegue conexão à internet
                return(fail);
            }

            catch
            {
                MessageBox.Show("Você não está conectado a internet!", "Atenção", MessageBoxButtons.OK);
                WebReq = null;
                fail   = false; //falhou a conexão à internet
                return(fail);
            }
        }
Beispiel #8
0
        public void SetGroup(string grpName)
        {
            GetAll();

            if (((Dictionary <string, int>)_objectExcahnge["SBM.Groups"]).ContainsKey(grpName))
            {
                Log.Warn("Group: '" + grpName + "' already exists.");
            }
            else
            {
                Log.Info("Creating group: " + grpName);

                var jsonStruct = new SBMSetGroup[1];
                jsonStruct[0] = new SBMSetGroup(grpName);

                var data    = JsonConvert.SerializeObject(jsonStruct);
                var jsonUrl = string.Format("{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=updategroupgeneral&action=1&count=1&checkForConcurrency=0",
                                            _protocol, Params.SBMHostPort);

                WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, data: data);

                _objectExcahnge.Remove("SBM.Groups");
                GetGroups();
            }
        }
        public static bool checkConectionOk()
        {
            bool conection_ok = false;

            System.Uri Url = new System.Uri("http://www.microsoft.com"); //é sempre bom por um site que costuma estar sempre on, para n haver problemas

            System.Net.WebRequest  WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq       = null;
                conection_ok = true;
            }
            catch
            {
                WebReq       = null;
                conection_ok = false;
            }

            Console.WriteLine(conection_ok);

            return(conection_ok);
        }
Beispiel #10
0
        private void SetRolesHelper(Dictionary <string, int> inputRoles, byte userOrGroup, int userOrGroupId, SBMRolesPerProject project, string proj)
        {
            var jsonUrl = string.Format("{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=updatesecuritycontrols&timestamp=-1", _protocol, Params.SBMHostPort);

            //get roles ids and grants to lists
            var permissionIds = new List <int>();
            var grantList     = new List <int>();
            //set all roles for group/user
            int firstRoleGranted;

            if (inputRoles.Count == 1 && inputRoles.TryGetValue("*", out firstRoleGranted))
            {
                foreach (var role in project.Roles)
                {
                    UpdatePermissionsGrantLists(role.Value, firstRoleGranted, role.Key, proj, ref permissionIds, ref grantList);
                }
            }
            else
            {
                foreach (var role in inputRoles)
                {
                    int tmpRole;
                    if (project.Roles.TryGetValue(role.Key, out tmpRole))
                    {
                        UpdatePermissionsGrantLists(tmpRole, role.Value, role.Key, proj, ref permissionIds, ref grantList);
                    }
                    else
                    {
                        Log.Warn(string.Format("Role '{0}' not found for project '{1}'", role.Key, proj));
                    }
                }
            }
            //prepare json struct
            int count = permissionIds.Count;

            if (count > 0)
            {
                var jsonStruct = new SBMSetRole[count];
                for (int i = 0; i < count; i++)
                {
                    jsonStruct[i] = new SBMSetRole(project.id, userOrGroupId, userOrGroup)
                    {
                        permissionId = permissionIds[i], granted = grantList[i]
                    }
                }
                ;

                var data = JsonConvert.SerializeObject(jsonStruct);
                WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, data: data);
            }
            else
            {
                Log.Warn(string.Format("No following roles found for '" + proj + "': "));
                foreach (var inputRole in inputRoles)
                {
                    Log.Warn(" - " + inputRole.Key);
                }
            }
        }
Beispiel #11
0
        private void Login()
        {
            string postPassword;

            postPassword = "******" + login + "&ppass=" + pass;

            webReq = new WebReq(sURL, getPost.post, connect, silentLogin, postPassword);
        }
Beispiel #12
0
        public async Task <JsonResult> GetById(string id)
        {
            WebReq req      = new WebReq();
            string response = await req.InfoById(id);

            CoinInformation ci = JsonConvert.DeserializeObject <CoinInformation>(response);

            ci.Description = Regex.Replace(ci.Description, @"\t|\n|\r", "");
            return(Json(ci));
        }
Beispiel #13
0
 /// <summary>
 /// Specifies the payload to use with the request. Automatically overrides the ContentSize property.
 /// </summary>
 /// <param name="payload">The payload value.</param>
 /// <param name="requestEncoding">The value to encode the payload.</param>
 /// <returns>Itself.</returns>
 public Http SetPayload(string payload, Encoding requestEncoding)
 {
     byte[] data = !string.IsNullOrEmpty(payload) ? requestEncoding.GetBytes(payload) : requestEncoding.GetBytes(String.Empty);
     WebReq.ContentLength = data.Length;
     if (WebReq.ContentLength > 0)
     {
         using (var dataStream = WebReq.GetRequestStream())
             dataStream.Write(data, 0, data.Length);
     }
     return(this);
 }
Beispiel #14
0
        private void button1_Click(object sender, EventArgs e)
        {
            CharacterNode node;
            string fileName;
            node = new CharacterNode(1, "test");
            Console.WriteLine(node.Details());

            fileName = makeURL(tbPageName.Text);
            fileName = string.Format(@"d:\temp\{0}.txt", fileName);

            for (int i = 1; i <= 5; i++)
            {
                webReq = new WebReq(string.Format("{0}{1}/page_{2}", sURL, tbPageName.Text, i), getPost.get, connect, false);
                webReq.doParse(fileName);

            }
        }
Beispiel #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            CharacterNode node;
            string        fileName;

            node = new CharacterNode(1, "test");
            Console.WriteLine(node.Details());

            fileName = makeURL(tbPageName.Text);
            fileName = string.Format(@"d:\temp\{0}.txt", fileName);

            for (int i = 1; i <= 5; i++)
            {
                webReq = new WebReq(string.Format("{0}{1}/page_{2}", sURL, tbPageName.Text, i), getPost.get, connect, false);
                webReq.doParse(fileName);
            }
        }
Beispiel #16
0
        private void GetGroups()
        {
            var jsonUrl =
                string.Format(
                    "{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=getgroups&showDeleted=0&onlyManaged=1&startIndex=0&fetchSize=99999&sortBy=name&sortOrder=ascend&searchString=",
                    _protocol, Params.SBMHostPort);

            var response = WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, contentLength: 0);

            JObject jObject   = JObject.Parse(response);
            JToken  groupList = jObject["groupList"];

            _objectExcahnge.Add("SBM.Groups", new Dictionary <string, int>());
            foreach (var group in groupList)
            {
                ((Dictionary <string, int>)_objectExcahnge["SBM.Groups"]).Add(group["name"].Value <string>(), group["id"].Value <int>());
            }
        }
Beispiel #17
0
        private void GetUsers()
        {
            var jsonUrl =
                string.Format(
                    "{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=getusers&showDeleted=0&showExternal=0&showLimited=0&onlyManaged=1&startIndex=0&fetchSize=99999&sortBy=loginId&sortOrder=ascend&searchString=",
                    _protocol, Params.SBMHostPort);

            var response = WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, contentLength: 0);

            JObject jObject  = JObject.Parse(response);
            JToken  userList = jObject["userList"];

            _objectExcahnge.Add("SBM.Users", new Dictionary <string, int>());
            foreach (var user in userList)
            {
                ((Dictionary <string, int>)_objectExcahnge["SBM.Users"]).Add(user["loginId"].Value <string>(), user["id"].Value <int>());
            }
        }
Beispiel #18
0
        /// <summary>
        /// Verifica se existe conexão com a internet através do site www.google.com.br
        /// </summary>
        /// <returns>True - existe conexão | False - não há conexão</returns>
        public static bool IsConnected()
        {
            Uri Url = new Uri("http://www.google.com.br");             //é sempre bom por um site que costuma estar sempre on, para não haver problemas

            System.Net.WebRequest  WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                return(WebReq.Equals(null));
            }
            catch
            {
                return(false);
            }
        }
Beispiel #19
0
 public bool IsConnected()
 {
     System.Uri             Url = new System.Uri("http://www.google.com");
     System.Net.WebRequest  WebReq;
     System.Net.WebResponse Resp;
     WebReq = System.Net.WebRequest.Create(Url);
     try
     {
         Resp = WebReq.GetResponse();
         Resp.Close();
         WebReq = null;
         return(true);
     }
     catch
     {
         WebReq = null;
         return(false);
     }
 }
Beispiel #20
0
        public void SetMembershipForUser(string inputUserLogin, string[] inputGroups)
        {
            GetAll();
            int userId;

            if (((Dictionary <string, int>)_objectExcahnge["SBM.Users"]).TryGetValue(inputUserLogin, out userId))
            {
                var jsonUrl = string.Format(
                    "{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=updatememberships&timestamp=-1&checkForConcurrency=0&subjectType=1", _protocol, Params.SBMHostPort);
                var groupIDs = new List <int>();
                foreach (var groupName in inputGroups)
                {
                    int tmpGroupId;
                    if (((Dictionary <string, int>)_objectExcahnge["SBM.Groups"]).TryGetValue(groupName, out tmpGroupId))
                    {
                        groupIDs.Add(tmpGroupId);
                        Log.Info(string.Format("Setting '" + groupName + "' membership for " + inputUserLogin));
                    }
                }
                int count = groupIDs.Count;
                if (count > 0)
                {
                    var jsonStruct = new SetMembership[count];
                    for (int i = 0; i < count; i++)
                    {
                        jsonStruct[i] = new SetMembership(groupIDs[i], userId);
                    }

                    var data = JsonConvert.SerializeObject(jsonStruct);
                    WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, data: data);
                }
                else
                {
                    Log.Warn(string.Format("No group membership to be set for '" + inputUserLogin + "'"));
                }
            }
            else
            {
                Log.Warn(string.Format("User '" + inputUserLogin + "' doesn't exist."));
            }
        }
Beispiel #21
0
        public async Task <ObjectResult> FullInformation(string id)
        {
            WebReq   req = new WebReq();
            UserList dBUserItemsDBFind = JsonConvert.DeserializeObject <UserList>(System.IO.File.ReadAllText(path));
            Commands comm = new Commands();

            comm.DBCheck(comm, dBUserItemsDBFind, id);
            if (comm.Exist == false)
            {
                Response.StatusCode = 404;
                return(new ObjectResult(null));
            }
            if (dBUserItemsDBFind == null)
            {
                Response.StatusCode = 404;
            }
            string real = dBUserItemsDBFind.users[comm.Index].Real;
            //List<string> cryptos = new List<string>();
            UserShow userShow = await req.GetTickers(dBUserItemsDBFind, comm.Index, real);

            return(new ObjectResult(userShow.Ticker));
        }
Beispiel #22
0
        /// <summary>
        /// Herhangi bir Url'lin canlı olup olmadığını verilen timeout ile kontrol eder.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="_TimeOut"></param>
        /// <returns></returns>
        public static bool Varmi_Baglanti(string url, int _TimeOut = 1000)
        {
            try
            {
                System.Uri Url = new System.Uri(url);

                System.Net.WebRequest  WebReq;
                System.Net.WebResponse Resp;
                WebReq = System.Net.WebRequest.Create(Url);

                WebReq.Timeout = _TimeOut;

                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                return(true);
            }

            catch
            {
                return(false);
            }
        }
Beispiel #23
0
        public void SetUser(string inputUserLogin, string inputUserName, string inputUserPwd, string email, string emailCc)
        {
            GetAll();

            int    action;
            string data;
            var    dateFormatted = (String.Format("{0:MM/dd/yyyy}", DateTime.Now)).Replace('.', '/');

            if (((Dictionary <string, int>)_objectExcahnge["SBM.Users"]).ContainsKey(inputUserLogin))
            {
                action = 2; //for at least update
                Log.Info("Modifying user: "******"SBM.Users"])[inputUserLogin]));
            }
            else
            {
                action = 1; //for creation
                Log.Info("Creating user: "******"SBM.Users");
            }

            var jsonUrl =
                string.Format(
                    "{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=updateusergeneral&action={2}&timestamp=-1&passWasChanged=1&checkForConcurrency=0", _protocol,
                    Params.SBMHostPort, action);

            WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, data: data);

            if (action == 1)
            {
                GetUsers();
            }
        }
Beispiel #24
0
        private void GetRoles()
        {
            var projects = (Dictionary <string, SBMRolesPerProject>)_objectExcahnge["SBM.RolesPerProject"];

            foreach (var sbmProject in projects)
            {
                var projectId  = sbmProject.Value.id;
                var solutionId = sbmProject.Value.solutionId;

                var jsonUrl =
                    string.Format(
                        "{0}://{1}/tmtrack/tmtrack.dll?JSONPage&command=getapplicationroles&startIndex=0&fetchSize=99999&sortBy=NAME&sortOrder=ascending&applicationId={2}&projectId={3}",
                        _protocol, Params.SBMHostPort, solutionId, projectId);
                var response = WebReq.Make(jsonUrl, ssoBase64: _ssoBase64, contentLength: 0);

                JObject  jObject = JObject.Parse(response);
                JToken[] roles   = jObject["applicationRoles"]["roles"].ToArray();

                foreach (var role in roles)
                {
                    sbmProject.Value.Roles.Add(role["roleName"].Value <string>(), role["id"].Value <int>());
                }
            }
        }
Beispiel #25
0
        public static void GetSensorBathRoom(out double temperature, out int luminiscence, out int humidity, out bool movement)
        {
            HttpWebRequest  WebReq;
            HttpWebResponse WebResp;

            Debug.GC(true);

            temperature  = 0;
            luminiscence = 0;
            humidity     = 0;
            movement     = false;
            try
            {
                var request = System.Net.WebRequest.Create("http://192.168.2.25:8083/ZAutomation/api/v1/devices/") as System.Net.HttpWebRequest;
                request.KeepAlive = true;

                request.Method = "PUT";

                request.ContentType = "application/json";
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("{\"id\":\"ZWayVDev_20:0:49:1\",\"deviceType\":\"probe\",\"metrics\":{\"probeTitle\":\"Temperature\",\"scaleTitle\":\"°C\",\"level\":7.599999904632568,\"title\":\"Temperature Sensor\",\"iconBase\":\"zwave\"},\"tags\":[],\"location\":null,\"updateTime\":1387882443}");
                request.ContentLength = byteArray.Length;
                using (var writer = request.GetRequestStream()) { writer.Write(byteArray, 0, byteArray.Length); }

                string responseContent = null;
                using (var response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                    }
                }

                WebReq                  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZAutomation/api/v1/devices/ZWayVDev_zway_5-0-48-1/command/update");
                WebReq.KeepAlive        = true;
                WebReq.Method           = "GET";
                WebReq.Timeout          = 1000;
                WebReq.ReadWriteTimeout = 1000;
                WebResp                 = (HttpWebResponse)WebReq.GetResponse();
                WebResp.Close();
                WebReq  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZAutomation/api/v1/devices/ZWayVDev_zway_5-0-49-1/command/update");
                WebResp = (HttpWebResponse)WebReq.GetResponse();
                WebResp.Close();
                WebReq  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZAutomation/api/v1/devices/ZWayVDev_zway_5-0-49-3/command/update");
                WebResp = (HttpWebResponse)WebReq.GetResponse();
                WebResp.Close();
                WebReq  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZAutomation/api/v1/devices/ZWayVDev_zway_5-0-49-5/command/update");
                WebResp = (HttpWebResponse)WebReq.GetResponse();
                WebResp.Close();

                WebReq  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZWaveAPI/Run/devices[5].instances[0].commandClasses[0x31].data[0x01].val.value");
                WebResp = (HttpWebResponse)WebReq.GetResponse();
                using (var reader = new StreamReader(WebResp.GetResponseStream()))
                {
                    double result2 = double.Parse(reader.ReadToEnd().ToString()) * 10;
                    int    result1 = (int)result2;
                    double result  = (double)result1 / 10;
                    Logging.LogMessageToFile("Main - Temperature = [" + result.ToString() + "]", "SENSOR");
                    temperature = result;
                    reader.Close();
                }
                WebResp.Close();
                WebReq  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZWaveAPI/Run/devices[5].instances[0].commandClasses[0x31].data[0x03].val.value");
                WebResp = (HttpWebResponse)WebReq.GetResponse();
                using (var reader = new StreamReader(WebResp.GetResponseStream()))
                {
                    int result = Int32.Parse(reader.ReadToEnd().ToString()); // do something fun...
                    Logging.LogMessageToFile("Main - Luminiscence = [" + result.ToString() + "]", "SENSOR");
                    luminiscence = result;
                    reader.Close();
                }
                WebResp.Close();
                WebReq  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZWaveAPI/Run/devices[5].instances[0].commandClasses[0x31].data[0x05].val.value");
                WebResp = (HttpWebResponse)WebReq.GetResponse();
                using (var reader = new StreamReader(WebResp.GetResponseStream()))
                {
                    int result = Int32.Parse(reader.ReadToEnd().ToString()); // do something fun...
                    Logging.LogMessageToFile("Main - Humidity = [" + result.ToString() + "]", "SENSOR");
                    humidity = result;
                    reader.Close();
                }
                WebResp.Close();

                WebReq  = (HttpWebRequest)WebRequest.Create("http://192.168.2.25:8083/ZWaveAPI/Run/devices[5].instances[0].commandClasses[0x30].data[1].level.value");
                WebResp = (HttpWebResponse)WebReq.GetResponse();
                using (var reader = new StreamReader(WebResp.GetResponseStream()))
                {
                    if (reader.ReadToEnd().ToString().ToUpper() == "FALSE")
                    {
                        Logging.LogMessageToFile("Main - Movement = [FALSE]", "SENSOR");
                        movement = false;
                    }
                    else
                    {
                        Logging.LogMessageToFile("Main - Movement = [TRUE]", "SENSOR");
                        movement = true;
                    }
                    reader.Close();
                }
                WebResp.Close();
                Debug.Print(DateTime.Now + "," + temperature.ToString().Substring(0, 4) + "," + humidity.ToString() + "," + luminiscence.ToString() + "," + movement.ToString());
            }
            catch (Exception e)
            {
                Debug.Print("*********" + e.Message);
            }
        }
Beispiel #26
0
        private void GetToken(string oeHost, string oePort, string username, string password, bool isHttps)
        {
            string requestData;

            using (Stream stream = GetType().Assembly.GetManifestResourceStream("userScript.SSO.ssoTokenRequest.xml"))
            {
                using (var sr = new StreamReader(stream))
                {
                    requestData = sr.ReadToEnd();
                }
            }

            requestData = requestData.Replace("{{Username}}", username).Replace("{{Password}}", password);
            string url = string.Format("http{0}://{1}:{2}/{3}", isHttps ? "s" : string.Empty, oeHost, oePort, Endpoint);

            var response = WebReq.Make(url, contentType: ContentType, data: requestData);

            if (string.IsNullOrEmpty(response))
            {
                throw new Exception("There were no response from SBM at all.");
            }

            //convert value to XML
            var xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.LoadXml(response);
            }
            catch (Exception)
            {
                throw new Exception("Not proper XML response recieved from SBM: \n" + response);
            }

            //we need to add namespace in order to be able to look for saml: nodes
            var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);

            nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
            nsmgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");
            //get node with required for SSO
            var fault = xmlDoc.SelectSingleNode("//soapenv:Fault", nsmgr);

            if (fault != null)
            {
                var explanation = fault.SelectSingleNode("//Explanation");
                if (explanation == null)
                {
                    throw new Exception("Failed to obtain SSO Token, no explanation has been provided in response.");
                }
                throw new Exception(explanation.InnerText);
            }

            var tokenShort = xmlDoc.SelectSingleNode("//saml:Assertion", nsmgr);

            _ssoTokenXMLNode = xmlDoc.SelectSingleNode("//soapenv:Envelope", nsmgr);
            if (tokenShort == null || _ssoTokenXMLNode == null)
            {
                throw new Exception("SSO: Failed to find nodes in response '//saml:Assertion' or '//soapenv:Envelope'");
            }

            _ssoTokenXmlString = _ssoTokenXMLNode.OuterXml;
            _ssoTokenDecoded   = tokenShort.OuterXml;
            var bytes = Encoding.UTF8.GetBytes(_ssoTokenDecoded);

            _ssoTokenBase64 = Convert.ToBase64String(bytes);
        }
Beispiel #27
0
        private void Login()
        {
            string postPassword;
            postPassword = "******" + login + "&ppass=" + pass;

            webReq = new WebReq(sURL, getPost.post, connect, silentLogin, postPassword);
        }
Beispiel #28
0
 /// <summary>
 /// Specifies the range header.
 /// </summary>
 /// <param name="from">The start range value.</param>
 /// <param name="to">The end range value.</param>
 /// <returns>Itself.</returns>
 public Http SetRange(int from, int to)
 {
     WebReq.AddRange(from, to);
     return(this);
 }
Beispiel #29
0
 /// <summary>
 /// Specifies the range header.
 /// </summary>
 /// <param name="range">The header value.</param>
 /// <returns>Itself.</returns>
 public Http SetRange(int range)
 {
     WebReq.AddRange(range);
     return(this);
 }
Beispiel #30
0
        public async Task <ObjectResult> UserEdit([FromBody] UserCurrencyToChange item, string ids)
        {
            WebReq   req = new WebReq();
            UserList dBUserItemsDBFind = JsonConvert.DeserializeObject <UserList>(System.IO.File.ReadAllText(path));
            Commands comm = new Commands();

            comm.DBCheck(comm, dBUserItemsDBFind, ids);
            if (comm.Exist == false)
            {
                Response.StatusCode = 404;
                return(new ObjectResult(null));
            }
            if (dBUserItemsDBFind == null)
            {
                Response.StatusCode = 404;
            }
            //bool cont = false;
            //int comm.Index = 0;
            //for (int i = 0; i < dBUserItemsDBFind.users.Count; i++)
            //{
            //    if (dBUserItemsDBFind.users[i].Id == ids)
            //    {
            //        comm = i;
            //        cont = true;
            //        break;
            //    }
            //}
            //if (cont == false)
            //{
            //    Response.StatusCode = 404;
            //    return new ObjectResult(null);
            //}
            //if(item.real != null)
            //{
            //    item.real = comm.InputCheckReal(item.real);
            //}
            //if (item.crypto != null)
            //{
            //    item.crypto = comm.InputCheckCrypto(item.crypto);
            //}
            //if (item.crypto_to_change != null)
            //{
            //    item.crypto_to_change = comm.InputCheckCrypto(item.crypto_to_change);
            //}
            client = new CoinpaprikaAPI.Client();
            var coins = await client.GetCoinsAsync();

            string s  = JsonConvert.SerializeObject(coins);
            Value  st = JsonConvert.DeserializeObject <Value>(s);
            Dictionary <string, string> names = new Dictionary <string, string>();
            int lenght = st.value.Count;

            for (int i = 0; i < lenght; i++)
            {
                st.value[i].Name = st.value[i].Name.ToLower();
                names.Add(st.value[i].Id, st.value[i].Name);
            }
            string temp  = names.FirstOrDefault(x => x.Value == item.crypto_to_change).Key;
            string temp2 = names.FirstOrDefault(x => x.Value == item.crypto).Key;

            if (temp != null)
            {
                temp = temp.ToLower();
            }
            if (temp2 != null)
            {
                temp2 = temp2.ToLower();
            }
            item.crypto = temp;
            if (item.real != null)
            {
                item.real = item.real.ToLower();
            }
            string item2  = item.real;
            var    status = await req.RealCheck(item2);

            if (status == HttpStatusCode.BadRequest)
            {
                Response.StatusCode = 400;
                return(new ObjectResult(null));
            }
            if (item2 != null)
            {
                string[]      cur  = dBUserItemsDBFind.users[comm.Index].Real.Split(new char[] { ',' });
                List <string> list = new List <string>(cur);
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i] == item2)
                    {
                        Response.StatusCode = 409;
                        return(new ObjectResult(null));
                    }
                }
                list.Add(item2);
                string output = string.Join(",", list);
                dBUserItemsDBFind.users[comm.Index].Real = output;
                await System.IO.File.WriteAllTextAsync(path, JsonConvert.SerializeObject(dBUserItemsDBFind, Formatting.Indented));

                if (temp == null || temp2 == null)
                {
                    return(new ObjectResult(null));
                }
            }
            if (temp != null && temp2 != null)
            {
                for (int i = 0; i < dBUserItemsDBFind.users[comm.Index].Currency.Count; i++)
                {
                    if (dBUserItemsDBFind.users[comm.Index].Currency[i].Crypto == temp)
                    {
                        if (temp == temp2)
                        {
                            Response.StatusCode = 409;
                            return(new ObjectResult(null));
                        }
                        for (int j = 0; j < dBUserItemsDBFind.users[comm.Index].Currency.Count; j++)
                        {
                            if (temp2 == dBUserItemsDBFind.users[comm.Index].Currency[j].Crypto)
                            {
                                Response.StatusCode = 409;
                                return(new ObjectResult(null));
                            }
                        }
                        if (temp != temp2)
                        {
                            dBUserItemsDBFind.users[comm.Index].Currency[i].Crypto = temp2;
                            await System.IO.File.WriteAllTextAsync(path, JsonConvert.SerializeObject(dBUserItemsDBFind, Formatting.Indented));

                            return(new ObjectResult(null));
                        }
                    }
                }
                Response.StatusCode = 404;
                return(new ObjectResult(null));
            }
            else
            {
                Response.StatusCode = 404;
                return(new ObjectResult(null));
            }
        }
Beispiel #31
0
        public async Task <ObjectResult> Information(string id, string cryptoname)
        {
            WebReq   req = new WebReq();
            UserList dBUserItemsDBFind = JsonConvert.DeserializeObject <UserList>(System.IO.File.ReadAllText(path));
            Commands comm = new Commands();

            comm.DBCheck(comm, dBUserItemsDBFind, id);
            if (comm.Exist == false)
            {
                Response.StatusCode = 404;
                return(new ObjectResult(null));
            }
            if (dBUserItemsDBFind == null)
            {
                Response.StatusCode = 404;
            }
            client = new CoinpaprikaAPI.Client();
            var coins = await client.GetCoinsAsync();

            string s  = JsonConvert.SerializeObject(coins);
            Value  st = JsonConvert.DeserializeObject <Value>(s);
            Dictionary <string, string> names = new Dictionary <string, string>();
            int lenght = st.value.Count;

            for (int i = 0; i < lenght; i++)
            {
                st.value[i].Name = st.value[i].Name.ToLower();
                names.Add(st.value[i].Id, st.value[i].Name);
            }
            string temp2 = names.FirstOrDefault(x => x.Value == cryptoname).Key;

            if (temp2 == null)
            {
                Response.StatusCode = 404;
                return(new ObjectResult(null));
            }
            string        real     = dBUserItemsDBFind.users[comm.Index].Real;
            List <string> cryptos  = new List <string>();
            UserShow      userShow = await req.GetTickers(dBUserItemsDBFind, comm.Index, real);

            int  cryind = 0;
            bool exist  = false;

            for (int i = 0; i < userShow.Ticker.Count; i++)
            {
                string t = userShow.Ticker[i].Name.ToLower();
                if (t == cryptoname)
                {
                    cryind = i;
                    exist  = true;
                }
            }
            if (exist == true)
            {
                return(new ObjectResult(userShow.Ticker[cryind]));
            }
            else
            {
                Response.StatusCode = 404;
                return(new ObjectResult(null));
            }
        }
Beispiel #32
0
        protected Result Get(Operation oper)
        {
            var url  = oper.Require <string>("url");
            var port = (int)oper.Optional <long>("port", 80);

            var req = new WebReq(url, port);

            // Data buffer for incoming data.
            byte[] bytes        = new byte[1024];
            string response     = null;
            var    utcTimeStamp = DateTime.MinValue;
            int    clientPort   = 0;

            // Connect to a remote device.

            // Establish the remote endpoint for the socket.
            // This example uses port 11000 on the local computer.
            //IPHostEntry ipClientInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPHostEntry ipHostInfo = Dns.GetHostEntry(req.Uri.Host);
            IPAddress   ipAddress  = ipHostInfo.AddressList.First(x => x.AddressFamily == AddressFamily.InterNetwork);
            IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, req.Port);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork,
                                       SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.

            sender.Connect(remoteEP);
            clientPort = ((IPEndPoint)sender.LocalEndPoint).Port;

            //Console.WriteLine("Socket connected to {0}",
            //    sender.RemoteEndPoint.ToString());

            // Encode the data string into a byte array.
            byte[] msg = Encoding.ASCII.GetBytes(req.ToString());

            // Send the data through the socket.
            utcTimeStamp = DateTime.UtcNow;
            int bytesSent = sender.Send(msg);

            // Receive the response from the remote device.
            int bytesRec = sender.Receive(bytes);

            response = Encoding.ASCII.GetString(bytes, 0, bytesRec);

            // Release the socket.
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();

            //return new NetResult(new WebResp(req, response, utcTimeStamp, Dns.GetHostName(), clientPort));

            dynamic r = new Result(oper);

            r.sourceAddress      = Dns.GetHostName();
            r.sourcePort         = clientPort;
            r.destinationAddress = req.Uri.AbsoluteUri;
            r.destinationPort    = req.Port;
            r.bytesSent          = req.ToString().Length;
            r.protocol           = req.Uri.Scheme;

            return(r);
        }