public WoopsaMetaResult Meta(string path)
        {
            string response = Request(WoopsaFormat.VerbMeta + path);
            var    result   = WoopsaFormat.DeserializeMeta(response);

            return(result);
        }
Exemple #2
0
        private void HandleRequest(WoopsaVerb verb, HTTPRequest request, HTTPResponse response)
        {
            try
            {
                // This is the first thing we do, that way even 404 errors have the right headers
                if (AllowCrossOrigin)
                {
                    // TODO: constantes symboliques
                    response.SetHeader("Access-Control-Allow-Origin", "*");
                }
                string result = null;
                ExecuteBeforeWoopsaModelAccess();
                try
                {
                    switch (verb)
                    {
                    case WoopsaVerb.Meta:
                        result = GetMetadata(request.Subroute);
                        break;

                    case WoopsaVerb.Read:
                        result = ReadValue(request.Subroute);
                        break;

                    case WoopsaVerb.Write:
                        result = WriteValue(request.Subroute, request.Body["value"]);
                        break;

                    case WoopsaVerb.Invoke:
                        result = InvokeMethod(request.Subroute, request.Body);
                        break;
                    }
                }
                finally
                {
                    ExecuteAfterWoopsaModelAccess();
                }
                response.SetHeader(HTTPHeader.ContentType, MIMETypes.Application.JSON);
                if (result != null)
                {
                    response.WriteString(result);
                }
            }
            catch (WoopsaNotFoundException e)
            {
                response.WriteError(HTTPStatusCode.NotFound, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
            catch (WoopsaInvalidOperationException e)
            {
                response.WriteError(HTTPStatusCode.BadRequest, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
            catch (WoopsaException e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
            catch (Exception e)
            {
                response.WriteError(HTTPStatusCode.InternalServerError, e.Message, WoopsaFormat.Serialize(e), MIMETypes.Application.JSON);
            }
        }
        public static WoopsaValue DeserializeWoopsaValue(string jsonText)
        {
            var result = JsonSerializer.Deserialize <WoopsaReadResult>(jsonText);

            if (result != null)
            {
                var         valueType = (WoopsaValueType)Enum.Parse(typeof(WoopsaValueType), result.Type);
                WoopsaValue resultWoopsaValue;
                DateTime?   timeStamp;
                if (result.TimeStamp != null)
                {
                    timeStamp = DateTime.Parse(result.TimeStamp, CultureInfo.InvariantCulture);
                }
                else
                {
                    timeStamp = null;
                }
                if (valueType == WoopsaValueType.JsonData)
                {
                    resultWoopsaValue = new WoopsaValue(WoopsaJsonData.CreateFromDeserializedData(result.Value), timeStamp);
                }
                else
                {
                    resultWoopsaValue = WoopsaValue.CreateChecked(WoopsaFormat.ToStringWoopsa(result.Value),
                                                                  valueType, timeStamp);
                }
                return(resultWoopsaValue);
            }
            else
            {
                return(WoopsaValue.Null);
            }
        }
        public WoopsaValue Write(string path, string value)
        {
            var arguments = new NameValueCollection {
                { WoopsaFormat.KeyValue, value }
            };
            string response = Request(WoopsaFormat.VerbWrite + path, arguments);

            return(WoopsaFormat.DeserializeWoopsaValue(response));
        }
Exemple #5
0
        public static WoopsaValue ToWoopsaValue(object value, WoopsaValueType type, DateTime?timeStamp = null)
        {
            try
            {
                switch (type)
                {
                case WoopsaValueType.Logical:
                    return(new WoopsaValue((bool)value, timeStamp));

                case WoopsaValueType.Integer:
                    return(new WoopsaValue(Convert.ToInt64(value), timeStamp));

                case WoopsaValueType.Real:
                    return(new WoopsaValue(Convert.ToDouble(value), timeStamp));

                case WoopsaValueType.DateTime:
                    return(new WoopsaValue((DateTime)value, timeStamp));

                case WoopsaValueType.TimeSpan:
                    if (value is TimeSpan)
                    {
                        return(new WoopsaValue((TimeSpan)value, timeStamp));
                    }
                    else
                    {
                        return(new WoopsaValue(TimeSpan.FromSeconds(Convert.ToDouble(value)),
                                               timeStamp));
                    }

                case WoopsaValueType.Text:
                    if (value == null)
                    {
                        return(new WoopsaValue(string.Empty, timeStamp));
                    }
                    else if (value.GetType().IsEnum)
                    {
                        return(new WoopsaValue(value.ToString(), timeStamp));
                    }
                    else if (string.IsNullOrEmpty((string)value))
                    {
                        return(new WoopsaValue(string.Empty, timeStamp));
                    }
                    else
                    {
                        return(new WoopsaValue(WoopsaFormat.ToStringWoopsa(value), timeStamp));
                    }

                default:
                    return(WoopsaValue.CreateUnchecked(WoopsaFormat.ToStringWoopsa(value), type, timeStamp));
                }
            }
            catch (InvalidCastException)
            {
                throw new WoopsaException(String.Format("Cannot typecast object of type {0} to Woopsa Type {1}", value.GetType(), type.ToString()));
            }
        }
Exemple #6
0
 public static bool ToBool(this WoopsaJsonData data)
 {
     if (data.IsSimple)
     {
         return(WoopsaFormat.ToBool(WoopsaFormat.ToStringWoopsa(data.InternalObject)));
     }
     else
     {
         throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastTypeMessage("bool", data.InternalObject.GetType().ToString()));
     }
 }
Exemple #7
0
 public static bool ToBool(this IWoopsaValue value)
 {
     if (value.Type == WoopsaValueType.Logical)
     {
         return(WoopsaFormat.ToBool(value.AsText));
     }
     else
     {
         throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastTypeMessage("bool", value.Type.ToString()));
     }
 }
Exemple #8
0
 internal void DispatchResults(WoopsaJsonData jsonData)
 {
     if (jsonData.IsArray)
     {
         for (int i = 0; i < jsonData.Length; i++)
         {
             WoopsaJsonData      item = jsonData[i];
             int                 id   = item[WoopsaFormat.KeyId];
             WoopsaClientRequest request;
             if (_clientRequestsById.TryGetValue(id, out request))
             {
                 WoopsaJsonData result = item[WoopsaFormat.KeyResult];
                 if (result.ContainsKey(WoopsaFormat.KeyError))
                 {
                     request.Result = new WoopsaClientRequestResult()
                     {
                         Error      = WoopsaFormat.DeserializeError(result.AsText),
                         ResultType = WoopsaClientRequestResultType.Error
                     };
                 }
                 else if (request.Request.Verb == WoopsaFormat.VerbMeta)
                 {
                     request.Result = new WoopsaClientRequestResult()
                     {
                         Meta       = WoopsaFormat.DeserializeMeta(result.AsText),
                         ResultType = WoopsaClientRequestResultType.Meta
                     };
                 }
                 else
                 {
                     request.Result = new WoopsaClientRequestResult()
                     {
                         Value      = WoopsaFormat.DeserializeWoopsaValue(result.AsText),
                         ResultType = WoopsaClientRequestResultType.Value
                     };
                 }
                 request.IsDone = true;
             }
             else
             {
                 throw new WoopsaException(
                           string.Format("MultiRequest received a result for an unkwnon request Id={0}", id));
             }
         }
     }
     else
     {
         throw new WoopsaException("MultiRequest response has invalid format");
     }
 }
 public static TimeSpan ToTimeSpan(this IWoopsaValue value)
 {
     if (value.Type == WoopsaValueType.TimeSpan)
     {
         if (WoopsaFormat.TryParseWoopsa(value.AsText, out double result))
         {
             return(TimeSpan.FromSeconds(result));
         }
         else
         {
             throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastValueMessage("TimeSpan", value.AsText));
         }
     }
     else
     {
         throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastTypeMessage("TimeSpan", value.Type.ToString()));
     }
 }
 public static int ToInt32(this IWoopsaValue value)
 {
     if (value.Type == WoopsaValueType.Integer)
     {
         if (WoopsaFormat.TryParseWoopsa(value.AsText, out int result))
         {
             return(result);
         }
         else
         {
             throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastValueMessage("Int32", value.AsText));
         }
     }
     else
     {
         throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastTypeMessage("Int32", value.Type.ToString()));
     }
 }
Exemple #11
0
 private WoopsaValue HandleCall(IWoopsaValue requestsArgument)
 {
     using (new WoopsaServerModelAccessFreeSection(_server))
     {
         ServerRequest[] requestsList             = JsonSerializer.Deserialize <ServerRequest[]>(requestsArgument.AsText, WoopsaUtils.ObjectToInferredTypesConverterOptions);
         List <MultipleRequestResponse> responses = new List <MultipleRequestResponse>();
         foreach (var request in requestsList)
         {
             string result = null;
             try
             {
                 using (new WoopsaServerModelAccessLockedSection(_server))
                 {
                     if (request.Verb.Equals(WoopsaFormat.VerbRead))
                     {
                         result = _server.ReadValue(request.Path);
                     }
                     else if (request.Verb.Equals(WoopsaFormat.VerbMeta))
                     {
                         result = _server.GetMetadata(request.Path);
                     }
                     else if (request.Verb.Equals(WoopsaFormat.VerbWrite))
                     {
                         result = _server.WriteValueDeserializedJson(request.Path, request.Value);
                     }
                     else if (request.Verb.Equals(WoopsaFormat.VerbInvoke))
                     {
                         result = _server.InvokeMethodDeserializedJson(request.Path,
                                                                       request.Arguments);
                     }
                 }
             }
             catch (Exception e)
             {
                 result = WoopsaFormat.Serialize(e);
             }
             MultipleRequestResponse response = new MultipleRequestResponse();
             response.Id     = request.Id;
             response.Result = result;
             responses.Add(response);
         }
         return(WoopsaValue.CreateUnchecked(responses.Serialize(), WoopsaValueType.JsonData));
     }
 }
Exemple #12
0
        private WoopsaValue HandleCall(IWoopsaValue requestsArgument)
        {
            var serializer = new JavaScriptSerializer();

            ServerRequest[] requestsList             = serializer.Deserialize <ServerRequest[]>(requestsArgument.AsText);
            List <MultipleRequestResponse> responses = new List <MultipleRequestResponse>();

            foreach (var request in requestsList)
            {
                string result = null;
                try
                {
                    if (request.Verb.Equals(WoopsaFormat.VerbRead))
                    {
                        result = _server.ReadValue(request.Path);
                    }
                    else if (request.Verb.Equals(WoopsaFormat.VerbMeta))
                    {
                        result = _server.GetMetadata(request.Path);
                    }
                    else if (request.Verb.Equals(WoopsaFormat.VerbWrite))
                    {
                        result = _server.WriteValueDeserializedJson(request.Path, request.Value);
                    }
                    else if (request.Verb.Equals(WoopsaFormat.VerbInvoke))
                    {
                        result = _server.InvokeMethodDeserializedJson(request.Path,
                                                                      request.Arguments);
                    }
                }
                catch (Exception e)
                {
                    result = WoopsaFormat.Serialize(e);
                }
                MultipleRequestResponse response = new MultipleRequestResponse();
                response.Id     = request.Id;
                response.Result = result;
                responses.Add(response);
            }
            return(WoopsaValue.CreateUnchecked(responses.Serialize(), WoopsaValueType.JsonData));
        }
 public static double ToDouble(this IWoopsaValue value)
 {
     if (value.Type == WoopsaValueType.Real)
     {
         if (WoopsaFormat.TryParseWoopsa(value.AsText, out double result))
         {
             return(result);
         }
         else
         {
             throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastValueMessage("double", value.AsText));
         }
     }
     else if (value.Type == WoopsaValueType.Integer)
     {
         return(value.ToInt64());
     }
     else
     {
         throw new WoopsaException(WoopsaExceptionMessage.WoopsaCastTypeMessage("double", value.Type.ToString()));
     }
 }
 public static void Serialize(StringBuilder stringBuilder, IWoopsaValue value)
 {
     stringBuilder.Append(ElementOpen);
     // Value
     if (MustQuote(value.Type))
     {
         SerializeKeyValue(stringBuilder, KeyValue, value.AsText, true, true);
     }
     else
     {
         SerializeKeyValue(stringBuilder, KeyValue, value.AsText, false, false);
     }
     stringBuilder.Append(ElementSeparator);
     // Type
     SerializeKeyValue(stringBuilder, KeyType, value.Type.ToString(), true, false);
     // TimeStamp
     if (value.TimeStamp.HasValue)
     {
         stringBuilder.Append(ElementSeparator);
         SerializeKeyValue(stringBuilder, KeyTimeStamp,
                           WoopsaFormat.ToStringWoopsa(value.TimeStamp.Value), true, false);
     }
     stringBuilder.Append(ElementClose);
 }
Exemple #15
0
        public WoopsaValue Invoke(string path, NameValueCollection arguments, TimeSpan timeout)
        {
            string response = Request(WoopsaFormat.VerbInvoke + path, arguments, timeout);

            return(WoopsaFormat.DeserializeWoopsaValue(response));
        }
        private string Request(string path, NameValueCollection postData, TimeSpan timeout)
        {
            if (!_terminating)
            {
                var request = (HttpWebRequest)WebRequest.Create(Url + path);
                request.CachePolicy = _cachePolicy;

                // TODO : affiner l'optimisation de performance
                request.ServicePoint.UseNagleAlgorithm = false;
                request.ServicePoint.Expect100Continue = false;

                HttpWebResponse response = null;

                lock (_pendingRequests)
                    _pendingRequests.Add(request);
                try
                {
                    try
                    {
                        if (Username != null)
                        {
                            request.Credentials = new NetworkCredential(Username, Password);
                        }

                        request.Timeout = (int)timeout.TotalMilliseconds;

                        if (postData != null)
                        {
                            request.Method      = "POST";
                            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                        }
                        else
                        {
                            request.Method = "GET";
                        }

                        request.Accept = "*/*";

                        if (postData != null)
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (var i = 0; i < postData.Count; i++)
                            {
                                string key = postData.AllKeys[i];
                                stringBuilder.AppendFormat(i == postData.Count - 1 ? "{0}={1}" : "{0}={1}&",
                                                           HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(postData[key]));
                            }
                            using (var writer = new StreamWriter(request.GetRequestStream()))
                                writer.Write(stringBuilder.ToString());
                        }

                        response = (HttpWebResponse)request.GetResponse();
                        SetLastCommunicationSuccessful(true);
                    }
                    catch (WebException exception)
                    {
                        // This could be an HTTP error, in which case
                        // we actually have a response (with the HTTP
                        // status and error)
                        response = (HttpWebResponse)exception.Response;
                        if (response == null)
                        {
                            SetLastCommunicationSuccessful(false);
                            // Sometimes, we can make the request, but the server dies
                            // before we get a reply - in that case the Response
                            // is null, so we re-throw the exception
                            throw;
                        }
                    }
                    catch (Exception)
                    {
                        SetLastCommunicationSuccessful(false);
                        throw;
                    }

                    string resultString;
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        resultString = reader.ReadToEnd();
                    }

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        if (response.ContentType == MIMETypes.Application.JSON)
                        {
                            var exception = WoopsaFormat.DeserializeError(resultString);
                            throw exception;
                        }

                        throw new WoopsaException(response.StatusDescription);
                    }

                    return(resultString);
                }
                finally
                {
                    lock (_pendingRequests)
                        _pendingRequests.Remove(request);
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
            else
            {
                throw new ObjectDisposedException(GetType().Name);
            }
        }
Exemple #17
0
 public WoopsaValue(TimeSpan value, DateTime?timestamp = null)
     : this(WoopsaFormat.ToStringWoopsa(value), WoopsaValueType.TimeSpan, timestamp)
 {
 }
Exemple #18
0
 public WoopsaValue(double value, DateTime?timestamp = null)
     : this(WoopsaFormat.ToStringWoopsa(value), WoopsaValueType.Real, timestamp)
 {
 }
Exemple #19
0
 public WoopsaValue(Int64 value, DateTime?timestamp = null)
     : this(WoopsaFormat.ToStringWoopsa(value), WoopsaValueType.Integer, timestamp)
 {
 }
Exemple #20
0
 public WoopsaValue(bool value, DateTime?timestamp = null)
     : this(WoopsaFormat.ToStringWoopsa(value), WoopsaValueType.Logical, timestamp)
 {
 }
Exemple #21
0
        public WoopsaValue Read(string path)
        {
            string response = Request(WoopsaFormat.VerbRead + path);

            return(WoopsaFormat.DeserializeWoopsaValue(response));
        }