Пример #1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    //Assign Role to user Here
                    await this.UserManager.AddToRoleAsync(user.Id, model.SelectedUserRole);

                    // end here
                    return(RedirectToAction("Index", "Home"));
                }
                var myHelper = new ControllersHelper();
                model.UserRoles = myHelper.GetRolesForUser(context, UserManager);

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #2
0
        public ActionResult Edit([Bind(Include = "ProductId,Name,ProductCategoryId,Price,Quantity,Description,ImagePath,ImageName,IsChangeImage")] ProductViewModel productViewModel)
        {
            if (ModelState.IsValid)
            {
                var imagePath = productViewModel.ImageName;
                if (productViewModel.IsChangeImage)
                {
                    var myHelper = new ControllersHelper();
                    imagePath = myHelper.SaveFile(productViewModel.ImagePath, ModelState, Server);
                }

                Product product = new Product
                {
                    ProductId         = productViewModel.ProductId,
                    Name              = productViewModel.Name,
                    Description       = productViewModel.Description,
                    Price             = productViewModel.Price,
                    Quantity          = productViewModel.Quantity,
                    ProductCategoryId = productViewModel.ProductCategoryId,
                    ImagePath         = imagePath
                };
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.ProductCategoryId = new SelectList(db.ProductCategory, "ProductCategoryId", "Name", productViewModel.ProductCategoryId);
            return(View(productViewModel));
        }
Пример #3
0
        public JToken Read([FromUri] ulong handle, [FromUri] BerkeleyDbOperation operation, [FromUri] BerkeleyDbMultiple multiple, [FromUri] int size, [FromBody] Byte[] key)
        {
            DbcHandle dbc = GetDbc(handle);

            if (key == null)
            {
                key = new Byte[size];
            }
            Byte[] value = new Byte[size];
            int    keySize, valueSize;

            BerkeleyDbError error = dbc.Methods.Get(dbc.Handle, key, value, operation, multiple, out keySize, out valueSize);

            if (error == BerkeleyDbError.DB_BUFFER_SMALL)
            {
                if (key.Length < keySize)
                {
                    key = new Byte[keySize];
                }
                if (value.Length < valueSize)
                {
                    value = new Byte[valueSize];
                }

                error = dbc.Methods.Get(dbc.Handle, key, value, operation, multiple, out keySize, out valueSize);
            }

            return(ControllersHelper.CreateJTokenObject(error, key, value, keySize, valueSize));
        }
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            IHttpController instance =
                ControllersHelper.IsUmbracoController(controllerType)
                  ? this._defaultHttpControllerActivator.Create(request, controllerDescriptor, controllerType)
                  : StructuremapMvc.StructureMapDependencyScope.GetInstance(controllerType) as IHttpController;

            return(instance);
        }
Пример #5
0
        public JToken ReadPartial([FromUri] ulong handle, [FromUri] int valueOffset, [FromUri] int size, [FromBody] Byte[] key)
        {
            DbcHandle dbc = GetDbc(handle);

            Byte[] value = new Byte[size];
            int    valueSize;
            var    error = dbc.Methods.GetPartial(dbc.Handle, key, value, valueOffset, out valueSize);

            return(ControllersHelper.CreateJTokenObject(error, null, value, 0, valueSize));
        }
Пример #6
0
        public ActionResult Register()
        {
            var myHelper            = new ControllersHelper();
            RegisterViewModel model = new RegisterViewModel
            {
                UserRoles        = myHelper.GetRolesForUser(context, UserManager),
                SelectedUserRole = RoleConstants.Client
            };

            return(View(model));
        }
Пример #7
0
        /// <summary>
        /// Get all the users
        /// </summary>
        // GET api/users
        public IEnumerable <UserViewModel> Get()
        {
            List <ApplicationUser> appUsers      = db.Users.ToList();
            List <UserViewModel>   userViewModel = new List <UserViewModel>();

            foreach (ApplicationUser appUser in appUsers)
            {
                var myHelper = new ControllersHelper();
                userViewModel.Add(myHelper.GetUserViewModel(appUser, db, UserManager));
            }
            return(userViewModel);
        }
Пример #8
0
        // GET: Users
        public ActionResult Index()
        {
            List <ApplicationUser> appUsers = db.Users.ToList();
            List <UserViewModel>   model    = new List <UserViewModel>();

            foreach (ApplicationUser appUser in appUsers)
            {
                var myHelper = new ControllersHelper();
                model.Add(myHelper.GetUserViewModel(appUser, db, UserManager));
            }
            return(View(model));
        }
        public void TriggerFeedback()
        {
            PTTOption option = _config.PushToTalkButton;

            if (option.HasFlag(PTTOption.LeftGrip) || option.HasFlag(PTTOption.LeftTrigger))
            {
                ControllersHelper.TriggerShortRumble(XRNode.LeftHand);
            }
            if (option.HasFlag(PTTOption.RightGrip) || option.HasFlag(PTTOption.RightTrigger))
            {
                ControllersHelper.TriggerShortRumble(XRNode.RightHand);
            }
        }
Пример #10
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,Email,UserName,SelectedRoleName,NewPassword,OldPassword,ConfirmPassword")]
                                              UserViewModel model)
        {
            var myHelper = new ControllersHelper();

            if (!ModelState.IsValid)
            {
                model.RoleChoices = db.Roles.Select(r => new SelectListItem {
                    Value = r.Name, Text = r.Name
                }).ToList();
                model.SelectedRoleName = UserManager.GetRoles(model.Id).FirstOrDefault();
                return(View(model));
            }
            var result = await UserManager.ChangePasswordAsync(model.Id, model.OldPassword, model.NewPassword);

            if (result.Succeeded)
            {
                var user = await UserManager.FindByIdAsync(model.Id);

                if (user != null)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }

                var roles = await UserManager.GetRolesAsync(model.Id);

                IdentityResult resultRole = await UserManager.RemoveFromRolesAsync(model.Id, roles.ToArray());

                if (resultRole.Succeeded)
                {
                    // add role
                    await this.UserManager.AddToRoleAsync(user.Id, model.SelectedRoleName);

                    user.UserName = model.UserName;
                    user.Email    = model.Email;
                    IdentityResult resultUser = UserManager.Update(user);
                    if (resultUser.Succeeded)
                    {
                        return(RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }));
                    }
                }
            }
            model.RoleChoices = db.Roles.Select(r => new SelectListItem {
                Value = r.Name, Text = r.Name
            }).ToList();
            model.SelectedRoleName = UserManager.GetRoles(model.Id).FirstOrDefault();
            AddErrors(result);
            return(View(model));
        }
Пример #11
0
        //
        // GET: /Manage/ChangeInformation
        public ActionResult ChangeInformation()
        {
            var myHelper = new ControllersHelper();
            var userId   = User.Identity.GetUserId();
            var user     = context.Users.Where(u => u.Id == userId).FirstOrDefault();
            ChangeInformationViewModel model = new ChangeInformationViewModel
            {
                SelectedUserRole = UserManager.GetRoles(User.Identity.GetUserId()).FirstOrDefault(),
                UserName         = user.UserName,
                Email            = user.Email,
                UserRoles        = myHelper.GetRolesForUser(context, UserManager, User)
            };

            return(View(model));
        }
Пример #12
0
        public ActionResult DeleteConfirmed(string id)
        {
            ApplicationUser appUser = db.Users.Where(u => u.Id == id).FirstOrDefault();
            var             isPurchaseForClientExists = onlineShopDB.Purchase.Any(p => p.ClientId == appUser.Id);

            if (isPurchaseForClientExists)
            {
                ModelState.AddModelError("", "Error! An error has occured. May be related to a Purchase associated with this Client.");
                var myHelper = new ControllersHelper();
                return(View(myHelper.GetUserViewModel(appUser, db, UserManager)));
            }
            db.Users.Remove(appUser);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #13
0
        /// <summary>
        /// Get an user by id
        /// </summary>
        // GET api/users/5
        public IHttpActionResult Get(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(NotFound());
            }
            ApplicationUser appUser = db.Users.Where(u => u.Id == id).FirstOrDefault();

            if (appUser == null)
            {
                return(NotFound());
            }
            var myHelper = new ControllersHelper();

            return(Ok(myHelper.GetUserViewModel(appUser, db, UserManager)));
        }
Пример #14
0
        // GET: Users/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ApplicationUser appUser = db.Users.Where(u => u.Id == id).FirstOrDefault();

            if (appUser == null)
            {
                return(HttpNotFound());
            }
            var myHelper = new ControllersHelper();

            return(View(myHelper.GetUserViewModel(appUser, db, UserManager)));
        }
Пример #15
0
        protected override object DoGetInstance(Type serviceType, string key)
        {
            IContainer container = (CurrentNestedContainer ?? Container);

            if (ControllersHelper.IsUmbracoController(serviceType))
            {
                return(Activator.CreateInstance(serviceType) as IHttpController);
            }
            if (string.IsNullOrEmpty(key))
            {
                return(serviceType.IsAbstract || serviceType.IsInterface
                   ? container.TryGetInstance(serviceType)
                   : container.GetInstance(serviceType));
            }
            return(container.GetInstance(serviceType, key));
        }
        public ActionResult Create([Bind(Include = "ProductCategoryId,Name,Description,ImagePath")] ProductCategoryViewModel productCategoryViewModel)
        {
            if (ModelState.IsValid)
            {
                var myHelper  = new ControllersHelper();
                var imagePath = myHelper.SaveFile(productCategoryViewModel.ImagePath, ModelState, Server);

                ProductCategory productCategory = new ProductCategory
                {
                    Name        = productCategoryViewModel.Name,
                    Description = productCategoryViewModel.Description,
                    ImagePath   = imagePath
                };
                db.ProductCategory.Add(productCategory);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(productCategoryViewModel));
        }
Пример #17
0
        public async Task <ActionResult> ChangeInformation(ChangeInformationViewModel model)
        {
            var myHelper = new ControllersHelper();

            if (!ModelState.IsValid)
            {
                model.UserRoles        = myHelper.GetRolesForUser(context, UserManager, User);
                model.SelectedUserRole = UserManager.GetRoles(User.Identity.GetUserId()).FirstOrDefault();
                return(View(model));
            }
            IdentityResult resultUser = null;
            var            user       = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user != null)
            {
                user.UserName = model.UserName;
                user.Email    = model.Email;
                resultUser    = UserManager.Update(user);
                if (resultUser.Succeeded)
                {
                    // roles delete
                    var roles = await UserManager.GetRolesAsync(User.Identity.GetUserId());

                    IdentityResult resultRole = await UserManager.RemoveFromRolesAsync(User.Identity.GetUserId(), roles.ToArray());

                    if (resultRole.Succeeded)
                    {
                        // add role
                        await this.UserManager.AddToRoleAsync(user.Id, model.SelectedUserRole);

                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeInformationSuccess }));
                    }
                }
            }
            model.UserRoles        = myHelper.GetRolesForUser(context, UserManager, User);
            model.SelectedUserRole = UserManager.GetRoles(User.Identity.GetUserId()).FirstOrDefault();
            AddErrors(resultUser);
            return(View(model));
        }
Пример #18
0
        /// <summary>
        /// Update a given user
        /// </summary>
        // PUT api/users/5
        public async Task <HttpResponseMessage> Put(string id, [FromBody] UserViewModel userViewModel)
        {
            var myHelper = new ControllersHelper();

            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Not found key");
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
            var result = await UserManager.ChangePasswordAsync(id, userViewModel.OldPassword, userViewModel.NewPassword);

            if (result.Succeeded)
            {
                var user = await UserManager.FindByIdAsync(id);

                if (user == null)
                {
                    ModelState.AddModelError("", "User Not found");
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
                }

                var roles = await UserManager.GetRolesAsync(id);

                IdentityResult resultRole = await UserManager.RemoveFromRolesAsync(id, roles.ToArray());

                if (resultRole.Succeeded)
                {
                    // add role
                    await this.UserManager.AddToRoleAsync(user.Id, userViewModel.SelectedRoleName);

                    user.UserName = userViewModel.UserName;
                    user.Email    = userViewModel.Email;
                    IdentityResult resultUser = UserManager.Update(user);
                    if (resultUser.Succeeded)
                    {
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                }
            }
            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
        }
Пример #19
0
        public async Task <ActionResult <RpGetCitizens> > GetCitizens([FromBody] RqGetCitizens rqGetCitizens)
        {
            try
            {
                if (!string.IsNullOrEmpty(rqGetCitizens.SearchRequest.Inn) && !ValidationsCollection.Validations.IsValidInnForIndividual(rqGetCitizens.SearchRequest.Inn))
                {
                    return(Json(ResponseHelper.ReturnBadRequest("Inn not valid")));
                }

                if (!string.IsNullOrEmpty(rqGetCitizens.SearchRequest.Snils) && !ValidationsCollection.Validations.IsValidSnils(StringConverter.GetNumbers(rqGetCitizens.SearchRequest.Snils)))
                {
                    return(Json(ResponseHelper.ReturnBadRequest("Snils not valid")));
                }

                var searchRequestParsed = new SearchRequestParsed();
                try
                {
                    searchRequestParsed = CitizenConverter.FromSearchRequestToSearchRequestParsed(rqGetCitizens.SearchRequest);
                }
                catch (Exception exception)
                {
                    LoggerStatic.Logger.Warn("Exception: " + exception);
                    return(Json(ResponseHelper.ReturnBadRequest(exception.Message)));
                }

                var rpGetCitizens = new RpGetCitizens
                {
                    Citizens = await _peopleService.GetCitizens(searchRequestParsed)
                };
                //return Json(rpGetCitizens);
                return(ControllersHelper.ReturnContentResult(SerializerJson.SerializeObjectToJsonString(rpGetCitizens)));
            }
            catch (Exception exception)
            {
                LoggerStatic.Logger.Error("Exception: " + exception);
                return(Json(ResponseHelper.ReturnInternalServerError(exception.Message)));
            }
        }
        public ActionResult Edit([Bind(Include = "ProductCategoryId,Name,Description,ImagePath,ImageName,IsChangeImage")] ProductCategoryViewModel productCategoryViewModel)
        {
            if (ModelState.IsValid)
            {
                var imagePath = productCategoryViewModel.ImageName;
                if (productCategoryViewModel.IsChangeImage)
                {
                    var myHelper = new ControllersHelper();
                    imagePath = myHelper.SaveFile(productCategoryViewModel.ImagePath, ModelState, Server);
                }

                ProductCategory productCategory = new ProductCategory
                {
                    ProductCategoryId = productCategoryViewModel.ProductCategoryId,
                    Name        = productCategoryViewModel.Name,
                    Description = productCategoryViewModel.Description,
                    ImagePath   = imagePath
                };
                db.Entry(productCategory).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(productCategoryViewModel));
        }
Пример #21
0
        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            var controllerName = base.GetControllerName(request);

            if (controllerName.ToLower() == "help")
            {
                return(new HttpControllerDescriptor(_configuration, controllerName, typeof(HelpController)));
            }

            Logger.DebugFormat("Incoming request is calling to controller : {0}.", controllerName);

            if (ControllersHelper.IsControllerEnabled(controllerName) == false)
            {
                string errorMessage = "Incoming request is calling to invalid controller.";

                Logger.ErrorFormat(errorMessage);
                throw new Exception(errorMessage);
            }

            try
            {
                var assemblyFullPath = AssemblyHelper.GetAssemblyFullPath(string.Format("{0}{1}.dll", controllerName, DynamicCoreConstants.DllSuffix));

                Logger.DebugFormat("Loading assembly : {0}", assemblyFullPath);

                byte[] assemblyBytes = File.ReadAllBytes(assemblyFullPath);

                string assemblyFullName = AssemblyHelper.GetAssemblyFullName(assemblyBytes);

                var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == assemblyFullName);

                if (assembly == null)
                {
                    assembly = Assembly.Load(assemblyBytes);
                }

                var referencedAssemblies = assembly.GetReferencedAssemblies();

                foreach (var referencedAssembly in referencedAssemblies)
                {
                    string referencedAssemblyFullPath = string.Format("{0}{1}.dll", _dynamicDllsPath, referencedAssembly.Name);

                    if (File.Exists(referencedAssemblyFullPath) == true)
                    {
                        byte[] referencedaAsemblyBytes = File.ReadAllBytes(referencedAssemblyFullPath);

                        assemblyFullName = AssemblyHelper.GetAssemblyFullName(referencedaAsemblyBytes);

                        var referencedaAsembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == assemblyFullName);

                        if (referencedaAsembly == null)
                        {
                            Assembly.Load(referencedaAsemblyBytes);
                        }
                    }
                }

                var types = assembly.GetTypes();

                var matchedTypes = types.Where(i => typeof(IHttpController).IsAssignableFrom(i)).ToList();

                Logger.DebugFormat("Assembly {0} loaded, file size is {1} bytes, {2} types found and {3} types matched.", assemblyFullPath, assemblyBytes.Length, types.Length, matchedTypes.Count);

                var matchedController =
                    matchedTypes.FirstOrDefault(i => i.Name.ToLower() == controllerName.ToLower() + "controller");

                if (matchedController != null)
                {
                    Logger.DebugFormat("Controller matched.");
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                Logger.DebugFormat("Memory Usage : {0}", GC.GetTotalMemory(true));

                return(new HttpControllerDescriptor(_configuration, controllerName, matchedController));
            }
            catch (ReflectionTypeLoadException ex)
            {
                var stringBuilder = new StringBuilder();

                foreach (Exception exception in ex.LoaderExceptions)
                {
                    stringBuilder.AppendLine(exception.Message);

                    var fileNotFoundException = exception as FileNotFoundException;

                    if (fileNotFoundException != null)
                    {
                        if (!string.IsNullOrEmpty(fileNotFoundException.FusionLog))
                        {
                            stringBuilder.AppendLine("Fusion Log:");
                            stringBuilder.AppendLine(fileNotFoundException.FusionLog);
                        }
                    }
                    stringBuilder.AppendLine();
                }

                Logger.ErrorFormat("Fail to load assembly : {0}", stringBuilder);

                throw;
            }
        }
Пример #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var sqlConnectionString = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <PeopleDbContext>(
                options => options.UseSqlServer(sqlConnectionString), ServiceLifetime.Scoped
                );


            services.AddControllers()
            .AddJsonOptions(opt =>
            {
                opt.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                opt.JsonSerializerOptions.WriteIndented          = true;
                opt.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
                opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });


            services.AddSingleton <IConfiguration>(Configuration);


            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "People API",
                    Description = "A simple example Web API",
                    Contact     = new OpenApiContact()
                    {
                        Name  = "Name",
                        Email = string.Empty,
                        //Url = "http://test.test"
                    }
                }
                                   );
            });

            services.ConfigureSwaggerGen(options =>
            {
                options.CustomSchemaIds(x => x.FullName);
            });

            services.RegisterServices(Configuration);

            services.Configure <ApiBehaviorOptions>(o =>
            {
                o.InvalidModelStateResponseFactory = actionContext =>
                {
                    var keyList = string.Join(",", actionContext.ModelState.Keys);

                    return(ControllersHelper.ReturnContentResult(SerializerJson.SerializeObjectToJsonString(ResponseHelper.ReturnBadRequest($"ModelState.Keys: {keyList}"))));
                };
            });

            services.AddLogging(builder =>
            {
                builder.AddConfiguration(Configuration.GetSection("Logging"))
                .AddConsole()
                .AddDebug();
            });

            services.Configure <WSettings>(Configuration);
        }
Пример #23
0
        public void Update()
        {
            if (_messageDisplayTime > 0f)
            {
                _messageDisplayTime -= Time.deltaTime;
                if (_messageDisplayTime <= 0f)
                {
                    _messageDisplayTime      = 0f;
                    _messageDisplayText.text = "";
                }
            }

            if (Config.Instance.EnableVoiceChat && Config.Instance.MicEnabled)
            {
                if (!Config.Instance.PushToTalk)
                {
                    isRecording = true;
                }
                else
                {
                    switch (Config.Instance.PushToTalkButton)
                    {
                    case 0:
                        isRecording = ControllersHelper.GetLeftGrip();
                        break;

                    case 1:
                        isRecording = ControllersHelper.GetRightGrip();
                        break;

                    case 2:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.LeftHand) > 0.85f;
                        break;

                    case 3:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.RightHand) > 0.85f;
                        break;

                    case 4:
                        isRecording = ControllersHelper.GetLeftGrip() && ControllersHelper.GetRightGrip();
                        break;

                    case 5:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.RightHand) > 0.85f && VRControllersInputManager.TriggerValue(XRNode.LeftHand) > 0.85f;
                        break;

                    case 6:
                        isRecording = ControllersHelper.GetLeftGrip() || ControllersHelper.GetRightGrip();
                        break;

                    case 7:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.RightHand) > 0.85f || VRControllersInputManager.TriggerValue(XRNode.LeftHand) > 0.85f;
                        break;

                    default:
                        isRecording = Input.anyKey;
                        break;
                    }
                }
            }
            else
            {
                isRecording = false;
            }

            if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
            {
                if (Input.GetKeyDown(KeyCode.Keypad0))
                {
                    fixedSendRate = 0;
                    Misc.Logger.Info($"Variable send rate");
                }
                else if (Input.GetKeyDown(KeyCode.Keypad1))
                {
                    fixedSendRate = 1;
                    Misc.Logger.Info($"Forced full send rate");
                }
                else if (Input.GetKeyDown(KeyCode.Keypad2))
                {
                    fixedSendRate = 2;
                    Misc.Logger.Info($"Forced half send rate");
                }
                else if (Input.GetKeyDown(KeyCode.Keypad3))
                {
                    fixedSendRate = 3;
                    Misc.Logger.Info($"Forced one third send rate");
                }
            }

            if (needToSendUpdates)
            {
                if (fixedSendRate == 1 || (fixedSendRate == 0 && Client.Instance.Tickrate > 67.5f * (1f / 90 / Time.deltaTime)))
                {
                    sendRateCounter = 0;
                    UpdatePlayerInfo();
#if DEBUG && VERBOSE
                    Misc.Logger.Info($"Full send rate! FPS: {(1f / Time.deltaTime).ToString("0.0")}, TPS: {Client.Instance.Tickrate.ToString("0.0")}");
#endif
                }
                else if (fixedSendRate == 2 || (fixedSendRate == 0 && Client.Instance.Tickrate > 37.5f * (1f / 90 / Time.deltaTime)))
                {
                    sendRateCounter++;
                    if (sendRateCounter >= 1)
                    {
                        sendRateCounter = 0;
                        UpdatePlayerInfo();
#if DEBUG && VERBOSE
                        Misc.Logger.Info($"Half send rate! FPS: {(1f / Time.deltaTime).ToString("0.0")}, TPS: {Client.Instance.Tickrate.ToString("0.0")}");
#endif
                    }
                }
                else if (fixedSendRate == 3 || (fixedSendRate == 0 && Client.Instance.Tickrate <= 37.5f * (1f / 90 / Time.deltaTime)))
                {
                    sendRateCounter++;
                    if (sendRateCounter >= 2)
                    {
                        sendRateCounter = 0;
                        UpdatePlayerInfo();
#if DEBUG && VERBOSE
                        Misc.Logger.Info($"One third send rate! FPS: {(1f / Time.deltaTime).ToString("0.0")}, TPS: {Client.Instance.Tickrate.ToString("0.0")}");
#endif
                    }
                }
            }
        }
        public void Update()
        {
            if (!Client.Instance.connected)
            {
                return;
            }

            if (_messageDisplayTime > 0f)
            {
                _messageDisplayTime -= Time.deltaTime;
                if (_messageDisplayTime <= 0f)
                {
                    _messageDisplayTime = 0f;
                    if (_messageDisplayText != null)
                    {
                        _messageDisplayText.text = "";
                    }
                }
            }

            if (Config.Instance.EnableVoiceChat && Config.Instance.MicEnabled)
            {
                if (!Config.Instance.PushToTalk)
                {
                    isRecording = true;
                }
                else
                {
                    switch (Config.Instance.PushToTalkButton)
                    {
                    case 0:
                        isRecording = ControllersHelper.GetLeftGrip();
                        break;

                    case 1:
                        isRecording = ControllersHelper.GetRightGrip();
                        break;

                    case 2:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.LeftHand) > 0.85f;
                        break;

                    case 3:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.RightHand) > 0.85f;
                        break;

                    case 4:
                        isRecording = ControllersHelper.GetLeftGrip() && ControllersHelper.GetRightGrip();
                        break;

                    case 5:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.RightHand) > 0.85f && VRControllersInputManager.TriggerValue(XRNode.LeftHand) > 0.85f;
                        break;

                    case 6:
                        isRecording = ControllersHelper.GetLeftGrip() || ControllersHelper.GetRightGrip();
                        break;

                    case 7:
                        isRecording = VRControllersInputManager.TriggerValue(XRNode.RightHand) > 0.85f || VRControllersInputManager.TriggerValue(XRNode.LeftHand) > 0.85f;
                        break;

                    default:
                        isRecording = Input.anyKey;
                        break;
                    }
                }
            }
            else
            {
                isRecording = false;
            }

            if (isVoiceChatActive && voiceChatListener != null)
            {
                voiceChatListener.isListening = isRecording;
            }

            if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
            {
                if (Input.GetKeyDown(KeyCode.Keypad0))
                {
                    _fixedSendRate = 0;
                    Plugin.log.Info($"Variable send rate");
                }
                else if (Input.GetKeyDown(KeyCode.Keypad1))
                {
                    _fixedSendRate = 1;
                    Plugin.log.Info($"Forced full send rate");
                }
                else if (Input.GetKeyDown(KeyCode.Keypad2))
                {
                    _fixedSendRate = 2;
                    Plugin.log.Info($"Forced half send rate");
                }
                else if (Input.GetKeyDown(KeyCode.Keypad3))
                {
                    _fixedSendRate = 3;
                    Plugin.log.Info($"Forced one third send rate");
                }
            }

            if (needToSendUpdates)
            {
                if (_fixedSendRate == 1 || (_fixedSendRate == 0 && Client.Instance.tickrate > (1f / Time.deltaTime / 3f * 2f + 5f)) || _spectatorInRoom)
                {
                    _sendRateCounter = 0;
                    UpdatePlayerInfo();
#if DEBUG && VERBOSE
                    Plugin.log.Info($"Full send rate! FPS: {(1f / Time.deltaTime).ToString("0.0")}, TPS: {Client.Instance.Tickrate.ToString("0.0")}, Trigger: TPS>{1f / Time.deltaTime / 3f * 2f + 5f}");
#endif
                }
                else if (_fixedSendRate == 2 || (_fixedSendRate == 0 && Client.Instance.tickrate > (1f / Time.deltaTime / 3f + 5f)))
                {
                    _sendRateCounter++;
                    if (_sendRateCounter >= 1)
                    {
                        _sendRateCounter = 0;
                        UpdatePlayerInfo();
#if DEBUG && VERBOSE
                        Plugin.log.Info($"Half send rate! FPS: {(1f / Time.deltaTime).ToString("0.0")}, TPS: {Client.Instance.Tickrate.ToString("0.0")}, Trigger: TPS>{1f / Time.deltaTime / 3f + 5f}");
#endif
                    }
                }
                else if (_fixedSendRate == 3 || (_fixedSendRate == 0 && Client.Instance.tickrate <= (1f / Time.deltaTime / 3f + 5f)))
                {
                    _sendRateCounter++;
                    if (_sendRateCounter >= 2)
                    {
                        _sendRateCounter = 0;
                        UpdatePlayerInfo();
#if DEBUG && VERBOSE
                        Plugin.log.Info($"One third send rate! FPS: {(1f / Time.deltaTime).ToString("0.0")}, TPS: {Client.Instance.Tickrate.ToString("0.0")}, Trigger: TPS<={1f / Time.deltaTime / 3f + 5f}");
#endif
                    }
                }
            }
        }
Пример #25
0
        public virtual HttpResponseMessage Index()
        {
            var config = HttpConfigurationImporter.ImportConfigurationFromPath(ConfigurationManager.AppSettings[DynamicCoreConstants.DynamicControllerDllPath]);

            config.SetDocumentationProvider(new XmlDocumentationProvider(ConfigurationManager.AppSettings[DynamicCoreConstants.DynamicControllerDllPath]));

            var apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions.Where(a =>
                                                                                         ControllersHelper.IsControllerEnabled(a.ActionDescriptor.ActionBinding.ActionDescriptor
                                                                                                                               .ControllerDescriptor.ControllerName) == true).ToList();

            Collection <ApiDescription> filteredApiDescriptions = new Collection <ApiDescription>(apiDescriptions);

            Index template = new Index
            {
                Model          = filteredApiDescriptions,
                ApiLinkFactory = apiName =>
                {
                    string controllerName = Regex.Replace(GetType().Name, "controller", "", RegexOptions.IgnoreCase);
                    return(Url.Route(HelpPageRouteName, new
                    {
                        controller = controllerName,
                        apiId = apiName
                    }));
                }
            };

            string helpPage = template.TransformText();

            return(new HttpResponseMessage
            {
                Content = new StringContent(helpPage, Encoding.UTF8, "text/html")
            });
        }