Esempio n. 1
0
            public override void ParseJson(DbGeographyGeoJsonConverter converter, Newtonsoft.Json.Linq.JArray array)
            {
                var targetCoordinateSystem = (converter as EpsgDbGeometryConverter).CoordinateSystem;

                //Cant convert if source dont have any coordinate system.
                if (!CoordinateSystem.HasValue || CoordinateSystem == targetCoordinateSystem)
                {
                    base.ParseJson(converter, array);
                    return;
                }



                Rings = new List <List <Position> >();
                var rings = array.ToObject <double[][][]>();

                var ringSizes        = rings.Select(r => r.Length).ToArray();
                var coordinateLength = rings.First().GroupBy(c => c.Length).Single().Key;

                foreach (var ring in rings)
                {
                    var flat = ring.SelectMany(s => s).ToArray();

                    Reproject.ReprojectPoints(flat, null,
                                              ProjectionInfo.FromEpsgCode(CoordinateSystem.Value), ProjectionInfo.FromEpsgCode(targetCoordinateSystem.Value), 0, ringSizes[0]);

                    var ringList = new List <Position>();
                    for (int i = 0; i < flat.Length; i += coordinateLength)
                    {
                        ringList.Add(new Position(flat.Skip(i).Take(coordinateLength).ToArray()));
                    }
                    Rings.Add(ringList);
                }
                CoordinateSystem = targetCoordinateSystem;
            }
Esempio n. 2
0
        public void OnPostDiagnostics()
        {
            if (!CheckPatient)
            {
                newTriage = (Triage)Enum.Parse(typeof(Triage), Request.Form[nameof(newTriage)].ToString());
            }
            else
            {
                Newtonsoft.Json.Linq.JArray tempData = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject((string)TempData["attention"]);
                patientsAttention = tempData.ToObject <List <ConsultoryPatients> >();
                var patientRecovered = new Patient
                {
                    Id       = patientsAttention[0].Id,
                    Name     = patientsAttention[0].Name,
                    Age      = patientsAttention[0].Age,
                    Document = patientsAttention[0].Document,
                    Gender   = patientsAttention[0].Gender,
                    State    = State.Recuperado
                };
                patientsAttention.RemoveAt(0);
                TempData["attention"] = JsonConvert.SerializeObject(patientsAttention);

                patientsRecovered.Add(patientRecovered);
                GetConsultories();
            }
        }
Esempio n. 3
0
        public static List <T> GetList <T>(DbDataReader dataReader)
        {
            // 列名
            var cols = new List <string>();

            for (int index = 0; index < dataReader.FieldCount; index++)
            {
                cols.Add(dataReader.GetName(index));
            }

            // 赋值
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            while (dataReader.Read() == true)
            {
                var toAdd_JObject = new Newtonsoft.Json.Linq.JObject();

                foreach (string col in cols)
                {
                    if (dataReader[col] != DBNull.Value)
                    {
                        toAdd_JObject.Add(col, dataReader[col].ToString());
                    }
                    else
                    {
                        toAdd_JObject.Add(col, null);
                    }
                }

                jArray.Add(toAdd_JObject);
            }

            return(jArray.ToObject <List <T> >());
        }
        // GET: IoT
        public async Task <ActionResult> Index()
        {
            List <Incident> incidents;

            using (var client = IncidentApiHelper.GetIncidentAPIClient())
            {
                int CACHE_EXPIRATION_SECONDS = 60;

                //Check Cache
                string cachedData = string.Empty;
                if (RedisCacheHelper.UseCachedDataSet(Settings.REDISCCACHE_KEY_INCIDENTDATA, out cachedData))
                {
                    incidents = JsonConvert.DeserializeObject <List <Incident> >(cachedData);
                }
                else
                {
                    //If stale refresh
                    var results = await client.IncidentOperations.GetAllIncidentsAsync();

                    Newtonsoft.Json.Linq.JArray ja = (Newtonsoft.Json.Linq.JArray)results;
                    incidents = ja.ToObject <List <Incident> >();
                    RedisCacheHelper.AddtoCache(Settings.REDISCCACHE_KEY_INCIDENTDATA, incidents, CACHE_EXPIRATION_SECONDS);
                }
            }
            return(View(incidents));
        }
Esempio n. 5
0
        static async void DownloadPageAsync()
        {
            // ... Target page.
            //string page = "https://jsonplaceholder.typicode.com/posts";
            //string page = "http://www.mocky.io/v2/5d447b6b2f000080291796ce";
            string page = "http://localhost:3000/api/todo";


            // ... Use HttpClient.

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                using (HttpResponseMessage response = await client.GetAsync(page))
                    using (HttpContent content = response.Content)
                    {
                        // ... Read the string.
                        string result = await content.ReadAsStringAsync();

                        // ... Display the result.
                        if (result != null &&
                            result.Length >= 50)
                        {
                            Console.WriteLine(result);
                            dynamic json = JsonConvert.DeserializeObject(result);
                            Newtonsoft.Json.Linq.JArray jarr = json;
                            OnePost v  = jarr[0].ToObject <OnePost>();
                            var     va = jarr.ToObject <OnePost[]>();
                        }
                    }
            }
        }
Esempio n. 6
0
        //RETURNS ALL BORROWED NOT RETURNED BUT BEFORE DEADLINE
        public async Task <List <Borrowed> > GetBorrowedForUserAsync(string email)
        {
            var gotFromServer = await service.getClient().GetStringAsync("http://localhost:8543/Borrowed/" + email);

            Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(gotFromServer);

            List <Borrowed> BorrowedByArray = array.ToObject <List <Borrowed> >();

            return(BorrowedByArray);
        }
Esempio n. 7
0
        public async Task <List <Item> > GetItemsAsync()
        {
            var gotFromServer = await service.getClient().GetStringAsync("http://localhost:8543/Items");

            Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(gotFromServer);

            List <Item> itemArray = array.ToObject <List <Item> > ();

            return(itemArray);
        }
Esempio n. 8
0
        public List <T> GetAllX <T>(List <DataFilterExpressionREST> dataFilterExpressionRESTs, out string error)
        {
            error = null;
            try
            {
                Uri            basePath   = new Uri(wpfConfig.RESTBasePath);
                Uri            requestUri = new Uri(basePath, "CustomerDemographics/GetAllX");
                GeneralBodyGet getRequest = new GeneralBodyGet();
                getRequest.NumberOfItens = 0;
                getRequest.ItensToSkip   = 0;
                getRequest.Filters       = dataFilterExpressionRESTs;
                string requestBody = Newtonsoft.Json.JsonConvert.SerializeObject(getRequest);

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Clear();
                    var request = new HttpRequestMessage
                    {
                        Method     = HttpMethod.Get,
                        RequestUri = requestUri,
                        Content    = new StringContent(requestBody, Encoding.UTF8, "application/json")
                    };
                    var response = client.SendAsync(request).Result;

                    var                responseContent    = response.Content;
                    string             responseString     = responseContent.ReadAsStringAsync().Result;
                    GeneralGetResponse generalGetResponse = JsonConvert.DeserializeObject <GeneralGetResponse>(responseString);
                    if (response.IsSuccessStatusCode)
                    {
                        Newtonsoft.Json.Linq.JArray        jArray        = (Newtonsoft.Json.Linq.JArray)generalGetResponse.Data;
                        List <GetCustomerDemographicsView> dataRetrieved = jArray.ToObject <List <GetCustomerDemographicsView> >();
                        List <T> result = new List <T>();
                        foreach (GetCustomerDemographicsView item in dataRetrieved)
                        {
                            T modelNotifiedForCustomerDemographicsNew = (T)Activator.CreateInstance(typeof(T));
                            Cloner.CopyAllTo(typeof(GetCustomerDemographicsView), item, typeof(T), modelNotifiedForCustomerDemographicsNew);
                            result.Add(modelNotifiedForCustomerDemographicsNew);
                        }
                        return(result);
                    }
                    else
                    {
                        error = "Server side refused this request and returned status {0}. Reason {1}. TransactionID:{0}";
                        error = string.Format(error, response.StatusCode, generalGetResponse.ReportHeader.MessageFromServer, generalGetResponse.ReportHeader.TransactionID);
                    }

                    return(null);
                }
            }
            catch (Exception ex)
            {
                error = "Error trying during data request. Request crash: " + ex.Message;
            }
            return(null);
        }
Esempio n. 9
0
        /// <summary>
        /// GridViewColumnsAddVisible
        /// </summary>
        private void GridViewColumnsAddVisible(DevExpress.XtraGrid.GridControl gridControl,
                                               DevExpress.XtraGrid.Views.Grid.GridView gridView,
                                               string gridControlHead)
        {
            string filePath   = string.Format(@"{0}\GridViewHeaderJson\{1}.txt", System.Windows.Forms.Application.StartupPath, gridControlHead);
            string jsonString = System.IO.File.ReadAllText(filePath);

            Newtonsoft.Json.Linq.JArray         jAarray = Newtonsoft.Json.Linq.JArray.Parse(jsonString) as Newtonsoft.Json.Linq.JArray;
            List <FYYK.Model.GridControlHeader> listDataGridViewHeader = jAarray.ToObject <List <FYYK.Model.GridControlHeader> >();

            FYYK.Util.DevGridControlHelper.DynamicGenerateColumns(gridView, listDataGridViewHeader);
        }
Esempio n. 10
0
        //RETURNS ALL BORROWED AFTER DEADLINE
        public async Task <List <Borrowed> > GetFinesForUserAsync(string email)
        {
            var gotFromServer = await service.getClient().GetStringAsync("http://localhost:8543/Borrowed/Fines/" + email);

            Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(gotFromServer);

            List <Borrowed> FinesArray = array.ToObject <List <Borrowed> >();

            foreach (Borrowed fine in FinesArray)
            {
                fine.setFine();
            }

            return(FinesArray);
        }
Esempio n. 11
0
        /// <summary>
        /// GetDataGridViewHeader
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static DataTable GetDataGridViewHeader(string fileName)
        {
            string filePath = string.Format(@"{0}\DataGridViewHeaderJson\{1}.txt", System.Windows.Forms.Application.StartupPath, fileName);

            System.Data.DataTable dt = new DataTable();
            try
            {
                string jsonString = System.IO.File.ReadAllText(filePath);
                Newtonsoft.Json.Linq.JArray    jAarray = Newtonsoft.Json.Linq.JArray.Parse(jsonString) as Newtonsoft.Json.Linq.JArray;
                List <Model.GridControlHeader> listDataGridViewHeader = jAarray.ToObject <List <Model.GridControlHeader> >();
                dt = Util.DataTableHelper.ListToDataTable <Model.GridControlHeader>(listDataGridViewHeader);
                return(dt);
            }catch (Exception ex)
            {
                Log4netUtil.Log4NetHelper.Info(String.Format("GetDataGridViewHeader Json转换成DataTable失败 {0}", ex.Message), @"Exception");
                return(dt);
            }
        }
Esempio n. 12
0
        public T Convert <T>(string contents)
        {
            dynamic result = null;

            try
            {
                if (!string.IsNullOrEmpty(contents))
                {
                    object data = JsonConvert.DeserializeObject(contents);
                    Newtonsoft.Json.Linq.JArray jArray = (Newtonsoft.Json.Linq.JArray)data;
                    result = jArray.ToObject <T>();
                }
            }
            catch (Exception ex)
            {
            }
            return((T)System.Convert.ChangeType(result, typeof(T)));
        }
Esempio n. 13
0
        public static List <CardDefClass> audioLanguagesFromJSONString(String faceJSONData)
        {
            List <CardDefClass> ret = new List <CardDefClass>();

            var JSONData = JsonConvert.DeserializeObject(faceJSONData);

            Newtonsoft.Json.Linq.JArray DataArray = (Newtonsoft.Json.Linq.JArray)JSONData;

            List <CardDefClass> ArrayCards = DataArray.ToObject <List <CardDefClass> >();

            foreach (CardDefClass item in ArrayCards)
            {
                if (item.TYPE == true)
                {
                    ret.Add(item);
                }
            }
            return(ret);
        }
Esempio n. 14
0
        private List <string> GetParameterAsList(Dictionary <string, object> request, string paramName, int size)
        {
            ValidateParamExists(request, paramName);
            Newtonsoft.Json.Linq.JArray paramArray = (Newtonsoft.Json.Linq.JArray)request[paramName];
            List <string> paramList = paramArray.ToObject <List <string> >();

            if (paramList.Count > MaxRequestList)
            {
                throw new ValidationException(OverMaxErrorMessage);
            }

            if (size > 0)
            {
                //validate
                foreach (string param in paramList)
                {
                    ValidateTrytes(paramName, size, param);
                }
            }

            return(paramList);
        }
Esempio n. 15
0
        private Track CreateTrack(Activity activity, List <ActivityStream> streams)
        {
            List <TrackPoint> trackPoints = new List <TrackPoint>();

            var latLngJArray = new Newtonsoft.Json.Linq.JArray(
                streams.First(stream => stream.StreamType == StreamType.LatLng).Data.ToArray()
                );

            var latLngList = latLngJArray.ToObject <List <float[]> >();


            //foreach(var item in latLngJArray)
            //    item.
            //var latLngList = latLngJArray.SelectMany(token => token.Values<float[]>()).ToArray();


            var distanceArray = streams.First(stream => stream.StreamType == StreamType.Distance).Data.Select(obj => (double)obj).ToArray();
            var altitudeArray = streams.First(stream => stream.StreamType == StreamType.Altitude).Data.Select(obj => (double)obj).ToArray();
            var timeArray     = streams.First(stream => stream.StreamType == StreamType.Time).Data.Select(obj => TimeSpan.FromSeconds(Convert.ToDouble(obj))).ToArray();


            for (int i = 0; i < latLngList.Count; i++)
            {
                var latitude  = latLngList[i][0];
                var longitude = latLngList[i][1];
                var distance  = distanceArray[i];
                var altitude  = altitudeArray[i];
                var time      = activity.DateTimeStart + timeArray[i];

                var trackpoint = new TrackPoint(latitude, longitude, altitude, distance, time);

                trackPoints.Add(trackpoint);
            }

            var climbs = new ClimbFinder().Find(trackPoints.ToArray());

            return(new Track(Guid.NewGuid(), trackPoints.ToArray(), climbs));
        }
Esempio n. 16
0
 private static T ReadSql <T>(string name)
 {
     try
     {
         if (Storage.Count == 0)
         {
             if (!File.Exists(cFile))
             {
                 return(default(T));
             }
             string json = GZipHelper.Decompress(File.ReadAllText(cFile));
             if (string.IsNullOrEmpty(json))
             {
                 return(default(T));
             }
             Storage = json.ToObject <Dictionary <string, string> >();
         }
         if (!Storage.ContainsKey(name))
         {
             return(default(T));
         }
         if (typeof(Newtonsoft.Json.Linq.JArray) == Storage[name].GetType())
         {
             Newtonsoft.Json.Linq.JArray ja = (Newtonsoft.Json.Linq.JArray)Storage[name];
             return(ja.ToObject <T>());
         }
         else
         {
             return(Storage[name].ToObject <T>());
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 17
0
        public static List <CardDefClass> faceCardStructureFromJSONString(String faceJSONData)
        {
            List <CardDefClass> ret = new List <CardDefClass>();

            try
            {
                var JSONData = JsonConvert.DeserializeObject(faceJSONData);

                Newtonsoft.Json.Linq.JArray DataArray = (Newtonsoft.Json.Linq.JArray)JSONData;

                List <CardDefClass> ArrayCards = DataArray.ToObject <List <CardDefClass> >();

                foreach (CardDefClass item in ArrayCards)
                {
                    ret.Add(item);
                }
            }
            catch (Exception _ee)
            {
                Console.WriteLine("ERROR:" + _ee.ToString());
            }

            return(ret);
        }
Esempio n. 18
0
        public void OnPostDnaTest()
        {
            if (Test != null)
            {
                var result = new StringBuilder();
                using (var reader = new StreamReader(Test.OpenReadStream()))
                {
                    while (reader.Peek() >= 0)
                    {
                        result.AppendLine(reader.ReadLine());
                    }
                }
                var dna = result;

                if (dna.ToString().Contains(MonGuaChain))
                {
                    Newtonsoft.Json.Linq.JArray tempData = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject((string)TempData["attention"]);
                    patientsAttention             = tempData.ToObject <List <ConsultoryPatients> >();
                    patientsAttention[0].Infected = true;
                }
                TempData["attention"] = JsonConvert.SerializeObject(patientsAttention);
                GetConsultories();
            }
        }
Esempio n. 19
0
        public void Open(object sender, EventArgs e)
        {
            //open project
            OpenFileDialog openFile = new OpenFileDialog();

            openFile.InitialDirectory = VB2projectsPath;
            openFile.Filter           = @"VB3 Project Files|*.vbpx|All Files|*.*";
            openFile.FilterIndex      = 1;
            openFile.RestoreDirectory = true;
            string strFileName = string.Empty;

            //save file name
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                strFileName = openFile.FileName;
            }
            else
            {
                return;
            }
            //Load a project file from disk and then send it out to be unpacked.
            IDictionary <string, IDictionary <string, object> > dictPluginStates = new Dictionary <string, IDictionary <string, object> >();

            StreamReader   streamreader           = new StreamReader(strFileName);
            JsonTextReader jsonreader             = new JsonTextReader(streamreader);
            string         strProjectStateJson    = streamreader.ReadToEnd();
            var            dictPackedProjectState = JsonConvert.DeserializeObject <Dictionary <string, object> >(strProjectStateJson);

            streamreader.Close();
            jsonreader.Close();

            //loop through plugins, deserialize each
            foreach (var plugin in dictPackedProjectState)
            {
                //key in pluginStates dict
                string strPluginKey = plugin.Key;
                //hold value
                Dictionary <string, string> dictJsonRep = new Dictionary <string, string>();
                //hold class type of value
                Dictionary <string, Type> dictObjectType = new Dictionary <string, Type>();
                //hold plugin state with value/class type assigned
                Dictionary <string, object> dictPluginState = new Dictionary <string, object>();
                //store plugin elements as a string for deserializing
                string strPluginStateJson          = plugin.Value.ToString();
                Newtonsoft.Json.Linq.JArray jarray = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(strPluginStateJson);

                //convert jarray to list in order to pull index for value and index for class type
                List <object> listContainer         = jarray.ToObject <List <object> >();
                string        strJsonDictJson       = listContainer[0].ToString();
                string        strObjectTypeDictJson = listContainer[1].ToString();

                //deserialize value and class type of value
                dictJsonRep    = JsonConvert.DeserializeObject <Dictionary <string, string> >(strJsonDictJson);
                dictObjectType = JsonConvert.DeserializeObject <Dictionary <string, Type> >(strObjectTypeDictJson);
                //loop through each pair and deserialize the value to it's class type
                foreach (var pair in dictJsonRep)
                {
                    Type   objType  = dictObjectType[pair.Key];
                    Type   jsonType = objType;
                    string jsonRep  = pair.Value;

                    object objDeserialized = JsonConvert.DeserializeObject(jsonRep, jsonType);
                    //add the newly constructed key value pair, containing correct class types to a dictionary
                    dictPluginState.Add(pair.Key, objDeserialized);
                }
                //add each plugin dictionary
                dictPluginStates.Add(strPluginKey, dictPluginState);
            }
            //raise unpacke event, sending packed plugins dictionary
            signaller.UnpackProjectState(dictPluginStates);
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            useHttp(true);
            port("8080");

            startServerInstance();

            get("/", (body, reponse) => {
                return("Hello World");
            });

            post("/Create/Call", (body, reponse) => {
                ApiCreateCallRequest apiCreateCallRequest = new ApiCreateCallRequest();

                apiCreateCallRequest.To            = body.To;
                apiCreateCallRequest.From          = body.From;
                apiCreateCallRequest.AnswerUrl     = body.AnswerUrl;
                apiCreateCallRequest.ApplicationId = voiceApplicationId;
                try
                {
                    voiceController.CreateCall(voiceAccountId, apiCreateCallRequest);
                }
                catch (APIException ex)
                {
                    throw new HttpStatusAwareException(ex.ResponseCode, ex.Message);
                }


                return("Creates a call");
            });

            post("/Create/Message", (body, reponse) => {
                MessageRequest messageReqeust = new MessageRequest();

                Newtonsoft.Json.Linq.JArray arr = body.To;

                messageReqeust.To            = arr.ToObject <List <string> >();
                messageReqeust.From          = body.From;
                messageReqeust.Text          = body.Text;
                messageReqeust.ApplicationId = msgApplicationId;
                try
                {
                    msgController.CreateMessage(msgApiToken, messageReqeust);
                } catch (APIException ex)
                {
                    throw new HttpStatusAwareException(ex.ResponseCode, ex.Message);
                }

                return("");
            });

            post("/Callbacks/Messaging", (body, reponse) => {
                return("Handle message callback");
            });

            post("/Callbacks/Voice/Outbound", (body, reponse) => {
                return("Handle outboud voice callback");
            });

            post("/Callbacks/Voice/Inbound", (body, reponse) => {
                return("Handle inbound voice callback");
            });

            post("/Bxml", (body, reponse) => {
                Response response           = new Response();
                SpeakSentence speakSentence = new SpeakSentence
                {
                    Sentence = "Hello World!"
                };
                response.Add(speakSentence);

                return(response.ToBXML());
            });

            post("/status", (body, reponse) => {
                string strBody = body;
                return(strBody);
            });

            post("/stop", (body, reponse) => {
                Task.Run(() => {
                    Thread.Sleep(2000);
                    stop();
                });

                return("Server Shutting Down");
            });


            WaitOnServerToStop();
        }
Esempio n. 21
0
        public Collection <Dictionary <string, object> > PAsDictCollection(string name)
        {
            Newtonsoft.Json.Linq.JArray rp = (Newtonsoft.Json.Linq.JArray)stateParameters[name];

            return(rp.ToObject <Collection <Dictionary <string, object> > >());
        }
Esempio n. 22
0
 public void LoadEntities(AbstractScene scene, string levelID)
 {
     foreach (EntityInstance entity in world.ParseLevel(scene, levelID))
     {
         Vector2 position = new Vector2(entity.Px[0], entity.Px[1]);
         if (entity.Identifier.Equals("Hero"))
         {
             hero = new Hero(scene, position);
         }
         else if (entity.Identifier.Equals("Lava"))
         {
             new Lava(scene, (int)entity.Width, (int)entity.Height, position);
         }
         else if (entity.Identifier.Equals("Spikes"))
         {
             Direction dir = default;
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Direction")
                 {
                     dir = Enum.Parse(typeof(Direction), field.Value);
                 }
             }
             float size = entity.Width > entity.Height ? entity.Width : entity.Height;
             new Spikes(scene, position, (int)size, dir);
         }
         else if (entity.Identifier.Equals("Fuel"))
         {
             float amount  = 0;
             bool  gravity = true;
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Amount")
                 {
                     amount = (float)field.Value;
                 }
                 else if (field.Identifier == "HasGravity")
                 {
                     gravity = field.Value;
                 }
             }
             FuelCan can = new FuelCan(scene, position, amount);
             can.HasGravity = gravity;
         }
         else if (entity.Identifier.Equals("EnemyPatrolTrigger"))
         {
             new EnemyPatrolTrigger(scene, (int)entity.Width, (int)entity.Height, position);
         }
         else if (entity.Identifier.Equals("Enemy"))
         {
             Direction dir      = Direction.WEST;
             bool      patrol   = true;
             bool      tutorial = false;
             Newtonsoft.Json.Linq.JArray array = null;
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Direction")
                 {
                     dir = Enum.Parse(typeof(Direction), field.Value);
                 }
                 else if (field.Identifier == "Patrol")
                 {
                     patrol = field.Value;
                 }
                 else if (field.Identifier == "Tutorial")
                 {
                     tutorial = field.Value;
                 }
                 else if (field.Identifier == "CarriedItems")
                 {
                     array = field.Value;
                 }
             }
             List <string> carriedItems = array.ToObject <List <string> >();
             EnemyTest     enemy        = new EnemyTest(scene, position, dir);
             enemy.Patrol   = patrol;
             enemy.Tutorial = tutorial;
             if (carriedItems != null && carriedItems.Count > 0)
             {
                 enemy.CarriedItems = carriedItems;
             }
         }
         else if (entity.Identifier.Equals("Door"))
         {
             bool locked = false;
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Locked")
                 {
                     locked = field.Value;
                 }
             }
             new Door(scene, position, (int)entity.Height, locked);
         }
         else if (entity.Identifier.Equals("MountedGun"))
         {
             Direction dir = default;
             Newtonsoft.Json.Linq.JArray array = null;
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Direction")
                 {
                     dir = Enum.Parse(typeof(Direction), field.Value);
                 }
                 else if (field.Identifier == "Integer")
                 {
                     array = field.Value;
                 }
             }
             List <int> param = array.ToObject <List <int> >();
             new MountedGun(scene, position, dir, param[0], param[1], param[2], param[3]);
         }
         else if (entity.Identifier.Equals("Saw"))
         {
             bool horizontal = false;
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Horizontal")
                 {
                     horizontal = field.Value;
                 }
             }
             new Saw(scene, position, horizontal);
         }
         else if (entity.Identifier.Equals("TrapTrigger"))
         {
             new TrapTrigger(scene, position, (int)entity.Width, (int)entity.Height);
         }
         else if (entity.Identifier.Equals("TutorialTrigger"))
         {
             string tutorial = "";
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Tutorial")
                 {
                     tutorial = field.Value;
                 }
             }
             new TutorialTrigger(scene, position, (int)entity.Width, (int)entity.Height, tutorial);
         }
         else if (entity.Identifier.Equals("Ammo"))
         {
             Type weaponType = null;
             int  amount     = 0;
             foreach (FieldInstance field in entity.FieldInstances)
             {
                 if (field.Identifier == "Weapon")
                 {
                     if (field.Value == "Handgun")
                     {
                         weaponType = typeof(Handgun);
                     }
                     else if (field.Value == "Machinegun")
                     {
                         weaponType = typeof(Machinegun);
                     }
                     else if (field.Value == "Shotgun")
                     {
                         weaponType = typeof(Shotgun);
                     }
                 }
                 else if (field.Identifier == "Amount")
                 {
                     amount = (int)field.Value;
                 }
             }
             new Ammo(scene, position, amount, weaponType);
         }
         else if (entity.Identifier.Equals("HealthPickup"))
         {
             new HealthPickup(scene, position);
         }
         else if (entity.Identifier.Equals("EndGameTrigger"))
         {
             new EndGameTrigger(scene, position, (int)entity.Width, (int)entity.Height);
         }
     }
 }
        public TCPCommand executeCommand(TCPCommand cmd)
        {
            if (cmd == null)
            {
                // null command? Can't do anything with a null command!
                return(null);
            }
            else
            {
                try
                {
                    MethodInfo method = FindMethod(cmd.name, _commandStructure.GetType());
                    if (method == null)
                    {
                        //tcpCommand response = new tcpCommand("__error", null);
                        //response.guid = cmd.guid;
                        //return response;
                        if (cmd.name == "GetName")
                        {
                            TCPCommand resp = new TCPCommand("__response", new List <object> {
                                _linkName
                            });
                            resp.guid = cmd.guid;
                            return(resp);
                        }
                        return(null);
                    }
                    else
                    {
                        object[] args;

                        if (cmd.arguments != null)
                        {
                            args = cmd.arguments.ToArray();
                        }
                        else
                        {
                            args = new object[0];
                        }

                        int idx = 0;
                        foreach (ParameterInfo param in method.GetParameters())
                        {
                            if (args[idx] is Newtonsoft.Json.Linq.JArray)
                            {
                                Newtonsoft.Json.Linq.JArray jArr = (Newtonsoft.Json.Linq.JArray)args[idx];
                                args[idx] = jArr.ToObject(param.ParameterType);
                            }
                            else
                            {
                                args[idx] = Convert.ChangeType(args[idx], param.ParameterType);
                            }
                            idx++;
                        }
                        object retval = method.Invoke(_commandStructure, args);

                        TCPCommand response = new TCPCommand("__response", new List <object> {
                            retval
                        });
                        response.guid = cmd.guid;

                        return(response);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    TCPCommand response = new TCPCommand("__error", null);
                    response.guid = cmd.guid;
                    return(response);
                }
            }
        }
Esempio n. 24
0
        /// <summary>
        /// 对总馆的数据进行添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimedEventBorrow(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                #region   操作sqlsugar
                SqlSugarClient db = new SqlSugarClient(
                    new ConnectionConfig()
                {
                    //ConnectionString = @"server=DESKTOP-FTUFS40\SQLEXPRESS;database=Sy04;uid=sa;pwd=90-=uiop",
                    ConnectionString      = "Data Source=.;Initial Catalog=Sy_DataWallHengDong01;Integrated Security=True",
                    DbType                = SqlSugar.DbType.SqlServer, //设置数据库类型
                    IsAutoCloseConnection = true,                      //自动释放数据务,如果存在事务,在事务结束后释放
                    InitKeyType           = InitKeyType.Attribute      //从实体特性中读取主键自增列信息
                });
                //时间
                var afterTime  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");              //获取到当前的时间
                var beforeTime = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss"); //获取前一小时
                #endregion
                #region  荣桓城北分馆
                string L1 = ConfigurationManager.ConnectionStrings["ShangYe.Data.L1"].ToString().Trim();//获取第一个馆的IP
                //获取第一个馆的设备id,此步骤需要查询第一个馆的数据库,客流设备的ID(切记不能和主馆ID重复)
                #region  第一个ID
                int DeviceID = 2;//设备ID
                var url      = L1 + "QuqeryList?SysCustDeviceId=" + DeviceID + "&beforeTime=" + beforeTime + "&afterTime=" + afterTime;
                //获取返回的结果集
                var        result = HttpClient.Get(url);
                JsonReader reader = new JsonTextReader(new StringReader(result));
                var        resp   = "";
                while (reader.Read())
                {
                    resp = reader.Value.ToString();
                }
                if (resp != "[]")
                {
                    Newtonsoft.Json.Linq.JArray userAarray1   = Newtonsoft.Json.Linq.JArray.Parse(resp) as Newtonsoft.Json.Linq.JArray;
                    List <SysCustData>          userListModel = userAarray1.ToObject <List <SysCustData> >();
                    foreach (var cus in userListModel)
                    {
                        var datas = new SysCustData()
                        {
                            SysCustDeviceId = DeviceID,                       //设备ID
                            D_Date          = Convert.ToDateTime(cus.D_Date), //时间
                            D_InNum         = Convert.ToInt32(cus.D_InNum),   //进馆人次
                            D_OutNum        = Convert.ToInt32(cus.D_OutNum),  //出馆人次
                        };
                        db.Insertable(datas).InsertColumns(it => new { it.SysCustDeviceId, it.D_Date, it.D_InNum, it.D_OutNum }).ExecuteReturnIdentity();
                    }
                    LogHelper.InfoLog("荣桓分馆设备ID" + DeviceID + "|时间从" + beforeTime + "开始|到" + afterTime + "结束");
                }
                #endregion

                #region  第二个ID
                int DeviceIDA = 7;//设备ID
                var urlA      = L1 + "QuqeryList?SysCustDeviceId=" + DeviceIDA + "&beforeTime=" + beforeTime + "&afterTime=" + afterTime;
                //获取返回的结果集
                var        resultA = HttpClient.Get(urlA);
                JsonReader readerA = new JsonTextReader(new StringReader(resultA));
                var        respA   = "";
                while (readerA.Read())
                {
                    respA = readerA.Value.ToString();
                }
                if (respA != "[]")
                {
                    Newtonsoft.Json.Linq.JArray userAarray1A   = Newtonsoft.Json.Linq.JArray.Parse(respA) as Newtonsoft.Json.Linq.JArray;
                    List <SysCustData>          userListModelA = userAarray1A.ToObject <List <SysCustData> >();
                    foreach (var cusA in userListModelA)
                    {
                        var datasA = new SysCustData()
                        {
                            SysCustDeviceId = DeviceIDA,                       //设备ID
                            D_Date          = Convert.ToDateTime(cusA.D_Date), //时间
                            D_InNum         = Convert.ToInt32(cusA.D_InNum),   //进馆人次
                            D_OutNum        = Convert.ToInt32(cusA.D_OutNum),  //出馆人次
                        };
                        db.Insertable(datasA).InsertColumns(it => new { it.SysCustDeviceId, it.D_Date, it.D_InNum, it.D_OutNum }).ExecuteReturnIdentity();
                    }
                    LogHelper.InfoLog("荣桓分馆设备ID" + DeviceIDA + "|时间从" + beforeTime + "开始|到" + afterTime + "结束");
                }
                #endregion
                #endregion

                #region  荣桓24小时分馆1
                //获取第一个馆的IP
                string L2 = ConfigurationManager.ConnectionStrings["ShangYe.Data.L2"].ToString().Trim();
                //获取第一个馆的设备id,此步骤需要查询第一个馆的数据库,客流设备的ID(切记不能和主馆ID重复)
                #region  第一个ID
                int DeviceID2 = 4;//设备ID
                var url2      = L2 + "QuqeryList?SysCustDeviceId=" + DeviceID2 + "&beforeTime=" + beforeTime + "&afterTime=" + afterTime;
                //获取返回的结果集
                var        result2 = HttpClient.Get(url2);
                JsonReader reader2 = new JsonTextReader(new StringReader(result2));
                var        resp2   = "";
                while (reader2.Read())
                {
                    resp2 = reader2.Value.ToString();
                }
                if (resp2 != "[]")
                {
                    Newtonsoft.Json.Linq.JArray userAarray2   = Newtonsoft.Json.Linq.JArray.Parse(resp2) as Newtonsoft.Json.Linq.JArray;
                    List <SysCustData>          userListMode2 = userAarray2.ToObject <List <SysCustData> >();
                    foreach (var cus2 in userListMode2)
                    {
                        var datas2 = new SysCustData()
                        {
                            SysCustDeviceId = DeviceID2,                       //设备ID
                            D_Date          = Convert.ToDateTime(cus2.D_Date), //时间
                            D_InNum         = Convert.ToInt32(cus2.D_InNum),   //进馆人次
                            D_OutNum        = Convert.ToInt32(cus2.D_OutNum),  //出馆人次
                        };
                        db.Insertable(datas2).InsertColumns(it => new { it.SysCustDeviceId, it.D_Date, it.D_InNum, it.D_OutNum }).ExecuteReturnIdentity();
                    }
                    LogHelper.InfoLog("24小时1馆ID" + DeviceID2 + "|时间从" + beforeTime + "开始|到" + afterTime + "结束");
                }
                #endregion
                #endregion

                #region  荣桓24小时分馆3
                //获取第一个馆的IP
                string L3 = ConfigurationManager.ConnectionStrings["ShangYe.Data.L3"].ToString().Trim();
                //获取第一个馆的设备id,此步骤需要查询第一个馆的数据库,客流设备的ID(切记不能和主馆ID重复)
                #region  第一个ID
                int DeviceID3 = 6;//设备ID
                var url3      = L3 + "QuqeryList?SysCustDeviceId=" + DeviceID3 + "&beforeTime=" + beforeTime + "&afterTime=" + afterTime;
                //获取返回的结果集
                var        result3 = HttpClient.Get(url3);
                JsonReader reader3 = new JsonTextReader(new StringReader(result3));
                var        resp3   = "";
                while (reader3.Read())
                {
                    resp3 = reader3.Value.ToString();
                }
                if (resp3 != "[]")
                {
                    Newtonsoft.Json.Linq.JArray userAarray3   = Newtonsoft.Json.Linq.JArray.Parse(resp3) as Newtonsoft.Json.Linq.JArray;
                    List <SysCustData>          userListMode3 = userAarray3.ToObject <List <SysCustData> >();
                    foreach (var cus3 in userListMode3)
                    {
                        var datas3 = new SysCustData()
                        {
                            SysCustDeviceId = DeviceID3,                       //设备ID
                            D_Date          = Convert.ToDateTime(cus3.D_Date), //时间
                            D_InNum         = Convert.ToInt32(cus3.D_InNum),   //进馆人次
                            D_OutNum        = Convert.ToInt32(cus3.D_OutNum),  //出馆人次
                        };
                        db.Insertable(datas3).InsertColumns(it => new { it.SysCustDeviceId, it.D_Date, it.D_InNum, it.D_OutNum }).ExecuteReturnIdentity();
                    }
                    LogHelper.InfoLog("24小时2馆ID" + DeviceID3 + "|时间从" + beforeTime + "开始|到" + afterTime + "结束");
                }
                #endregion
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("错误原因:" + ex.Message + "错误位置:" + ex.StackTrace);
            }
        }