Inheritance: MonoBehaviour
Exemple #1
0
 public BasePage()
 {
     if (unity == null)
     {
         unity = new UnityContext();
     }
 }
        public ActionResult SayStatus(string password, bool isOnline)
        {
            if (password != WebConstants.WebPassword)
            {
                return new ContentResult {
                           Content = "password fail"
                }
            }
            ;
            var context = new UnityContext();
            var status  = context.UnityStatus.First();

            if (status.Online == isOnline)
            {
                return new ContentResult {
                           Content = "already know!"
                }
            }
            ;
            status.Online = isOnline;
            if (isOnline)
            {
                status.UpTime = WebConstants.GetCurrentTime();
            }
            context.SaveChanges();
            return(new ContentResult {
                Content = "successful"
            });
        }
Exemple #3
0
        public ActionResult Register(RegisterModel model)
        {
            if (!WebConstants.IsRegistrationAvailable)
            {
                return(View());
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // Attempt to register the user
            try
            {
                if (!RegisterModel.IsCorrectUserName(model.UserName))
                {
                    ViewBag.Message =
                        "В имени пользователя допустимы только рус/англ буквы, точка, пробел, земля и дефис.";
                    return(View(model));
                }
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
                var context = new UnityContext();
                context.UserProfiles.First(z => z.UserName == model.UserName).CvarcTag = Guid.NewGuid().ToString();
                context.SaveChanges();
                WebSecurity.Login(model.UserName, model.Password);
                return(RedirectToAction("Index", "Home"));
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        void BuildEntitiesFromScene(UnityContext contextHolder)
        {
            //An EntityDescriptorHolder is a special Svelto.ECS class created to exploit
            //GameObjects to dynamically retrieve the Entity information attached to it.
            //Basically a GameObject can be used to hold all the information needed to create
            //an Entity and later queries to build the entitity itself.
            //This allow to trigger a sort of polyformic code that can be re-used to
            //create several type of entities.

            IEntityDescriptorHolder[] entities = contextHolder.GetComponentsInChildren <IEntityDescriptorHolder>();

            //However this common pattern in Svelto.ECS application exists to automatically
            //create entities from gameobjects already presented in the scene.
            //I still suggest to avoid this method though and create entities always
            //manually. Basically EntityDescriptorHolder should be avoided
            //whenver not strictly necessary.

            for (int i = 0; i < entities.Length; i++)
            {
                var entityDescriptorHolder = entities[i];
                var entityDescriptor       = entityDescriptorHolder.RetrieveDescriptor();
                _entityFactory.BuildEntity
                    (((MonoBehaviour)entityDescriptorHolder).gameObject.GetInstanceID(),
                    entityDescriptor,
                    (entityDescriptorHolder as MonoBehaviour).GetComponentsInChildren <IImplementor>());
            }
        }
Exemple #5
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            Database.SetInitializer <UnityContext>(new InitUnityDb());

            //initialize now
            //это позволяет отлавливать ошибки с БД сразу же, а не потом.
            var context = new UnityContext(false);

            // опасный трай. если вдруг на сервере сработает -- вся база умрет.
            // наверное.
            // но без этого локальная не работает.
            // файл с бд отсутствует, а база данных почему-то есть.
            // ниже строчка с дропом должна быть всегда закомментирована в гите на всякий случай.
            // при необходимости запустить локально -- у себя локально раскомментировать.
            // это лучшее решение, которое я придумал
            try
            {
                context.UnityStatus.ToArray();
            }
            catch (DataException)
            {
                //context.Database.Delete();
                context = new UnityContext(false);
                context.UnityStatus.ToArray();
            }
        }
Exemple #6
0
        public override void Read(UnityReader reader, UnityContext context, JObject currentObject)
        {
            JArray current = new JArray();

            currentObject[FieldName] = current;

            int count = reader.ReadInt32();

            if (TemplateTypeName != null)
            {
                var template = context.TypeTable[TemplateTypeName];
                for (int i = 0; i < count; i++)
                {
                    JObject instance = new JObject();
                    current.Add(instance);
                    template.Read(reader, context, instance);
                }
            }
            else
            {
                for (int i = 0; i < count; i++)
                {
                    JObject instance = new JObject();
                    current.Add(instance);
                    ReadChildren(reader, context, instance);
                }
            }
        }
Exemple #7
0
        public ActionResult DeleteGamesByFilter(FormCollection collection)
        {
            var    gameContext    = new UnityContext();
            var    contextChanged = false;
            double minutesToDelete;

            if (double.TryParse(collection["Time"], out minutesToDelete))
            {
                var timeToDeleteFrom    = WebConstants.GetCurrentTime() - TimeSpan.FromMinutes(minutesToDelete);
                var gamesToDeleteByTime = gameContext.GameResults.Where(r => r.Time > timeToDeleteFrom).ToArray();
                contextChanged = gamesToDeleteByTime.Length > 0;
                foreach (var game in gamesToDeleteByTime)
                {
                    gameContext.GameResults.Remove(game);
                }
            }

            string tag           = collection["Tag"];
            string subtag        = collection["Subtag"];
            var    gamesToDelete = string.IsNullOrEmpty(subtag)
                ? gameContext.GameResults.Where(r => r.Type == tag).ToArray()
                : gameContext.GameResults.Where(r => r.Type == tag && r.Subtype == subtag).ToArray();

            contextChanged = contextChanged || gamesToDelete.Length > 0;
            foreach (var game in gamesToDelete)
            {
                gameContext.GameResults.Remove(game);
            }
            if (contextChanged)
            {
                gameContext.SaveChanges();
            }
            return(View());
        }
Exemple #8
0
        public ActionResult GetAllUsers()
        {
            var context = new UnityContext();
            var users   = context.UserProfiles.ToArray();

            return(View(users));
        }
Exemple #9
0
        public static void SendEmail(string email, string subject, string body)
        {
            try
            {
                var unity         = new UnityContext();
                var configService = unity.GetInstance <IConfigService>();


                var cfg = configService.GetConfig(1);

                var smtp = new SmtpClient();

                smtp.Host = cfg.GetValue("host");
                smtp.Port = cfg.GetValue("port").TryParseToInt32();
                smtp.UseDefaultCredentials = false;
                smtp.EnableSsl             = "ssl".Equals(cfg.GetValue("secure")) ? true : false;

                System.Net.NetworkCredential nc = new System.Net.NetworkCredential(cfg.GetValue("username"), cfg.GetValue("password"));
                smtp.Credentials = nc.GetCredential(smtp.Host, smtp.Port, "NTLM");

                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

                smtp.Send(cfg.GetValue("email"), email, subject, body);
            }
            catch (Exception ex)
            {
                Logger.GetLogger().Error("发送邮件出错\n", ex);
            }
        }
Exemple #10
0
        public bool SendOrder(string mobile, string subname, string orderid)
        {
            string msg = string.Format("【巨店网】您出售的店铺[{0}]买家已经付款,如有疑问请联系选猫网", subname);

            var unity = new UnityContext();

            var orderService = unity.GetInstance <IOrderService>();

            var order = orderService.GetOrder(orderid);

#if !DEBUG
            if (order != null && order.Send_Mail != 1 && order.Mobile.Equals(mobile))
            {
                if (SendText(mobile, msg))
                {
                    order.Send_Mail = 1;
                    orderService.Modify(order);

                    return(true);
                }
            }
#endif

#if DEBUG
            if (SendText(mobile, msg))
            {
                return(true);
            }
#endif

            return(false);
        }
 public Interfaces.Contexts.Context CreateContext()
 {
     Builder builder = new UnityBuilder();
       Container container = new HashContainer();
       Context ctx = new UnityContext(builder, container);
       return ctx;
 }
        static UnityHandlerFactory()
        {
            //初始化UnityContainer
            var unityContext = new UnityContext();

            unityContainer = unityContext.GetUnityContainer();
        }
        public ActionResult UploadSolution(SimpleFileView simpleFileView)
        {
            if (!Directory.Exists(WebConstants.BasePath + WebConstants.RelativeSolutionsPath))
            {
                Directory.CreateDirectory(WebConstants.BasePath + WebConstants.RelativeSolutionsPath);
            }
            if (simpleFileView.UploadedFile == null)
            {
                ViewBag.Message = "Ошибка: Выберете файл для загрузки!";
                return(View(simpleFileView));
            }
            if (simpleFileView.UploadedFile.ContentLength > 7 * 512 * 1024) // 3.5 MB
            {
                ViewBag.Message = "Ошибка: Файл слишком большой! Максимальный размер 3.5 МБ. Попробуйте удалить все бинарные файлы из архива.";
                return(View(simpleFileView));
            }
            var path      = WebConstants.BasePath + WebConstants.RelativeSolutionsPath;
            var extention = simpleFileView.UploadedFile.FileName.Split('.').Last();

            if (extention != "zip")
            {
                ViewBag.Message = "Ошибка: вы должны предоставить архив с решением в формате *.zip";
                return(View(simpleFileView));
            }
            var expectedFileName = User.Identity.Name + "." + extention;

            simpleFileView.UploadedFile.SaveAs(path + expectedFileName);
            var context = new UnityContext();

            context.UserProfiles.First(u => u.UserName == User.Identity.Name).SolutionLoaded = WebConstants.GetCurrentTime();
            context.SaveChanges();
            ViewBag.Message = "Решение было загружено успешно!";
            return(View(simpleFileView));
        }
Exemple #14
0
        public override UnityContext GetUnityContext()
        {
            UnityContext unityContext = new UnityContext();

            HardwareInfo hardwareInfo = this.GetOSHardwareInfo();

            if (hardwareInfo != null)
            {
                if (hardwareInfo.Version != null)
                {
                    String deviceModel = hardwareInfo.Version;
                    if (deviceModel.IndexOf("iPad") >= 0)
                    {
                        unityContext.iPad = true;
                    }
                    else if (deviceModel.IndexOf("iPhone") >= 0)
                    {
                        unityContext.iPhone = true;
                    }
                    else if (deviceModel.IndexOf("iPod") >= 0)
                    {
                        unityContext.iPod = true;
                    }
                }
            }

            return(unityContext);
        }
Exemple #15
0
 protected void ReadChildren(UnityReader reader, UnityContext context, JObject currentObject)
 {
     foreach (SerializationNode node in Nodes)
     {
         node.Read(reader, context, currentObject);
     }
 }
Exemple #16
0
        void ICompositionRoot.OnContextCreated(UnityContext contextHolder)
        {
            var tasksCount = NumberOfEntities.value;

#if FIRST_TIER_EXAMPLE || SECOND_TIER_EXAMPLE || THIRD_TIER_EXAMPLE
            var boidDescriptor = new BoidEntityDescriptor(new[] { new Boid() });
#else
            var boidDescriptor = new BoidEntityDescriptor();
#endif
#if DONT_TRY_THIS_AT_HOME
            for (int i = 0; i < tasksCount; i++)
            {
                GameObject crazyness = new GameObject();
                crazyness.AddComponent <UnityWay>();
            }
#else
            IEnginesRoot   enginesRoot;
            IEntityFactory entityFactory = (enginesRoot = new EnginesRoot(new UnitySumbmissionNodeScheduler())) as IEntityFactory;

            var boidsEngine = new BoidsEngine();
            enginesRoot.AddEngine(boidsEngine);
            _contextNotifier.AddFrameworkDestructionListener(boidsEngine);

            for (int i = 0; i < tasksCount; i++)
            {
                entityFactory.BuildEntity(i, boidDescriptor);
            }

            entityFactory.BuildEntity(0, new GenericEntityDescriptor <PrintTimeNode>(contextHolder.GetComponentInChildren <PrintIteration>()));
#endif
        }
Exemple #17
0
        public override void Read(UnityReader reader, UnityContext context, JObject currentObject)
        {
            JObject current = new JObject();

            //Add early to faults show progress
            currentObject[FieldName] = current;
            ReadChildren(reader, context, currentObject);
        }
        public void OnContextCreated(UnityContext contextHolder)
        {
//            var prefabsDictionary = new PrefabsDictionary(Application.persistentDataPath + "/prefabs.json");

            BuildEntitiesFromScene(contextHolder);
//            BuildPlayerEntities(prefabsDictionary);
//            BuildNetworkEntities(prefabsDictionary);
        }
 public void Init()
 {
     if (!UseUnityContextClock)
     {
         _clock = new Clock();
     }
     Blackboard = new Blackboard(UseUnityContextClock ? UnityContext.GetClock() : _clock);
 }
Exemple #20
0
 public void OnContextCreated(UnityContext contextHolder)
 {
     IEntityDescriptorHolder[] entities = contextHolder.GetComponentsInChildren <IEntityDescriptorHolder>();
     for (int i = 0; i < entities.Length; i++)
     {
         _entityFactory.BuildEntity((entities[i] as MonoBehaviour).gameObject.GetInstanceID(), entities[i].BuildDescriptorType());
     }
 }
Exemple #21
0
 private Context defaultContext()
 {
     Builder builder = new UnityBuilder();
     Container container = new HashContainer();
     container.Register(typeof(Log), typeof(LogTest));
     Context context = new UnityContext(builder, container);
     return context;
 }
Exemple #22
0
 public void Refresh()
 {
     if (this.IsLogged)
     {
         var unity = new UnityContext();
         var svr   = unity.GetInstance <IUserService>();
         Context.Session[KEY_SESSION] = svr.GetUser(this.DisplayName);
     }
 }
 void OnDisable()
 {
     if (unityContext != null && updateCycleCoroutine != null)
     {
         unityContext.StopCoroutine(updateCycleCoroutine);
     }
     updateCycleCoroutine = null;
     unityContext         = null;
 }
Exemple #24
0
 protected void Awake()
 {
     sharedBlackboard = UnityContext.GetSharedBlackboard("sharedbb");
     blackboard       = new Blackboard(sharedBlackboard, UnityContext.GetClock());
     RegisterToSharedBlackboard();
     mailbox                = new Mailbox(this);
     canCheckMailbox        = true;
     awaitingReconfirmation = false;
 }
Exemple #25
0
    public GameTimer(float interval, Action onFinish, bool loop = false)
    {
        _interval = interval;
        _timer    = 0f;

        _onFinish = onFinish;
        _loop     = loop;

        UnityContext.AddUpdateAction(Update);
    }
        /// <summary>
        /// This is a standard approach to create Entities from already existing GameObject in the scene
        /// It is absolutely not necessary, but convienent in case you prefer this way
        /// </summary>
        /// <param name="contextHolder"></param>
        void ICompositionRoot.OnContextCreated(UnityContext contextHolder)
        {
            var prefabsDictionary = new PrefabsDictionary(Application.persistentDataPath + "/prefabs.json");

            BuildEntitiesFromScene(contextHolder);
            //Entities can also be created dynamically in run-time
            //using the entityFactory; You can, if you wish, create
            //starting entities here.
            BuildPlayerEntities(prefabsDictionary);
            BuildCameraEntity();
        }
Exemple #27
0
        private void SetupCamera(UnityContext contextHolder)
        {
            CameraEntityDescriptorHolder cameraEntityDescriptor = contextHolder.GetComponentInChildren <CameraEntityDescriptorHolder>();
            EntityDescriptorInfo         entityDescriptor       = cameraEntityDescriptor.RetrieveDescriptor();

            _EntityFactory.BuildEntity(
                cameraEntityDescriptor.gameObject.GetInstanceID(),
                entityDescriptor,
                cameraEntityDescriptor.GetComponentsInChildren <IImplementor>()
                );
        }
Exemple #28
0
        public UnitOfWork(IUnityContext context)
        {
            this._context = context as UnityContext ?? new UnityContext();

            this._objectContext = ((IObjectContextAdapter)this._context).ObjectContext;

            if (this._objectContext.Connection.State != ConnectionState.Open)
            {
                this._objectContext.Connection.Open();
                this._transaction = _objectContext.Connection.BeginTransaction();
            }
        }
        void BuildBonusSpawnerEntity(UnityContext contextHolder)
        {
            var spawners = contextHolder.GetComponentsInChildren <BonusSpawnerImplementor>();


            foreach (var spawner in spawners)
            {
                List <IImplementor> implementors = new List <IImplementor>();
                spawner.GetComponents(implementors);
                _entityFactory.BuildEntity <BonusSpawnerEntityDescriptor>(spawner.GetInstanceID(), implementors.ToArray());
            }
        }
Exemple #30
0
        public ActionResult RecreateCvarcTag()
        {
            if (!WebConstants.IsRecreateTagAvailable)
            {
                return(RedirectToAction("Manage", new { Message = ManageMessageId.RecreateCvarcTagFail }));
            }
            var context = new UnityContext();

            context.UserProfiles.First(u => u.UserName == User.Identity.Name).CvarcTag = Guid.NewGuid().ToString();
            context.SaveChanges();
            return(RedirectToAction("Manage", new { Message = ManageMessageId.RecreateCvarcTagSuccess }));
        }
Exemple #31
0
        private void BuildGridFromScene(UnityContext unityContext, IEntityFactory entityFactory)
        {
            var entities = unityContext.GetComponentsInChildren <IEntityDescriptorHolder>();

            foreach (var entityHolder in entities)
            {
                entityFactory.BuildEntity(
                    new EGID((uint)((MonoBehaviour)entityHolder).gameObject.GetInstanceID(), EcsGroups.GridGroup),
                    entityHolder.GetDescriptor(),
                    ((MonoBehaviour)entityHolder).GetComponents <IImplementor>()
                    );
            }
        }
Exemple #32
0
    public void OnContextCreated(UnityContext contextHolder)
    {
        //inject all the gameobjects in the scene child of the GameContext
        foreach (UnityEngine.Transform transform in contextHolder.transform)
        {
            var monobehaviours = transform.GetComponentsInChildren <UnityEngine.MonoBehaviour>();

            for (int i = 0; i < monobehaviours.Length; i++)
            {
                container.Inject(monobehaviours[i]);
            }
        }
    }