상속: MonoBehaviour
        private async void Button_Click(object sender, RoutedEventArgs e)
        {

            bar.IsIndeterminate = true;
            bar.Visibility = Visibility.Visible;
           


            var picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".jpeg");

            picker.FileTypeFilter.Add(".jpg");
            picker.SuggestedStartLocation = PickerLocationId.Desktop;
            picker.ViewMode = PickerViewMode.List;
            StorageFile file = await picker.PickSingleFileAsync();
            IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

          

            Helper obj = new Helper();
            CloudBlobContainer blobContainer = await obj.GetCloudBobContainer();
            CloudBlockBlob blob = blobContainer.GetBlockBlobReference(Guid.NewGuid().ToString() + ".jpg");


            await blob.UploadFromStreamAsync(stream);
            bar.IsIndeterminate = false;
            bar.Visibility = Visibility.Collapsed;
            MessageDialog msd = new MessageDialog("The image uploaded succesfully");
            await msd.ShowAsync();


        }
예제 #2
0
        public override Lattice tree( TimeGrid grid)  
        {
            TermStructureFittingParameter phi= new TermStructureFittingParameter(termStructure());

            ShortRateDynamics numericDynamics=
                                    new Dynamics(phi, a(), sigma());

            TrinomialTree trinomial=
                             new TrinomialTree(numericDynamics.process(), grid);
            ShortRateTree numericTree =
                             new ShortRateTree(trinomial, numericDynamics, grid);

            TermStructureFittingParameter.NumericalImpl impl = 
                (TermStructureFittingParameter.NumericalImpl)phi.implementation();
            impl.reset();
            double value = 1.0;
            double vMin = -50.0;
            double vMax = 50.0;
            for (int i=0; i<(grid.size() - 1); i++) {
                double discountBond = termStructure().link.discount(grid[i+1]);
                double xMin = trinomial.underlying(i, 0);
                double dx = trinomial.dx(i);
                Helper finder = new Helper(i, xMin, dx, discountBond, numericTree);
                Brent s1d = new Brent();
                s1d.setMaxEvaluations(1000);
                value = s1d.solve(finder, 1e-7, value, vMin, vMax);
                impl.setvalue(grid[i], value);
                // vMin = value - 10.0;
                // vMax = value + 10.0;
            }
            return numericTree;
        }
예제 #3
0
 static void Main(string[] args)
 {
     var helper = new Helper();
     helper.IntDelay(1000);
     helper.ProcessAwaiter(Process.GetProcessById(6724));
     Console.ReadLine();
 }
예제 #4
0
 public void SetToDoItems(List<ToDoItem> items)
 {
     var array = items.ToArray();
     var heloer = new Helper { Items = items.ToArray() };
     string r = JsonConvert.SerializeObject(heloer);
     _fileManager.SaveText(file, r);
 }
		public Helper Add(string helperName, string typeDescription) {
			Helper newItem = new Helper();
			newItem.Name = helperName;
			newItem.Type = typeDescription;
			this.Add(newItem);
			return newItem;
		}
예제 #6
0
파일: test.cs 프로젝트: mono/gert
	static void Main ()
	{
		AppDomainSetup setup = new AppDomainSetup ();
		setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
		setup.ApplicationName = "test";

		AppDomain newDomain = AppDomain.CreateDomain ("test",
			AppDomain.CurrentDomain.Evidence, setup);

		StringCollection probePaths = new StringCollection ();
		probePaths.Add (Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "lib"));

		// create an instance of our custom Assembly Resolver in the target domain.
		newDomain.CreateInstanceFrom (Assembly.GetExecutingAssembly ().CodeBase,
			typeof (AssemblyResolveHandler).FullName,
			false,
			BindingFlags.Public | BindingFlags.Instance,
			null,
			new object[] { probePaths },
			CultureInfo.InvariantCulture,
			null,
			AppDomain.CurrentDomain.Evidence);

		Helper helper = new Helper ();
		newDomain.DoCallBack (new CrossAppDomainDelegate (helper.Test));
	}
예제 #7
0
파일: Program.cs 프로젝트: anamalu/Procdet
        /// <summary>
        /// Entry point for the program
        /// </summary>
        /// <param name="args">list of commandline arguments</param>
        private static void Main(string[] args)
        {
            Helper _helper = new Helper();
            Console.WriteLine();
            Console.WriteLine("===========OUTPUT==========");
            Console.WriteLine();
            //Get the second argument that holds the file/Directory
            var fileORDirectory = args[1];

            if (File.Exists(fileORDirectory))
            {
                // The path is a file
                _helper.ProcessFile(fileORDirectory);
            }
            else if (Directory.Exists(fileORDirectory))
            {
                // The path is a directory
                _helper.ProcessDirectory(fileORDirectory);
            }
            else
            {
                Console.WriteLine("{0} is not a valid file or directory.", fileORDirectory);
                Console.ReadKey();
            }

            Console.ReadKey();
        }
예제 #8
0
        private async Task<string[]> MakeDlPage(string url) {
            HtmlHandler ht = new HtmlHandler();
            Helper hlp = new Helper();
            await ht.DownloadHtml(url);
            //Get RELEASE INFO 
            var temp = ht.GetNodeByAttr(ht.HtmlDoc,"li","class","release");
            string releaseInfo = temp.InnerText.Replace("Release info:","").Trim()??"";
            releaseInfo = hlp.FormatTxt(releaseInfo);
            //Get Img Src
            temp = ht.GetNodeByAttr(ht.HtmlDoc,"img","alt","Poster");
            string Imgs = "";
            try {
                Imgs=ht.GetAttr(temp,"src") ?? "";
            }
            catch(Exception) { }
            //Get Owner
            temp = ht.GetNodeByAttr(ht.HtmlDoc,"li","class","author");
            temp = ht.GetNodeByType(temp,"a")??null;
            string owner = temp.InnerText.Trim()??"";
            owner = hlp.FormatTxt(owner);
            //Get Details
            temp = ht.GetNodeByAttr(ht.HtmlDoc,"div","id","details");
            string details = temp.InnerText.Replace("Subtitle details:","").Trim()??"";
            details = hlp.FormatTxt(details);
            //Get Downloadlink
            temp = ht.GetNodeByAttr(ht.HtmlDoc,"a","id","downloadButton");
            string dlUrl = ht.GetAttr(temp,"href")??"";

            return new string []{Imgs,releaseInfo,owner,details,dlUrl};
        }
예제 #9
0
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("WorkerRole1 entry point called", "Information");

            // Disables EntityFramework Code First checks
            Database.SetInitializer<ConvictsContext>(null);

            while (true)
            {
                try
                {

                    Helper h = new Helper();
                    h.CalculateConvictTotals();
                    h.getDonorNames();
                    h.getPaymentRecords();
                    h.SanitiseDatabaseQuotes();
                    h.getConvictURLS();
                    h.getTeamURLS();
                    h.CalculateTeamTotals();
                    h.addTeamCodeToPaymentRecords();

                    Thread.Sleep(60000); //5 minutes
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message.ToString());
                    //throw;
                }
                System.Threading.Thread.Sleep(1000 * 60);
            }
        }
예제 #10
0
파일: Sys_DeptDAL.cs 프로젝트: bIgMunich/Re
 public Sys_Dept GetModel(int Id)
 {
     Sys_Dept entity = new Sys_Dept();
     entity.Id = Id;
     Sys_Dept model = new Helper().Find(entity);
     return model;
 }
예제 #11
0
 public void Init(Helper help, Character chr)
 {
     try
     {
         _character = chr;
         _helper = help;
         listView1.ItemsSource = _character.Attacks;
         listView2.ItemsSource = _character.Effects;
         listView3.ItemsSource = _character.KnownSpells;
         listView4.ItemsSource = _character.AvailableCastings;
         listView6.ItemsSource = _character.Spells.Where(f => f.IsCasted == false).OrderByDescending(k => k.Definition.Level);
         listView7.ItemsSource = _character.Skills;
         comboBox2.ItemsSource = _character.AvailableCastings;
         comboBox1.ItemsSource = SpellEditWindow.Types;
         comboBox4.ItemsSource = Rules.SkillsDefinition;
         comboBox4.DisplayMemberPath = "Name";
         ContentGrid.DataContext = _character;
         textBox18.Text = _helper.CurrentTime.Date.AddDays(-7).ToString();
         if (_character.ImagePath != null)
         {
             image1.Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\" + _character.ImagePath));
         }
     }
     catch (Exception exc)
     {
         MessageBox.Show("Inicjalizacja się nie powiodła:" + exc.ToString());
     }
 }
예제 #12
0
파일: Helper.cs 프로젝트: Dekken/buildatron
 public static Helper getInstance()
 {
     if (Helper.instance == null){
         Helper.instance = new Helper();
     }
     return Helper.instance;
 }
 public ListView()
 {
     this.memberDAL = new MemberDAL();
     this.listMembers = new List<KeyValuePair<string, string>>();
     this.helper = new Helper();
     listMembers = memberDAL.listMembers();
 }
예제 #14
0
        public ActionResult About()
        {
            var helper = new Helper();
            ViewBag.Message = helper.Welcome();

            return View();
        }
예제 #15
0
 public Frm_T_Detalle(Helper.eOpcion _qOpcion, Helper.eTablas _eTabla, string Idtabla)
 {
     InitializeComponent();
     qOpcion = _qOpcion;
     eTabla = _eTabla;
     sIdtabla = Idtabla;
 }
예제 #16
0
        static void Main(string[] args)
        {
            List<string> testList = new List<string>();
            Helper helperLib=new Helper();

            for (int i = 0; i < 100; i++)
            {
                testList.Add("item" + i.ToString());
            }

            string csv = helperLib.ListToCSV(testList);
            int length = csv.Split(',').Length;

            List<string> testList2 = helperLib.CSVToList(csv);

            //Sum of Integer List

            List<int> integerList = new List<int>();
            for (int i = 0; i < length; i++)
            {
                integerList.Add(i);
            }

            long TotalSum = helperLib.SumOfIntList(integerList);
        }
예제 #17
0
        public void InitializeAllRoles()
        {
            var roleList = new List<string>()
            {
                "Admin","Customer","Supplier","Sales"
            };
            if (roleList != null)
            {
                var helper = new Helper();
                foreach (var item in roleList)
                {
                    string titleCaseRole = helper.ConvertToTitleCase(item.ToLowerInvariant());

                    var searchResult = (from role in db.Roles
                                        where role.Name == titleCaseRole
                                        select role).FirstOrDefault();

                    if (searchResult == null)
                    {
                        db.Roles.Add(new IdentityRole()
                        {
                            Name = titleCaseRole
                        });
                        db.SaveChanges();
                    }
                }
            }
        }
예제 #18
0
 public IEnumerable<Term> FindTermsByPOS(Helper.POS pos)
 {
     var result = from term in terms
                  where term.PoS == pos
                  select term;
     return result;
 }
        public void InsertTestData()
        {
            Helper helper = new Helper();
            User dil = new User();
            dil.UserName = "******";
            dil.Password = helper.EncryptPassword(dil.UserName+"123");
            dil.Role = "Admin";
            String v1 = helper.GenerageVerificationCode(4);
            dil.VerificationCode = v1;

            User laxman = new User();
            laxman.UserName = "******";
            laxman.Password = helper.EncryptPassword(laxman.UserName+"123");
            laxman.Role = "Staff";
            String v2 = helper.GenerageVerificationCode(4);
            laxman.VerificationCode = v2;

            List<User> users = new List<User>();
            users.Add(dil);
            users.Add(laxman);
            using (var db = new GPAEntities())
            {
                db.Users.AddRange(users);
                db.SaveChanges();
            }
        }
예제 #20
0
        public override bool IsValid()
        {
            Helper helper = new Helper();
            object obj2 = base.PropInfo.GetValue(base.Instance, null);
            if (helper.IsNullOrEmpty(obj2))
            {
                return true;
            }
            switch (this.RegexType)
            {
                case NRegexType.Email:
                    if (helper.IsValidEmail(obj2.ToString()))
                    {
                        return true;
                    }
                    base.mErrorMeg = helper.GetStringValue(NReasonError.Email_Field);
                    return false;

                case NRegexType.Phone:
                    if (helper.IsValidPhone(obj2.ToString()))
                    {
                        return true;
                    }
                    base.mErrorMeg = helper.GetStringValue(NReasonError.Phone_Field);
                    return false;
            }
            return false;
        }
예제 #21
0
        static void Main(string[] args)
        {
            var help = new Helper();
            var list = help.GetConnections();
            #region 生成模板
            //foreach (var item in list)
            //{
            //    help.GenerateFetchStatement(help.GetDatabaseSheme(item));
            //    help.GenerateFetchStatementWithNolock(help.GetDatabaseSheme(item));
            //}

            #endregion
            #region 生成实体类

            var help2 = new EntityHelper();

            int c = 0;
            foreach (var item in list)
            {
                help2.GenerateFile(help2.GetSheme(item, ConfigurationManager.AppSettings["ns"].Split('|')[c]), ConfigurationManager.AppSettings["fn"].Split('|')[c]);
                c++;
            }


            #endregion

            Console.WriteLine("生成完毕!");
            Console.Read();
        }
예제 #22
0
        public string GetTranslatedText(string sourseText, string langSource, string langTrans)
        {
            Helper helper = new Helper();
            string returnValue = string.Empty;

            if (!helper.IsNullOrEmpty(sourseText))
            {
                HttpWebRequest request = null;
                HttpWebResponse response = null;
                StringBuilder builder = new StringBuilder("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0");
                builder.Append("&q=" + HttpUtility.UrlEncode(sourseText.Trim()));
                builder.Append("&langpair=" + langSource + "|" + langTrans);
                builder.Append("&key=" + ConfigurationManager.AppSettings["GoogleAPIKey"]);
                request = (HttpWebRequest)WebRequest.Create(builder.ToString());
                request.Method = NHttpMethod.GET.ToString();
                response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string str = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    string leadingText = "{\"translatedText\":\"";
                    int startIndex = str.IndexOf(leadingText) + leadingText.Length;
                    int index = str.IndexOf("\"},");

                    returnValue = str.Substring(startIndex, index - startIndex);
                }
                else
                    returnValue = "Google translation service no response.";
            }

            return returnValue;
        }
예제 #23
0
 public Sys_Template GetModel(int Id)
 {
     Sys_Template entity = new Sys_Template();
     entity.Id = Id;
     Sys_Template model = new Helper().Find(entity);
     return model;
 }
예제 #24
0
파일: ErrorLog.cs 프로젝트: wjkong/MicNets
 public ErrorLog(Exception ex, string additionalInfo)
 {
     this.oHelper = new Helper();
     this.mException = ex;
     this.mAdditionalInfo = additionalInfo;
     this.ReportErrorNonWeb(string.Empty);
 }
예제 #25
0
파일: ErrorLog.cs 프로젝트: wjkong/MicNets
 public ErrorLog(Exception ex, HttpContext context)
 {
     this.oHelper = new Helper();
     this.mContext = context;
     this.mException = ex;
     this.ReportError();
 }
예제 #26
0
        /// <summary>
        /// Konstruktor
        /// </summary>
        /// <param name='size'>Größe der Population</param>
        /// <param name='genomeSize'>Größe des einzelnen Genomes</param>
        public Population(int size, int genomeSize, double minAllelValue, double maxAllelValue, Helper.Enums.Encryption encryption)
        {
            _encryption = encryption;
            // Erzeuge Listen mit fester Kapazität
            curGeneration = new List<Genome>(size);
            oldGeneration = new List<Genome>(size);
            totalSize = size;
            Genome tmp;

            for(int i = 0; i < size; i++)
            {
                if (_encryption == Helper.Enums.Encryption.None)
                    throw new NotImplementedException(); //todo Genome mit Integerwerten
            //				else if (_encryption == Helper.Enums.Encryption.Binary)
            //				{
            //					throw new NotImplementedException(); //todo
            //				}
            //				else if (_encryption == Helper.Enums.Encryption.Real)
                else
                {
                    tmp = new GenomeReal(genomeSize, minAllelValue, maxAllelValue);
                    // um Duplikate bei der Erzeugung der Population zu vermeiden
                    while(curGeneration.Contains(tmp))
                    {
                        //Console.WriteLine(String.Format("Duplikat: {0}\r\ni = {1}", tmp.AsString(),i));
                        tmp = new GenomeReal(genomeSize, minAllelValue, maxAllelValue);
                    }
                    curGeneration.Add(tmp);
                }
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string latest_updatex = IsolatedSettingsHelper.GetValue<string>("latest_update");
            string latest_update_channelx = IsolatedSettingsHelper.GetValue<string>("latest_update_channel");
            string latest_update_timex = IsolatedSettingsHelper.GetValue<string>("latest_update_time");

            Helper helper = new Helper();
            if (latest_updatex != null)
            {
                if (latest_updatex.Count() > 0)
                    latest_update.Text = latest_updatex + "\n" + latest_update_channelx.Remove(0, 1);
            }
            if (latest_update_timex == "" || latest_update_timex == null)
            {
                //do nothing.
            }
            else
            {
                DateTime date = Convert.ToDateTime(latest_update_timex);
                latest_update_time.Text = helper.CalculateShareTime(date) + " ago.";
            }


  

        }
예제 #28
0
		protected virtual void BaseAwake()
		{
			appMain = App.Main.Instance;
			h       = Helper.Instance;
			conf    = Config.Instance;
			ds      = DataStorage.Instance;
		}
 public ProviderController(Helper helper, JsonSerializer json, CoreConverter converter, ProductController productController)
 {
     _h = helper;
     _j = json;
     _c = converter;
     _p = productController;
 }
예제 #30
0
 static void Main(string[] args)
 {
     var helper = new Helper();
     helper.Validate(args);
     var model = helper.UnfurlNodes(helper.ParseXml());
     model.WriteValues();
 }
예제 #31
0
 public void display()
 {
     Helper.ellipse(location.x, location.y, 16, 16);
 }
예제 #32
0
 /// <summary>
 ///     This method is invoked when the HeaderTemplateSelector property changes.
 /// </summary>
 /// <param name="oldHeaderTemplateSelector">The old value of the HeaderTemplateSelector property.</param>
 /// <param name="newHeaderTemplateSelector">The new value of the HeaderTemplateSelector property.</param>
 protected virtual void OnHeaderTemplateSelectorChanged(DataTemplateSelector oldHeaderTemplateSelector, DataTemplateSelector newHeaderTemplateSelector)
 {
     Helper.CheckTemplateAndTemplateSelector("Header", HeaderTemplateProperty, HeaderTemplateSelectorProperty, this);
 }
예제 #33
0
 /// <summary>
 /// 获取结果
 /// </summary>
 private string GetResult(TagHelperAttributeList contextAttributes = null, TagHelperAttributeList outputAttributes = null, TagHelperContent content = null)
 {
     return(Helper.GetResult(_output, _component, contextAttributes, outputAttributes, content));
 }
예제 #34
0
        public async Task SetUp()
        {
            const string Original     = @"original.config";
            const string OriginalMono = @"original.mono.config";

            if (Helper.IsRunningOnMono())
            {
                File.Copy("Website1/original.config", "Website1/web.config", true);
                File.Copy(OriginalMono, Current, true);
            }
            else
            {
                File.Copy("Website1\\original.config", "Website1\\web.config", true);
                File.Copy(Original, Current, true);
            }

            Environment.SetEnvironmentVariable(
                "JEXUS_TEST_HOME",
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            _server = new IisExpressServerManager(Current);

            var serviceContainer = new ServiceContainer();

            serviceContainer.RemoveService(typeof(IConfigurationService));
            serviceContainer.RemoveService(typeof(IControlPanel));
            var scope = ManagementScope.Site;

            serviceContainer.AddService(typeof(IControlPanel), new ControlPanel());
            serviceContainer.AddService(
                typeof(IConfigurationService),
                new ConfigurationService(
                    null,
                    _server.Sites[0].GetWebConfiguration(),
                    scope,
                    null,
                    _server.Sites[0],
                    null,
                    null,
                    null, _server.Sites[0].Name));

            serviceContainer.RemoveService(typeof(IManagementUIService));
            var mock = new Mock <IManagementUIService>();

            mock.Setup(
                action =>
                action.ShowMessage(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <MessageBoxButtons>(),
                    It.IsAny <MessageBoxIcon>(),
                    It.IsAny <MessageBoxDefaultButton>())).Returns(DialogResult.Yes);
            serviceContainer.AddService(typeof(IManagementUIService), mock.Object);

            var module = new IpSecurityModule();

            module.TestInitialize(serviceContainer, null);

            _feature = new IpSecurityFeature(module);
            _feature.Load();
        }
        public string GetCommandString(string connectionString, string tableName)
        {
            String cmdStr = null;

            String    getDateColsCmdStr = String.Format("SELECT Column_Name FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = '{0}' AND data_type IN ('{1}','{2}')", tableName, Constants.SqlTypeNames.Date, Constants.SqlTypeNames.DateTime);
            DataTable dt = Helper.GetSqlDataTable(connectionString, getDateColsCmdStr);

            if (dt.Rows.Count != 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("update " + tableName + " SET ");
                String comma = String.Empty;
                foreach (DataRow row in dt.Rows)
                {
                    sb.Append(comma);
                    comma = ", ";
                    String clause = String.Format(" {0} = (CASE WHEN {0} <= '{1}' THEN NULL ELSE {0} END)", Helper.GetDestinationColumnName(row[0].ToString()), Constants.SqlDateMinValue);
                    sb.Append(clause);
                }
                cmdStr = sb.ToString();
            }
            return(cmdStr);
        }
예제 #36
0
 public async Task<StorageFile> CreateRandomFile()
 {
     var folder = await GetOutputFolder(true);
     var saveAsTarget = await folder.CreateFileAsync(Helper.GenerateString("IMG") + ".jpg", CreationCollisionOption.GenerateUniqueName);
     return saveAsTarget;
 }
예제 #37
0
 /// <summary>
 /// Türkiye genelinde tanımlı olan tüm yerli kartlara ait BIN numaraları için sorgulama yapılmasına izin veren servisi temsil eder. 
 /// </summary>
 /// <param name="request">Istek olarak gelen bin numarasını temsil etmektedir.</param>
 /// <param name="options">Kullanıcıya özel olarak belirlenen ayarları temsil eder.</param>
 /// <returns></returns>
 public static BinNumberInquiryResponse Execute(BinNumberInquiryRequest request, Settings options)
 {
     options.TransactionDate = Helper.GetTransactionDateString();
     options.HashString = options.PrivateKey + request.binNumber + options.TransactionDate;
     return RestHttpCaller.Create().PostJson<BinNumberInquiryResponse>(options.BaseUrl + "rest/payment/bin/lookup", Helper.GetHttpHeaders( options, Helper.application_json), request);
 }
예제 #38
0
        /// <summary>
        /// This will check if the token exists in the request to force renewal
        /// </summary>
        /// <returns></returns>
        protected override Task ApplyResponseGrantAsync()
        {
            if (_umbracoContextAccessor.UmbracoContext == null || Context.Request.Uri.IsClientSideRequest())
            {
                return(Task.FromResult(0));
            }

            //Now we need to check if we should force renew this based on a flag in the context and whether this is a request that is not normally renewed by OWIN...
            // which means that it is not a normal URL that is authenticated.

            var normalAuthUrl = ((BackOfficeCookieManager)Options.CookieManager)
                                .ShouldAuthenticateRequest(Context, _umbracoContextAccessor.UmbracoContext.OriginalRequestUrl,
                                                           //Pass in false, we want to know if this is a normal auth'd page
                                                           checkForceAuthTokens: false);

            //This is auth'd normally, so OWIN will naturally take care of the cookie renewal
            if (normalAuthUrl)
            {
                return(Task.FromResult(0));
            }

            var httpCtx = Context.TryGetHttpContext();
            //check for the special flag in either the owin or http context
            var shouldRenew = Context.Get <bool?>(Constants.Security.ForceReAuthFlag) != null || (httpCtx.Success && httpCtx.Result.Items[Constants.Security.ForceReAuthFlag] != null);

            if (shouldRenew)
            {
                var signin        = Helper.LookupSignIn(Options.AuthenticationType);
                var shouldSignin  = signin != null;
                var signout       = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
                var shouldSignout = signout != null;

                //we don't care about the sign in/sign out scenario, only renewal
                if (shouldSignin == false && shouldSignout == false)
                {
                    //get the ticket
                    var ticket = GetTicket();
                    if (ticket != null)
                    {
                        var currentUtc = Options.SystemClock.UtcNow;
                        var issuedUtc  = ticket.Properties.IssuedUtc;
                        var expiresUtc = ticket.Properties.ExpiresUtc;

                        if (expiresUtc.HasValue && issuedUtc.HasValue)
                        {
                            var timeElapsed   = currentUtc.Subtract(issuedUtc.Value);
                            var timeRemaining = expiresUtc.Value.Subtract(currentUtc);

                            //if it's time to renew, then do it
                            if (timeRemaining < timeElapsed)
                            {
                                //renew the date/times
                                ticket.Properties.IssuedUtc = currentUtc;
                                var timeSpan = expiresUtc.Value.Subtract(issuedUtc.Value);
                                ticket.Properties.ExpiresUtc = currentUtc.Add(timeSpan);

                                //now save back all the required cookie details
                                var cookieValue = Options.TicketDataFormat.Protect(ticket);

                                var cookieOptions = ((UmbracoBackOfficeCookieAuthOptions)Options).CreateRequestCookieOptions(Context, ticket);

                                Options.CookieManager.AppendResponseCookie(
                                    Context,
                                    Options.CookieName,
                                    cookieValue,
                                    cookieOptions);
                            }
                        }
                    }
                }
            }

            return(Task.FromResult(0));
        }
예제 #39
0
 public IEnumerable <Photo> GetAllPhotos()
 {
     return(new JavaScriptSerializer()
            .Deserialize <Photo[]>(Helper.GetRestResponse("http://jsonplaceholder.typicode.com/photos").Content));
 }
예제 #40
0
 public IEnumerable <Type> GetAllTypes()
 {
     return(Helper.GetTypesWithUIOMaticAttribute());
 }
예제 #41
0
파일: MarsManaged.cs 프로젝트: jar0l/crypto
		public override void GenerateIV()
		{
			IVValue = new byte[BlockSizeValue / 8];
			Helper.GetRandomBytes( IVValue );
		}
예제 #42
0
파일: MarsManaged.cs 프로젝트: jar0l/crypto
		public override void GenerateKey()
		{
			KeyValue = new byte[KeySizeValue / 8];
			Helper.GetRandomBytes( KeyValue );
		}
예제 #43
0
 protected override void OnStart(string[] args)
 {
     Helper.WriteLogEntryScheduler(EventLogEntryType.Information, "Starting Scheduler from the Scheduler Service");
     //Run scheduler
     Task.Run(() => StartScheduler());
 }
예제 #44
0
 /********************************
  ** Config Menu Initialization **
  ********************************/
 
 /// <summary>Initializes menu for Generic Mod Config Menu on game launch.</summary>
 /// <param name="sender">The event sender.</param>
 /// <param name="e">The event data.</param>
 private void OnGameLaunched(object sender, GameLaunchedEventArgs e)
 {
     try
     {
         // Get Generic Mod Config Menu's API (if it's installed).
         var configMenu = Helper.ModRegistry.GetApi<IGenericModConfigMenuApi>("spacechase0.GenericModConfigMenu");
         if (configMenu is null)
             return;
         
         // Register mod.
         configMenu.Register(mod: ModManifest, reset: () => Config = new ModConfig(), save: () => Helper.WriteConfig(Config));
         
         // Add options.
         configMenu.AddSectionTitle(mod: ModManifest, text: () => str.Get("headerRanges"));
         
         List<string> rangeList = new List<string>();
         rangeList.Add("1");
         rangeList.Add("-1");
         for (int i = 2; i <= 20; i++)
             rangeList.Add(i.ToString());
         
         foreach (string subject in new string[] { "axe", "pickaxe", "hoe", "wateringCan", "seeds", "objects" })
         {
             configMenu.AddTextOption(
                 mod: ModManifest,
                 name: () => str.Get("optionRangeName", new { subject = str.Get(subject + "ForRangeName") }),
                 tooltip: () => str.Get("optionRangeTooltip", new { subject = str.Get(subject + "ForRangeTooltip") }),
                 getValue: () =>
                 {
                     int value = 1;
                     switch (subject)
                     {
                         case "axe": value = Config.AxeRange; break;
                         case "pickaxe": value = Config.PickaxeRange; break;
                         case "hoe": value = Config.HoeRange; break;
                         case "wateringCan": value = Config.WateringCanRange; break;
                         case "seeds": value = Config.SeedRange; break;
                         case "objects": value = Config.ObjectPlaceRange; break;
                     }
                     return rangeList[value == 1? 0 // Default
                                    : value < 0? 1 // Unlimited
                                    : value]; // Extended
                 },
                 setValue: strValue =>
                 {
                     int value = 1;
                     if (strValue.Equals(rangeList[0]))
                         value = 1;
                     else if (strValue.Equals(rangeList[1]))
                         value = -1;
                     else
                     {
                         for (int i = 2; i <= 20; i++)
                         {
                             if (strValue.Equals(rangeList[i]))
                             {
                                 value = i;
                                 break;
                             }
                         }
                     }
                     
                     switch (subject)
                     {
                         case "axe": Config.AxeRange = value; break;
                         case "pickaxe": Config.PickaxeRange = value; break;
                         case "hoe": Config.HoeRange = value; break;
                         case "wateringCan": Config.WateringCanRange = value; break;
                         case "seeds": Config.SeedRange = value; break;
                         case "objects": Config.ObjectPlaceRange = value; break;
                     }
                 },
                 allowedValues: rangeList.ToArray(),
                 formatAllowedValue: value =>
                 {
                     if (value.Equals("1"))
                         return str.Get("rangeDefault");
                     else if (value.Equals("-1"))
                         return str.Get("rangeUnlimited");
                     else
                         return str.Get("rangeExtended", new { tiles = value });
                 }
             );
         }
         
         configMenu.AddSectionTitle(mod: ModManifest, text: () => str.Get("headerUseOnTile"));
         
         foreach (string tool in new string[] { "axe", "pickaxe", "hoe" })
         {
             configMenu.AddBoolOption(
                 mod: ModManifest,
                 name: () => str.Get("optionSelfUsabilityName", new { tool = str.Get(tool + "ForUsabilityName") }),
                 tooltip: () => str.Get("optionSelfUsabilityTooltip", new { tool = str.Get(tool + "ForUsabilityTooltip") }),
                 getValue: () =>
                 {
                     switch (tool)
                     {
                         case "axe": return Config.AxeUsableOnPlayerTile;
                         case "pickaxe": return Config.PickaxeUsableOnPlayerTile;
                         case "hoe": return Config.HoeUsableOnPlayerTile;
                     }
                     return true;
                 },
                 setValue: value =>
                 {
                     switch (tool)
                     {
                         case "axe": Config.AxeUsableOnPlayerTile = value; break;
                         case "pickaxe": Config.PickaxeUsableOnPlayerTile = value; break;
                         case "hoe": Config.HoeUsableOnPlayerTile = value; break;
                     }
                 }
             );
         }
         
         configMenu.AddSectionTitle(mod: ModManifest, text: () => str.Get("headerFaceClick"));
         
         configMenu.AddBoolOption(
             mod: ModManifest,
             name: () => str.Get("optionToolFaceClickName"),
             tooltip: () => str.Get("optionToolFaceClickTooltip"),
             getValue: () => Config.ToolAlwaysFaceClick,
             setValue: value => Config.ToolAlwaysFaceClick = value
         );
         
         configMenu.AddBoolOption(
             mod: ModManifest,
             name: () => str.Get("optionWeaponFaceClickName"),
             tooltip: () => str.Get("optionWeaponFaceClickTooltip"),
             getValue: () => Config.WeaponAlwaysFaceClick,
             setValue: value => Config.WeaponAlwaysFaceClick = value
         );
         
         configMenu.AddSectionTitle(mod: ModManifest, text: () => str.Get("headerMisc"));
         
         configMenu.AddTextOption(
             mod: ModManifest,
             name: () => str.Get("optionToolHitLocationName"),
             tooltip: () => str.Get("optionToolHitLocationTooltip"),
             getValue: () => Config.ToolHitLocationDisplay.ToString(),
             setValue: value => Config.ToolHitLocationDisplay = int.Parse(value),
             allowedValues: new string[] { "0", "1", "2" },
             formatAllowedValue: value =>
             {
                 switch (value)
                 {
                     case "0": return str.Get("locationLogicOriginal");
                     case "1": default: return str.Get("locationLogicNew");
                     case "2": return str.Get("locationLogicCombined");
                 }
             }
         );
         
         configMenu.AddBoolOption(
             mod: ModManifest,
             name: () => str.Get("optionAllowRangedChargeName"),
             tooltip: () => str.Get("optionAllowRangedChargeTooltip"),
             getValue: () => Config.AllowRangedChargeEffects,
             setValue: value => Config.AllowRangedChargeEffects = value
         );
         
         configMenu.AddBoolOption(
             mod: ModManifest,
             name: () => str.Get("optionOnClickOnlyName"),
             tooltip: () => str.Get("optionOnClickOnlyTooltip"),
             getValue: () => Config.CustomRangeOnClickOnly,
             setValue: value => Config.CustomRangeOnClickOnly = value
         );
     }
     catch (Exception exception)
     {
         Log("Error setting up mod config menu (menu may not appear): " + exception.InnerException
           + Environment.NewLine + exception.StackTrace);
     }
 }
예제 #45
0
        /// <summary>
        /// Execute an INSERT query.
        /// </summary>
        /// <param name="tableName">The table in which you wish to INSERT.</param>
        /// <param name="keyValuePairs">The key-value pairs for the row you wish to INSERT.</param>
        /// <returns>A DataTable containing the results.</returns>
        public DataTable Insert(string tableName, Dictionary <string, object> keyValuePairs)
        {
            if (String.IsNullOrEmpty(tableName))
            {
                throw new ArgumentNullException(nameof(tableName));
            }
            if (keyValuePairs == null || keyValuePairs.Count < 1)
            {
                throw new ArgumentNullException(nameof(keyValuePairs));
            }

            #region Variables

            string    keys           = "";
            string    values         = "";
            int       insertedId     = 0;
            string    retrievalQuery = "";
            DataTable result;

            #endregion

            #region Build-Key-Value-Pairs

            int added = 0;
            foreach (KeyValuePair <string, object> curr in keyValuePairs)
            {
                if (String.IsNullOrEmpty(curr.Key))
                {
                    continue;
                }

                if (added == 0)
                {
                    #region First

                    keys += SqliteHelper.PreparedFieldname(curr.Key);
                    if (curr.Value != null)
                    {
                        if (curr.Value is DateTime || curr.Value is DateTime?)
                        {
                            values += "'" + DbTimestamp((DateTime)curr.Value) + "'";
                        }
                        else if (curr.Value is int || curr.Value is long || curr.Value is decimal)
                        {
                            values += curr.Value.ToString();
                        }
                        else
                        {
                            if (Helper.IsExtendedCharacters(curr.Value.ToString()))
                            {
                                values += SqliteHelper.PreparedUnicodeValue(curr.Value.ToString());
                            }
                            else
                            {
                                values += SqliteHelper.PreparedStringValue(curr.Value.ToString());
                            }
                        }
                    }
                    else
                    {
                        values += "null";
                    }

                    #endregion
                }
                else
                {
                    #region Subsequent

                    keys += "," + SqliteHelper.PreparedFieldname(curr.Key);
                    if (curr.Value != null)
                    {
                        if (curr.Value is DateTime || curr.Value is DateTime?)
                        {
                            values += ",'" + DbTimestamp((DateTime)curr.Value) + "'";
                        }
                        else if (curr.Value is int || curr.Value is long || curr.Value is decimal)
                        {
                            values += "," + curr.Value.ToString();
                        }
                        else
                        {
                            if (Helper.IsExtendedCharacters(curr.Value.ToString()))
                            {
                                values += "," + SqliteHelper.PreparedUnicodeValue(curr.Value.ToString());
                            }
                            else
                            {
                                values += "," + SqliteHelper.PreparedStringValue(curr.Value.ToString());
                            }
                        }
                    }
                    else
                    {
                        values += ",null";
                    }

                    #endregion
                }

                added++;
            }

            #endregion

            #region Build-INSERT-Query-and-Submit

            result = Query(SqliteHelper.InsertQuery(tableName, keys, values));

            #endregion

            #region Post-Retrieval

            if (!Helper.DataTableIsNullOrEmpty(result))
            {
                bool idFound = false;

                string primaryKeyColumn = GetPrimaryKeyColumn(tableName);

                foreach (DataRow curr in result.Rows)
                {
                    if (Int32.TryParse(curr["id"].ToString(), out insertedId))
                    {
                        idFound = true;
                        break;
                    }
                }

                if (!idFound)
                {
                    result = null;
                }
                else
                {
                    retrievalQuery = "SELECT * FROM `" + tableName + "` WHERE " + primaryKeyColumn + "=" + insertedId;
                    result         = Query(retrievalQuery);
                }
            }

            #endregion

            return(result);
        }
예제 #46
0
        /// <summary>
        /// Execute an UPDATE query.
        /// </summary>
        /// <param name="tableName">The table in which you wish to UPDATE.</param>
        /// <param name="keyValuePairs">The key-value pairs for the data you wish to UPDATE.</param>
        /// <param name="filter">The expression containing the UPDATE filter (i.e. WHERE clause data).</param>
        public void Update(string tableName, Dictionary <string, object> keyValuePairs, Expression filter)
        {
            if (String.IsNullOrEmpty(tableName))
            {
                throw new ArgumentNullException(nameof(tableName));
            }
            if (keyValuePairs == null || keyValuePairs.Count < 1)
            {
                throw new ArgumentNullException(nameof(keyValuePairs));
            }

            #region Variables

            string keyValueClause = "";

            #endregion

            #region Build-Key-Value-Clause

            int added = 0;
            foreach (KeyValuePair <string, object> curr in keyValuePairs)
            {
                if (String.IsNullOrEmpty(curr.Key))
                {
                    continue;
                }

                if (added == 0)
                {
                    if (curr.Value != null)
                    {
                        if (curr.Value is DateTime || curr.Value is DateTime?)
                        {
                            keyValueClause += SqliteHelper.PreparedFieldname(curr.Key) + "='" + DbTimestamp((DateTime)curr.Value) + "'";
                        }
                        else if (curr.Value is int || curr.Value is long || curr.Value is decimal)
                        {
                            keyValueClause += SqliteHelper.PreparedFieldname(curr.Key) + "=" + curr.Value.ToString();
                        }
                        else
                        {
                            if (Helper.IsExtendedCharacters(curr.Value.ToString()))
                            {
                                keyValueClause += SqliteHelper.PreparedFieldname(curr.Key) + "=" + SqliteHelper.PreparedUnicodeValue(curr.Value.ToString());
                            }
                            else
                            {
                                keyValueClause += SqliteHelper.PreparedFieldname(curr.Key) + "=" + SqliteHelper.PreparedStringValue(curr.Value.ToString());
                            }
                        }
                    }
                    else
                    {
                        keyValueClause += SqliteHelper.PreparedFieldname(curr.Key) + "= null";
                    }
                }
                else
                {
                    if (curr.Value != null)
                    {
                        if (curr.Value is DateTime || curr.Value is DateTime?)
                        {
                            keyValueClause += "," + SqliteHelper.PreparedFieldname(curr.Key) + "='" + DbTimestamp((DateTime)curr.Value) + "'";
                        }
                        else if (curr.Value is int || curr.Value is long || curr.Value is decimal)
                        {
                            keyValueClause += "," + SqliteHelper.PreparedFieldname(curr.Key) + "=" + curr.Value.ToString();
                        }
                        else
                        {
                            if (Helper.IsExtendedCharacters(curr.Value.ToString()))
                            {
                                keyValueClause += "," + SqliteHelper.PreparedFieldname(curr.Key) + "=" + SqliteHelper.PreparedUnicodeValue(curr.Value.ToString());
                            }
                            else
                            {
                                keyValueClause += "," + SqliteHelper.PreparedFieldname(curr.Key) + "=" + SqliteHelper.PreparedStringValue(curr.Value.ToString());
                            }
                        }
                    }
                    else
                    {
                        keyValueClause += "," + SqliteHelper.PreparedFieldname(curr.Key) + "= null";
                    }
                }
                added++;
            }

            #endregion

            #region Build-UPDATE-Query-and-Submit

            Query(SqliteHelper.UpdateQuery(tableName, keyValueClause, filter));

            #endregion
        }
예제 #47
0
        public HttpResponseMessage GenerateOwtToken([FromBody] OwtPayloadContract owtPayloadContract)
        {
            HttpResponseMessage resMsg = null;

            // Log the Request Contract Payload
            Helper.LogData(ConfigurationManager.AppSettings["ServiceLog"], $"[{Helper.ServerIP(Request.Headers.Host)}] [GenerateWebToken:{owtPayloadContract}]");

            try
            {
                // Need to Create the Signing Credentials With the Encrypted Public Key.
                var securityKey = File.ReadAllText(ConfigurationManager.AppSettings["EncryptedPublicKey"])
                                  .Replace("-----BEGIN PUBLIC KEY-----\n", "")
                                  .Replace("\n-----END PUBLIC KEY-----\n", "");

                var signingKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
                var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature);
                var header             = new JwtHeader(signingCredentials);

                var payload = new JwtPayload(   // Issuer - String
                    owtPayloadContract.Issuer,
                    // Audience - String
                    owtPayloadContract.Audience,
                    // Claims - IEnumerable<Claims>
                    new List <Claim>()
                {
                    new Claim(ClaimTypes.Uri, owtPayloadContract.URI),
                    new Claim(ClaimTypes.Actor, owtPayloadContract.Actor),
                    new Claim(ClaimTypes.Role, owtPayloadContract.Role),
                    new Claim(ClaimTypes.Sid, owtPayloadContract.SID),
                    new Claim(ClaimTypes.Name, owtPayloadContract.Name),
                    new Claim(ClaimTypes.NameIdentifier, owtPayloadContract.EmployeeId),
                    new Claim(ClaimTypes.Dns, owtPayloadContract.DNS),
                    new Claim(ClaimTypes.Email, owtPayloadContract.Email),
                    new Claim(ClaimTypes.Hash, owtPayloadContract.MacAddress),
                    new Claim(ClaimTypes.Locality, owtPayloadContract.IpAddress)
                },
                    // Not Before - DateTime?
                    owtPayloadContract.NotBefore,
                    // Expires - DateTime?
                    owtPayloadContract.Expires,
                    // Issued At - DateTime?
                    owtPayloadContract.IssuedAt
                    );                         // End of JwtPayLoad Paramaters

                var secToken    = new JwtSecurityToken(header, payload);
                var handler     = new JwtSecurityTokenHandler();
                var tokenString = handler.WriteToken(secToken);

                // Log the token that was generated.
                Helper.LogData(ConfigurationManager.AppSettings["ServiceLog"], $"[{Helper.ServerIP(Request.Headers.Host)}] [JSON_WEB_TOKEN:{(!string.IsNullOrEmpty(tokenString) ? "CREATED" : "NULL|EMPTY")}]");

                resMsg = Request.CreateResponse(HttpStatusCode.OK, tokenString);
            }
            catch (Exception ex)
            {
                Helper.LogData(ConfigurationManager.AppSettings["ExceptionLog"], $"[{Helper.ServerIP(Request.Headers.Host)}] [GenerateJwtToken: {ex.Message}]");
                resMsg = Request.CreateResponse(HttpStatusCode.NotAcceptable, ex);
            }

            return(resMsg);
        }
예제 #48
0
        /// <summary>
        /// Show the columns and column metadata from a specific table.
        /// </summary>
        /// <param name="tableName">The table to view.</param>
        /// <returns>A list of column objects.</returns>
        public List <Column> DescribeTable(string tableName)
        {
            if (String.IsNullOrEmpty(tableName))
            {
                throw new ArgumentNullException(nameof(tableName));
            }

            List <Column> columns = new List <Column>();

            DataTable result = Query(SqliteHelper.LoadTableColumnsQuery(tableName));

            if (result != null && result.Rows.Count > 0)
            {
                foreach (DataRow currColumn in result.Rows)
                {
                    #region Process-Each-Column

                    /*
                     * public bool PrimaryKey;
                     * public string Name;
                     * public string DataType;
                     * public int? MaxLength;
                     * public bool Nullable;
                     */

                    Column tempColumn = new Column();

                    tempColumn.Name = currColumn["COLUMN_NAME"].ToString();

                    tempColumn.MaxLength = null;
                    if (currColumn.Table.Columns.Contains("CHARACTER_MAXIMUM_LENGTH"))
                    {
                        int maxLength = 0;
                        if (Int32.TryParse(currColumn["CHARACTER_MAXIMUM_LENGTH"].ToString(), out maxLength))
                        {
                            tempColumn.MaxLength = maxLength;
                        }
                    }

                    tempColumn.Type = Helper.DataTypeFromString(currColumn["DATA_TYPE"].ToString());

                    if (currColumn.Table.Columns.Contains("IS_NULLABLE"))
                    {
                        if (String.Compare(currColumn["IS_NULLABLE"].ToString(), "YES") == 0)
                        {
                            tempColumn.Nullable = true;
                        }
                        else
                        {
                            tempColumn.Nullable = false;
                        }
                    }
                    else if (currColumn.Table.Columns.Contains("IS_NOT_NULLABLE"))
                    {
                        tempColumn.Nullable = !(Convert.ToBoolean(currColumn["IS_NOT_NULLABLE"]));
                    }

                    if (currColumn["IS_PRIMARY_KEY"] != null &&
                        currColumn["IS_PRIMARY_KEY"] != DBNull.Value &&
                        !String.IsNullOrEmpty(currColumn["IS_PRIMARY_KEY"].ToString()))
                    {
                        tempColumn.PrimaryKey = Convert.ToBoolean(currColumn["IS_PRIMARY_KEY"]);
                    }

                    if (!columns.Exists(c => c.Name.Equals(tempColumn.Name)))
                    {
                        columns.Add(tempColumn);
                    }

                    #endregion
                }
            }

            return(columns);
        }
예제 #49
0
 internal static void Save()
 {
     Helper.WriteConfig(Instance);
 }
예제 #50
0
        public HttpResponseMessage GetPayloadFromToken()
        {
            HttpResponseMessage resMsg  = null;
            JwtPayload          payload = null;

            try
            {
                var securityKey = File.ReadAllText(ConfigurationManager.AppSettings["EncryptedPublicKey"])
                                  .Replace("-----BEGIN PUBLIC KEY-----\n", "")
                                  .Replace("\n-----END PUBLIC KEY-----\n", "");

                var jsonWebToken = Helper.GetJsonWebTokenFromRequestHeader(Request);
                if (!string.IsNullOrEmpty(jsonWebToken))
                {
                    SecurityToken validatedToken = Helper.GetValidatedToken(jsonWebToken, securityKey);
                    if (validatedToken != null)
                    {
                        payload = (validatedToken as JwtSecurityToken).Payload;

                        resMsg = Request.CreateResponse(HttpStatusCode.OK, payload);
                    }
                    else
                    {
                        resMsg = Request.CreateResponse(HttpStatusCode.OK, payload);
                    }
                }
                else
                {
                    resMsg = Request.CreateResponse(HttpStatusCode.BadRequest, @"Token does not exist.");

                    // Log message for non-existing token.
                    Helper.LogData(ConfigurationManager.AppSettings["ServiceLog"], $"[{Helper.ServerIP(Request.Headers.Host)}] [GetPayloadFromToken: Token does not exist.]");
                }

                // Log the Token that are being Invalidate Against and the result payload.
                Helper.LogData(ConfigurationManager.AppSettings["ServiceLog"], $"[{Helper.ServerIP(Request.Headers.Host)}] [GetPayloadFromToken: CALLED | JSON_WEB_TOKEN: {(!string.IsNullOrEmpty(jsonWebToken) ? "EXIST" : "NOT EXIST")}]");
            }
            catch (Exception ex)
            {
                Helper.LogData(ConfigurationManager.AppSettings["ExceptionLog"], $"[{Helper.ServerIP(Request.Headers.Host)}] [GetPayloadFromToken: {ex.Message}]");
                resMsg = Request.CreateResponse(HttpStatusCode.NotAcceptable, ex);
            }

            return(resMsg);
        }
예제 #51
0
        private Mesh CreateStarfieldMesh()
        {
            const int numberOfStars = 9110;

            var binaryDataFile = Resources.Load("Binary/Stars", typeof(TextAsset)) as TextAsset;

            if (binaryDataFile == null)
            {
                Debug.Log("Starfield: Binary data file reading error!");
                return(null);
            }

            var starsCIs = new List <CombineInstance>();

            using (var reader = new BinaryReader(new MemoryStream(binaryDataFile.bytes)))
            {
                for (int i = 0; i < numberOfStars - 1; i++)
                {
                    var star     = new StarfieldStar();
                    var starSize = StarsDistance / 100 * StarsScale;

                    // NOTE : Swap Z and Y...
                    star.Position = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
                    star.Color    = new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), 0);

                    star.Position = Vector3.Scale(star.Position, new Vector3(-1.0f, 1.0f, -1.0f));
                    star.Color.w  = new Vector3(star.Color.x, star.Color.y, star.Color.z).magnitude;

                    if (star.Color.w > 5.7f)
                    {
                        star.Color = Vector4.Normalize(star.Color) * 0.5f;
                    }

                    var ci = new CombineInstance
                    {
                        mesh      = MeshFactory.MakeBillboardQuad(starSize),
                        transform = MatrixHelper.BillboardMatrix(star.Position * StarsDistance)
                    };

                    ci.mesh.colors = new Color[] { star.Color, star.Color, star.Color, star.Color };

                    starsCIs.Add(ci);
                }
            }

            var mesh = new Mesh();

            mesh.CombineMeshes(starsCIs.ToArray());
            mesh.name      = string.Format("StarfieldMesh_({0})", Random.Range(float.MinValue, float.MaxValue));
            mesh.bounds    = new Bounds(Vector3.zero, new Vector3(1e8f, 1e8f, 1e8f));
            mesh.hideFlags = HideFlags.DontSave;

            #region Cleanup

            foreach (var ci in starsCIs)
            {
                Helper.Destroy(ci.mesh);
            }

            starsCIs.Clear();

            GC.Collect();

            #endregion

            return(mesh);
        }
예제 #52
0
#pragma warning restore IDE1006

        internal static void Load()
        {
            Instance = Helper.ReadConfig <ModConfig> ();
        }
 private void InitializePage()
 {
     gridDocuments.TopToolbarItems += string.Format("<a class=\"btn btn-default\" href=\"/PageLoader.aspx?c={0}\">{1}</a>",
                                                    Helper.Encrypt((int)Arad.SMS.Gateway.Business.UserControls.UI_Users_User, Session),
                                                    Language.GetString("Cancel"));
 }
예제 #54
0
 public void Test(decimal x, decimal expected, decimal tolerance)
 {
     tolerance = Helper.GetScaledTolerance(expected, (int)tolerance, true);
     Assert.That(DecimalEx.Cos(x), Is.EqualTo(expected).Within(tolerance));
 }
            private void InitUIComponents(View rootView)
            {
                mListView = rootView.FindViewById(Resource.Id.list_view) as ListView;
                TurnOffListViewDecoration(mListView);
                mListView.Adapter = mAdapter;

                mBtnChannel        = rootView.FindViewById(Resource.Id.btn_channel) as ImageButton;
                mBtnChannel.Click += (sender, e) => {
                    if (OnChannelListClicked != null)
                    {
                        OnChannelListClicked(this, new EventArgs());
                    }
                };
                mBtnSend          = rootView.FindViewById(Resource.Id.btn_send) as Button;
                mBtnUpload        = rootView.FindViewById(Resource.Id.btn_upload) as ImageButton;
                mBtnUpload.Click += delegate {
                    Intent intent = new Intent();
                    intent.SetType("image/*");
                    intent.SetAction(Intent.ActionGetContent);
                    StartActivityForResult(Intent.CreateChooser(intent, "Select Picture"), REQUEST_PICK_IMAGE);
                };
                mProgressBtnUpload     = rootView.FindViewById(Resource.Id.progress_btn_upload) as ProgressBar;
                mEtxtMessage           = rootView.FindViewById(Resource.Id.etxt_message) as EditText;
                mEtxtMessage.KeyPress += (object sender, View.KeyEventArgs e) => {
                    if (e.KeyCode == Keycode.Enter)
                    {
                        if (e.Event.Action == KeyEventActions.Down)
                        {
                            Send();

                            e.Handled = true;
                        }
                    }
                    else
                    {
                        e.Handled = false;
                    }
                };

                mBtnSend.Enabled = false;
                mBtnSend.Click  += (object sender, EventArgs e) => {
                    Send();
                };

                mEtxtMessage.AfterTextChanged += (object sender, AfterTextChangedEventArgs e) => {
                    mBtnSend.Enabled = true;
                };
                mListView.Touch += (object sender, View.TouchEventArgs e) => {
                    Helper.HideKeyboard(this.Activity);
                    e.Handled = false;
                };
                mListView.ScrollStateChanged += (s, args) => {
                    if (args.ScrollState == ScrollState.Idle)
                    {
                        if (args.View.FirstVisiblePosition == 0 && args.View.ChildCount > 0 && args.View.GetChildAt(0).Top == 0)
                        {
                            var mMessageListQuery = SendBirdSDK.QueryMessageList(SendBirdSDK.GetChannelUrl());
                            mMessageListQuery.OnResult += (sender, e) => {
                                // mSyncContext.Post for RunOnUIThread
                                mSyncContext.Post(delegate {
                                    foreach (var messageModel in e.Messages)
                                    {
                                        mAdapter.AddMessageModel(messageModel);
                                    }

                                    mAdapter.NotifyDataSetChanged();
                                    mListView.SetSelection(e.Messages.Count);
                                }, null);
                            };
                            mMessageListQuery.Prev(mAdapter.GetMinMessageTimestamp(), 30);                              // Excute Query
                        }
                    }
                };

                // Register Cache
                // Get max available VM memory, exceeding this amount will throw an OutOfMemory exception.
                // Stored in kilobytes as LruCache takes an int in its constructor.
                var cacheSize = (int)(Java.Lang.Runtime.GetRuntime().MaxMemory() / 16);

                mMemoryCache = new ImageUtils.MemoryLimitedLruCache(cacheSize);
            }
예제 #56
0
 public void LoadFilterQuery()
 {
     Search   = Helper.GetQueryStringValue <string>("Search");
     AuthorId = Helper.GetQueryStringValue <string>("AuthorId");
 }
예제 #57
0
 public void SetPlayer(Transform player)
 {
     thisT = player;
     handT = Helper.FindChild("HandPos", thisT);
 }
 private static bool BoxUnboxToQ<T>(T o)
 {
     return Helper.Compare((EmptyStructGen<int>?)(object)o, Helper.Create(default(EmptyStructGen<int>)));
 }
예제 #59
0
파일: MSG0191.cs 프로젝트: ertprs/crm_fonte
        public Pollux.MSG0191 DefinirPropriedades(Endereco crm)
        {
            #region Msg
            Conta conta = new ContaService(this.Organizacao, this.IsOffline).BuscaConta(crm.Conta.Id);

            Pollux.MSG0191 xml = new Pollux.MSG0191(
                itb.RetornaSistema(itb.Sistema.CRM),
                Helper.Truncate(String.Format("{0} / {1}", crm.CodigoEndereco, conta.NomeAbreviado), 40)
                );

            #region campos-obrigatorios
            xml.CodigoCliente = (int)Convert.ToInt32(conta.CodigoMatriz);
            xml.CodigoEntrega = crm.CodigoEndereco;
            xml.NomeAbreviado = conta.NomeAbreviado;
            xml.Situacao      = crm.StatusAtivo ? (int)Enum.StateCode.Ativo : (int)Enum.StateCode.Inativo;
            xml.NomeEndereco  = crm.EnderecoNumero;
            xml.CEP           = crm.Cep.Replace("-", "").Replace(".", "");
            xml.Numero        = crm.Numero;
            xml.Bairro        = crm.Bairro;
            xml.NomeCidade    = crm.NomeCidade;
            xml.Cidade        = String.Format("{0},{1},{2}", crm.NomeCidade, crm.SiglaEstado, crm.NomePais);
            xml.UF            = crm.SiglaEstado;
            xml.Estado        = String.Format("{0},{1}", crm.NomePais, crm.SiglaEstado);
            xml.NomePais      = crm.NomePais;
            xml.Pais          = crm.NomePais;
            #endregion

            #region campos-nao-obrigatorios
            if (crm.CodigoTaxa.HasValue)
            {
                xml.CodigoTaxa = crm.CodigoTaxa;
            }

            if (crm.CodigoTipoEntrega.HasValue)
            {
                xml.CodigoTipoEntrega = crm.CodigoTipoEntrega;
            }

            if (!String.IsNullOrEmpty(crm.Identificacao))
            {
                xml.CpfCnpjCodEstrangeiro = crm.Identificacao;
            }

            if (!String.IsNullOrEmpty(crm.InscricaoEstadual))
            {
                xml.InscricaoEstadual = crm.InscricaoEstadual;
            }

            if (!String.IsNullOrEmpty(crm.Email))
            {
                xml.Email = crm.Email;
            }

            if (crm.TipoEndereco.HasValue)
            {
                xml.TipoEndereco = crm.TipoEndereco;
            }

            if (!String.IsNullOrEmpty(crm.CaixaPostal))
            {
                xml.CaixaPostal = crm.CaixaPostal;
            }

            if (!String.IsNullOrEmpty(crm.Complemento))
            {
                xml.Complemento = crm.Complemento;
            }

            if (!String.IsNullOrEmpty(crm.Observacao))
            {
                xml.Observacao = crm.Observacao;
            }
            #endregion

            #endregion
            return(xml);
        }
        public IList <Point_Measure_Fact> List_Point_Measure_Fact_Service(IList <RawDataDTO> list_raw_data_dto, ElementDTO element)
        {
            try
            {
                IList <Point_Measure_Fact> point_measure_facts = new List <Point_Measure_Fact>();
                Point_Measure_Fact         point_measure_fact;

                for (int j = 0; j < list_raw_data_dto.Count; j++)
                {
                    point_measure_fact = new Point_Measure_Fact();
                    try
                    {
                        point_measure_fact.Client_ID = 0;
                        point_measure_fact.DataRecordingFrequency = element.Recorded_Freq;

                        point_measure_fact.Date_ID = Convert.ToDateTime(list_raw_data_dto[j].TIMESTAMP).Date;

                        point_measure_fact.External_ID = list_raw_data_dto[j].ID.ToString();

                        point_measure_fact.Hour_ID = Convert.ToDateTime(list_raw_data_dto[j].TIMESTAMP.Value.ToString("yyyy-MM-dd HH:") + "00"); // 07/05/2015 11:00

                        point_measure_fact.Last_Update_Time = System.DateTime.Now;
                        point_measure_fact.Max_Value        = element.Max_Value;
                        point_measure_fact.Min_Value        = element.Min_Value;
                        point_measure_fact.Point_ID         = element.ID;
                        point_measure_fact.Schedule_ID      = 0;
                        point_measure_fact.Timestamp_From   = Convert.ToDateTime(list_raw_data_dto[j].TIMESTAMP);

                        if (j + 1 < list_raw_data_dto.Count)
                        {
                            point_measure_fact.Timestamp_To = Convert.ToDateTime(list_raw_data_dto[j + 1].TIMESTAMP);
                        }
                        else
                        {
                            point_measure_fact.Timestamp_To = Convert.ToDateTime(list_raw_data_dto[j].TIMESTAMP);
                        }

                        point_measure_fact.Unit_Of_Measurement = element.Unit.Unit_Name;
                        point_measure_fact.Raw_Value           = Convert.ToDouble(list_raw_data_dto[j].VALUE);
                        point_measure_fact.Point_Status        = list_raw_data_dto[j].STATUS_TAG;
                        //Iterpolation method check the spikes or wrong value
                        //  point_measure_fact.Value = Interpolation.InterPolateValue(list_raw_data_dto[j], element, point_measure_fact);

                        if (element.Value_Type == DataValueType.Totalised)
                        {
                            point_measure_fact.Value = Convert.ToDouble(list_raw_data_dto[j].VAL);
                        }
                        else
                        {
                            point_measure_fact.Value = Convert.ToDouble(list_raw_data_dto[j].VALUE);
                        }

                        point_measure_facts.Add(point_measure_fact);
                    }
                    catch (Exception ex)
                    {
                        Helper.WriteToFile("Error in Point mesaure fact service " + ex.Message + "-- Point Id " + element.ID);
                    }
                }
                return(point_measure_facts);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }