Ejemplo n.º 1
0
 public string Serialize <T> (T obj, bool readableOutput = false) where T : class, new()
 {
     try
     {
         System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType(), ExtraTypes.ToArray());
         using (StringWriter writer = new StringWriter())
         {
             XmlWriterSettings settings = (readableOutput ? settingsForReadableOutput : settingsForCompactOutput);
             using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
             {
                 xmlSerializer.Serialize(xmlWriter, obj);
                 string xml = writer.ToString();
                 //DebugLog.Info("To XML: " + xml);
                 return(xml);
             }
         }
     }
     catch (Exception e)
     {
         DebugLog.Error("Unable to serialize {0}. XML serialize error: {1}",
                        typeof(T).Name,
                        DebugLog.GetNestedMessages(e));
         throw new Exception("Unable to serialize to XML: " + DebugLog.SafeName(obj), e);
     }
 }
        protected void GetAll(ResponseHandler callback)
        {
            List <T> items = new List <T>();
            string   error = null;

            try
            {
                TextAsset[] textAssets = Resources.LoadAll <TextAsset>(DataDirectory);
                foreach (TextAsset textAsset in textAssets)
                {
                    T      item = Serializer.Deserialize <T>(textAsset.text);
                    string id   = GetKey(item).ToString();
                    if (textAsset.name.CompareTo(id) != 0)
                    {
                        DebugLog.Error("Object ID ({0}) does not match filename in {1}: {2}", id, DataDirectory, textAsset.name);
                    }
                    items.Add(item);
                }
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            finally
            {
                if (callback != null)
                {
                    callback(new Response(items, error));
                }
            }
        }
 void Update()
 {
     // Detect field change
     if (brain != previousBrain)
     {
         if (brain != null)
         {
             if (brain.DecisionMaker != null)
             {
                 DebugLog.Info("IntelligentAgent set NavigationController");
                 NavigationController navController = GetComponent <NavigationController>();
                 if (navController != null)
                 {
                     brain.DecisionMaker.LocalKnowledge.Set("NavigationController", navController);
                 }
                 brain.DecisionMaker.IsEnabled = enabled;
             }
             else
             {
                 DebugLog.Error("DecisionMaker not set in {0}", brain.name);
             }
         }
         previousBrain = brain;
     }
 }
Ejemplo n.º 4
0
 public override void OnStartReveal()
 {
     if (Error != null)
     {
         DebugLog.Error("Error Alert Displayed. {0}. {1}", Error.Message, Error.StackTrace);
     }
     base.OnStartReveal();
 }
        private void RefreshActivityList()
        {
            try
            {
                Contract.PropertyNotNull("sessionState.CourseSettings", sessionState.CourseSettings);

                DebugLog.Info("RefreshActivityList");
                navigator.Reveal <ProgressIndicatorViewModel>().Then((vm, onRevealed, onRevealError) =>
                {
                    ProgressIndicatorViewModel progressIndicatorViewModel = vm.ResultAs <ProgressIndicatorViewModel>();
                    ProgressIndicatorViewModel.ProgressInfo busyIndicator = progressIndicatorViewModel.Begin("Loading...");
                    activityService.LoadActivities(sessionState.CourseSettings.CourseId)
                    .Then((prevResult, onCompleted, onError) =>
                    {
                        DebugLog.Info("Activities loaded");
                        Activities = prevResult.ResultAs <List <Activity> >();
                        IEnumerable <string> activityIds = Activities.Select(a => a.Id);
                        activityService.LoadActivityStates(sessionState.Student.Id, activityIds).Start(onCompleted, onError);
                    })
                    .Then((prevResult, onCompleted, onError) =>
                    {
                        DebugLog.Info("Activity States loaded");
                        ActivityStates = prevResult.ResultAs <List <ActivityState> >();
                        onCompleted(true);
                    })
                    .Catch((Exception e) =>
                    {
                        DebugLog.Error("Can't load activitues: {0}", e.Message);
                        navigator.Reveal <AlertViewModel>(alert =>
                        {
                            alert.Title           = "Unable to load activity information.";
                            alert.Message         = e.Message;
                            alert.Error           = e;
                            alert.AlertDismissed += ((int index) => DebugLog.Info("Button {0} pressed", index));
                        }).Start();
                    }).Finally(() =>
                    {
                        busyIndicator.Dispose();
                    }).Start();

                    onRevealed(true);
                }).Start();
            }
            catch (Exception e)
            {
                navigator.Reveal <AlertViewModel>(alert =>
                {
                    alert.Title   = "Unable load activity information";
                    alert.Message = e.Message;
                    alert.Error   = e;
                }).Start();
            }
        }
 public void Write(LogEntry entry)
 {
     if (Enabled)
     {
         Insert(entry, (Response response) =>
         {
             if (!response.Success)
             {
                 DebugLog.Error("RepositoryLogger unabled to log. " + response.Error);
             }
         });
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Get response stream from a web service indicated by URI
        /// </summary>
        /// <param name="uri">URI (path plus query string) to web service</param>
        /// <param name="retries">The number of times to retry get if it fails</param>
        /// <param name="callback">Method called on failure or success that is passed an AsyncResult whose Result property is set to HttpResult</param>
        /// <returns>WebRequest IAsyncResult object</returns>
        public IAsyncResult Get(Uri uri, int retries, AsyncCallback callback)
        {
#if (SILVERLIGHT || WPF || TOOL)
            WebRequest webRequest = WebRequest.Create(uri);
#else
            WebRequest webRequest = new UnityWebRequest(uri);
#endif
            webRequest.Method = "GET";
            IAsyncResult asyncResult = webRequest.BeginGetResponse((responseResult) =>
            {
                bool retry            = false;
                HttpResult httpResult = null;
                try
                {
                    HttpWebResponse response = ((WebRequest)responseResult.AsyncState).EndGetResponse(responseResult) as HttpWebResponse;
                    // Response stream is released when HttpResult is released
                    httpResult = new HttpResult(response.GetResponseStream(), response.StatusCode, response.StatusDescription, response.ContentType);
                }
                catch (WebException we)
                {
                    DebugLog.Error("WebException -> Get '{0}' failed", uri.ToString());
                    DebugLog.Error(we.Message);
                    if (retries > 0 && we.Status != WebExceptionStatus.RequestCanceled)
                    {
                        DebugLog.Info("Retry Get '{0}'", uri.ToString());
                        Get(uri, --retries, callback);
                        retry = true;
                    }
                    else
                    {
                        httpResult = new HttpResult(we);
                    }
                }
                catch (Exception e)
                {
                    DebugLog.Error("HTTP GET '{0}' failed: {1}", uri.ToString(), e.Message);
                    httpResult = new HttpResult(e);
                }
                finally
                {
                    if (!retry && callback != null)
                    {
                        callback(new AsyncResult <HttpResult>(httpResult));
                    }
                }
            },
                                                                   webRequest);

            return(asyncResult);
        }
Ejemplo n.º 8
0
        public override void Insert(T instance, ResponseHandler callback)
        {
            string serializedObj = Serializer.Serialize <T>(instance);

            MimePart mimePart = new MimePart(MimePart.ApplicationXml, serializedObj);

            httpClient.Post(CreateUri, DefaultRetryCount, mimePart, (postResult) =>
            {
                List <T> responseInstance = null;
                string error = null;
                try
                {
                    using (HttpResult httpResult = postResult.AsyncState as HttpResult)
                    {
                        // Check server response
                        if (CheckServerResult(httpResult, ref error))
                        {
                            string responseObj = httpResult.Response;
                            if (!string.IsNullOrEmpty(responseObj))
                            {
                                RestResponse response = Serializer.Deserialize <R>(responseObj) as RestResponse;
                                responseInstance      = response.ToList <T>();
                                error = response.Error;
                            }
                            else
                            {
                                error = "Empty response for: " + UpdateUri.ToString();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    error = "Unable to upload data to the cloud. " + e.Message;
                }
                finally
                {
                    if (!String.IsNullOrEmpty(error))
                    {
                        DebugLog.Error(error);
                    }

                    if (callback != null)
                    {
                        callback(new Response(responseInstance, error));
                    }
                }
            });
        }
Ejemplo n.º 9
0
        protected void Get(Uri uri, ResponseHandler callback)
        {
            httpClient.Get(uri, DefaultRetryCount, (postResult) =>
            {
                List <T> instance = null;
                string error      = null;
                try
                {
                    using (HttpResult httpResult = postResult.AsyncState as HttpResult)
                    {
                        // Check status of the WWW upload
                        if (CheckServerResult(httpResult, ref error))
                        {
                            string serializedObj = httpResult.Response;
                            if (!string.IsNullOrEmpty(serializedObj))
                            {
                                RestResponse response = Serializer.Deserialize <R>(serializedObj) as RestResponse;
                                instance = response.ToList <T>();
                                error    = response.Error;
                            }
                            else
                            {
                                error = "Empty response for: " + uri.ToString();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    error = "Unable to download data from cloud. " + e.Message;
                }
                finally
                {
                    if (!String.IsNullOrEmpty(error))
                    {
                        DebugLog.Error(error);
                    }

                    if (callback != null)
                    {
                        callback(new Response(instance, error));
                    }
                }
            });
        }
Ejemplo n.º 10
0
 public T Deserialize <T>(string xml) where T : class, new()
 {
     try
     {
         //DebugLog.Info("From XML: " + xml);
         System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
         using (TextReader reader = new StringReader(xml))
         {
             T obj = (T)xmlSerializer.Deserialize(reader);
             return(obj);
         }
     }
     catch (Exception e)
     {
         DebugLog.Error("Unable to deserialize {0}. XML deserialize error: {1}\n{2}",
                        typeof(T).Name,
                        DebugLog.GetNestedMessages(e),
                        xml);
         throw new Exception("Unable to deserialize from XML: " + typeof(T).GetType().Name, e);
     }
 }
        /// <summary>
        /// Convenient method for quickly accessing a unique Component on the Unique GameObject (or a
        /// child of the Unique GameObject)
        /// </summary>
        /// <typeparam name="C">The 1st type parameter.</typeparam>
        public static C Component <C>() where C : Behaviour
        {
            if (referenceCache.ContainsKey(typeof(C)))
            {
                return(referenceCache[typeof(C)] as C);
            }
            else
            {
                Behaviour[] components = Current.GetComponentsInChildren <C>(true);
                if (components.Length > 0)
                {
                    referenceCache.Add(typeof(C), components[0]);
                    if (components.Length > 1)
                    {
                        DebugLog.Error("Found more than one component of type '{0}' within '{1}' GameObject hierarchy",
                                       typeof(C).Name,
                                       Current.gameObject.name);
                    }
                    return(components[0] as C);
                }
            }

            return(null);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Post one or more MIME parts to a URI
        /// </summary>
        /// <param name="uri">The URI of the web service to receive the Http post message</param>
        /// <param name="retries">Number of times to retry post if there is an error</param>
        /// <param name="mimeParts">MIME encoded payload</param>
        /// <param name="callback">Method called on failure or success that is passed an AsyncResult whose Result property is set to HttpResult</param>
        /// <returns>WebRequest IAsyncResult object</returns>
        public IAsyncResult Post(Uri uri, int retries, List <MimePart> mimeParts, AsyncCallback callback)
        {
#if (SILVERLIGHT || WPF || TOOL)
            WebRequest webRequest = WebRequest.Create(uri);
#else
            WebRequest webRequest = new UnityWebRequest(uri);
#endif
            webRequest.Method = "POST";
            IAsyncResult asyncResult = webRequest.BeginGetRequestStream((asynchronousResult) =>
            {
                WebRequest request = (WebRequest)asynchronousResult.AsyncState;

                if (mimeParts.Count > 1)
                {
                    CreateMultiPartRequest(request, asynchronousResult, mimeParts);
                }
                else
                {
                    CreateSinglePartRequest(request, asynchronousResult, mimeParts[0]);
                }

                // Start the asynchronous operation to get the response
                request.BeginGetResponse((responseResult) =>
                {
                    bool retry            = false;
                    HttpResult httpResult = null;
                    try
                    {
                        HttpWebResponse response = ((WebRequest)responseResult.AsyncState).EndGetResponse(responseResult) as HttpWebResponse;
                        // Response stream is released when HttpResult is released
                        httpResult = new HttpResult(response.GetResponseStream(), response.StatusCode, response.StatusDescription, response.ContentType);
                    }
                    catch (WebException we)
                    {
                        DebugLog.Error("WebException -> {0} '{1}' failed", webRequest.Method, uri.ToString());
                        DebugLog.Error(we.Message);
                        if (retries > 0 && we.Status != WebExceptionStatus.RequestCanceled)
                        {
                            DebugLog.Info("Retry {0} '{1}'", webRequest.Method, uri.ToString());
                            Post(uri, --retries, mimeParts, callback);
                            retry = true;
                        }
                        else
                        {
                            httpResult = new HttpResult(we);
                        }
                    }
                    catch (Exception e)
                    {
                        DebugLog.Error("HTTP {0} '{1}' failed: {2}", webRequest.Method, uri.ToString(), e.Message);
                        httpResult = new HttpResult(e);
                    }
                    finally
                    {
                        if (!retry && callback != null)
                        {
                            callback(new AsyncResult <HttpResult>(httpResult));
                        }
                    }
                },
                                         request);
            },
                                                                        webRequest);

            return(asyncResult);
        }