Пример #1
1
        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AppendHeader("Content-encoding", "");

            Random random = new Random();
            imgCaptcha.ImageUrl = imgCaptcha.ImageUrl + "?" + random.ToString();
        }
Пример #2
0
        static void Main(string[] args)
        {
            try
            {
                string url = "65.52.224.21:10000";

                var fs = File.Create(filename);
                fs.Close();

                Timer timer = new Timer(5000);
                timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
                timer.Start();

                for (int i = new Random().Next(0, 1000000); i >= 0; i++)
                {
                    try
                    {
                        var server = MongoServer.Create(string.Format("mongodb://{0}/?slaveOk=true", url));
                        server.Connect();

                        var db = server.GetDatabase("test");
                        var collection = db.GetCollection<BsonDocument>("numbers");
                        collection.Insert(new BsonDocument()
                        {
                            { i.ToString(), @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur venenatis, lectus viverra blandit faucibus, eros risus adipiscing ipsum, at iaculis magna neque in nibh. Nulla venenatis, purus in imperdiet aliquet, ligula ligula gravida lorem, et egestas justo tellus cursus elit. Nam ut metus leo. In et odio et ligula auctor vulputate. Nunc posuere erat at tortor molestie gravida. Vestibulum sodales nunc pharetra tellus aliquam et blandit risus suscipit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin erat leo, eleifend vitae hendrerit sollicitudin, eleifend vel neque. Sed et sapien nunc, at adipiscing dolor. Sed luctus mollis arcu, eu adipiscing risus suscipit nec. Aenean eu elit lacus, in dapibus sem. Aliquam est dui, porta vitae fringilla eget, tristique in neque. Aliquam eget nisl ac tellus sodales viverra. Nam mauris mauris, ornare placerat aliquet id, eleifend et mauris. Fusce iaculis condimentum aliquet. Nunc dictum massa nunc." }
                        });

                        insertCount++;

                        var query = Query.EQ(i.ToString(), @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur venenatis, lectus viverra blandit faucibus, eros risus adipiscing ipsum, at iaculis magna neque in nibh. Nulla venenatis, purus in imperdiet aliquet, ligula ligula gravida lorem, et egestas justo tellus cursus elit. Nam ut metus leo. In et odio et ligula auctor vulputate. Nunc posuere erat at tortor molestie gravida. Vestibulum sodales nunc pharetra tellus aliquam et blandit risus suscipit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin erat leo, eleifend vitae hendrerit sollicitudin, eleifend vel neque. Sed et sapien nunc, at adipiscing dolor. Sed luctus mollis arcu, eu adipiscing risus suscipit nec. Aenean eu elit lacus, in dapibus sem. Aliquam est dui, porta vitae fringilla eget, tristique in neque. Aliquam eget nisl ac tellus sodales viverra. Nam mauris mauris, ornare placerat aliquet id, eleifend et mauris. Fusce iaculis condimentum aliquet. Nunc dictum massa nunc.");
                        foreach (BsonDocument number in collection.Find(query))
                        {
                            var element = number.Elements.ToList()[1];
                            Console.WriteLine(string.Format("Name: {0} - Value : {1}[...]", element.Name, element.Value.AsString.Substring(0, 40)));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("erreur");
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            catch (Exception exx)
            {
                Console.WriteLine(exx.Message);
            }
            finally
            {
                Console.WriteLine("Appuyez sur une touche pour quitter");
                Console.ReadLine();
            }
        }
Пример #3
0
        public void Execute(IrcDotNet.IrcClient Client, string Channel, IrcDotNet.IrcUser Sender, string Message)
        {
            string[] words = Message.Trim().Split(' ');
            if (words.Length < 2 || words.Length > 2)
            {
                Client.LocalUser.SendMessage(Channel, "!random <start> <end>");
                return;
            }

            int start, end;
            try
            {
                start = Convert.ToInt32(words[0]);
                end = Convert.ToInt32(words[1]);
            }
            catch (Exception)
            {
                Client.LocalUser.SendMessage(Channel, "Numbers please");
                return;
            }

            int random = new Random().Next(start, end + 1);

            Client.LocalUser.SendMessage(Channel, random.ToString());
        }
Пример #4
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var tokenReportIdentifier = context.Request.QueryString[Constants.KindOfReportParameter];
                var reportService = CreateInstanceBasedOnToken(tokenReportIdentifier);

                //Retrieve the class name parameters
                var classNames = new StringDictionary();
                foreach (var styleName in typeof (StyleName).GetFields())
                    classNames.Add(styleName.Name, context.Request[styleName.GetValue(null).ToString()]);

                var textResponse = reportService.getReport(context.Request.QueryString);

                //it waits 1 up to 10 seconds
                var rnd = new Random(DateTime.Now.Millisecond).Next(1, 7);
                Thread.Sleep(rnd*1000);
                Log.Debug(GetType(),
                          "Time loading the report: " + rnd.ToString(CultureInfo.InvariantCulture) + " seconds");
                // *** end ***
                textResponse = ReportHelper.FormatResultTokens(textResponse, classNames);

                if (!String.IsNullOrEmpty(context.Request[Constants.JsonCallbackParameter]))
                    textResponse = String.Format(CultureInfo.InvariantCulture, "{0}({1});",
                                                 context.Request[Constants.JsonCallbackParameter], textResponse);

                context.Response.StatusCode = (int) HttpStatusCode.OK;
                context.Response.ContentType = "application/json";
                context.Response.Write(textResponse);
            }
            catch (Exception ex)
            {
                Log.LogException(GetType(), ex);
            }
        }
Пример #5
0
        public ActionResult CreateNewRoom()
        {
            var newRoomNumber = new Random()
                .ToEnumerable(r => r.Next(100, 10000))
                .First(n => this.Db.Rooms.Any(room => room.RoomNumber == n) == false);

            var urlOfThisRoom = Url.AppUrl() + Url.Action("Room", new { id = newRoomNumber });
            var bitly = Bitly.Default;
            var shortUrlOfThisRoom = bitly.Status == Bitly.StatusType.Available ?
#if DEBUG
                bitly.ShortenUrl("http://asktheaudiencenow.azurewebsites.net/Room/" + newRoomNumber.ToString()) : "";
#else
                bitly.ShortenUrl(urlOfThisRoom) : "";
#endif

            var options = new[] { 
                new Option{ DisplayOrder = 1, Text = "Yes" },
                new Option{ DisplayOrder = 2, Text = "No"},
            }.ToList();

            this.Db.Rooms.Add(new Room
            {
                RoomNumber = newRoomNumber,
                OwnerUserID = this.User.Identity.Name,
                Options = options,
                Url = urlOfThisRoom,
                ShortUrl = shortUrlOfThisRoom
            });
            this.Db.SaveChanges();

            return RedirectToAction("Room", new { id = newRoomNumber });
        }
        public HttpResponseMessage DiceRoll(string triggerState,
                                        [Metadata("Number of Sides", "Number of sides that should be on the die that is rolled")]
                                        int numberOfSides,
                                        [Metadata("Target Number", "Trigger will fire if dice roll is above this number")]
                                        int targetNumber)
        {
            // Validate configuration
            if (numberOfSides <= 0)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                        "Bad configuration. Dice require 1 or more sides");
            }

            int lastRoll = 0;
            int.TryParse(triggerState, out lastRoll);
            int thisRoll = new Random().Next(numberOfSides);

            // Roll the dice
            if (thisRoll >= targetNumber /* We've hit or exceeded the target */
                    && thisRoll != lastRoll /* And this dice roll isn't the same as the last */)
            {
                // Let the Logic App know the dice roll matched
                return Request.EventTriggered(new SamplePollingResult(thisRoll),
                                                triggerState: thisRoll.ToString(),
                                                pollAgain: TimeSpan.FromSeconds(30)); 
            }
            else
            {
                // Let the Logic App know we don't have any data for it
                return Request.EventWaitPoll(retryDelay: null, triggerState: triggerState);

            }

        }
Пример #7
0
        public static string SimpleEncrypt(string str, string key)
        {
            string result;

            if (string.IsNullOrEmpty(str))
            {
                result = string.Empty;
            }
            else
            {
                int num;
                int num2;
                int num3;
                StringUtils.GetSimpleEncryptKey(key, out num, out num2, out num3);
                int num4 = new System.Random().Next(100);
                num  += num4;
                num2 += num4;
                num3 += num4;
                string text  = num4.ToString("x2");
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
                byte[] array = bytes;
                for (int i = 0; i < array.Length; i++)
                {
                    byte b  = array[i];
                    byte b2 = (byte)((int)b ^ num >> 8);
                    text += b2.ToString("x2");
                    num   = ((int)b2 + num) * num2 + num3;
                }
                result = text;
            }
            return(result);
        }
        public void ZAP()
        {
            var score = new Random().Next(32);

            Debug.Print("Zapping for " + score);
            _queueClient.CreateQueueMessage(score.ToString());
        }
        public void CHOMP()
        {
            var score = new Random().Next(16);

            Debug.Print("Chomping for " + score);
            _queueClient.CreateQueueMessage(score.ToString());
        }
Пример #10
0
 protected int Login_Input()
 {
     UserLoginStatus loginStatus = new UserLoginStatus();
     UserInfo objUserInfo = UserController.ValidateUser(PortalId, tbUsername.Text, tbPassword.Text, "", PortalSettings.PortalName, Request.UserHostAddress, ref loginStatus);
     if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER)
     {
         UserController.UserLogin(PortalId, objUserInfo, PortalSettings.PortalName, Request.UserHostAddress, false);
         if (cbRemember.Checked)
         {
             // Set settings
             int random = new Random().Next();
             ModuleController obModule = new ModuleController();
             obModule.UpdateModuleSetting(ModuleId, tbUsername.Text, random.ToString());
             // Set cookie
             HttpCookie obCookie = new HttpCookie(cookie_name());
             obCookie.Value = string.Format("{0}_{1}", random, tbUsername.Text);
             obCookie.Expires = DateTime.Today.AddMonths(3);
             Response.Cookies.Add(obCookie);
             obCookie = new HttpCookie("EOFFICE");
             obCookie.Value = Request.ApplicationPath;
             obCookie.Expires = DateTime.Today.AddYears(1);
             obCookie.HttpOnly = false;
             Response.Cookies.Add(obCookie);
         }
         return 1;
     }
     else
     {
         lbError.Text = "Tên đăng nhập hoặc Mật khẩu không chính xác";
         return 0;
     }
 }
Пример #11
0
        public string Generatetxnid()
        {
            Random rnd = new Random();
            string strHash = Generatehash512(rnd.ToString() + DateTime.Now);
            //string txnid1 = strHash.ToString().Substring(0, 20);

            return strHash.ToString().Substring(0, 20);
        }
        public void LoadPage() {
            var i1 = new MGMixAndMatchItems();
            var i2 = new MGMixAndMatchItems();
            var i3 = new MGMixAndMatchItems();
            MGMixAndMatch.Get3RandomItems(int.Parse(MMID.Text), out i1, out i2, out i3);

            MGMixAndMatchItems correctItem = null;
            var correctItemNumber = new Random(DateTime.Now.Millisecond).Next(1, 3);
            switch(correctItemNumber) {
                case 1:
                    correctItem = i1;
                    break;
                case 2:
                    correctItem = i2;
                    break;
                case 3:
                    correctItem = i3;
                    break;
            }

            var difficulty = int.Parse(Difficulty.Text);

            if(correctItem != null) {
                MMIID.Text = correctItem.MMIID.ToString();
                StringBuilder audio = new StringBuilder(MixMatchBasePath);

                switch(difficulty) {
                    case 2:
                        //medium
                        lblMixMatch.Text = correctItem.MediumLabel;
                        audio.AppendFormat("m_{0}.mp3", MMIID.Text);
                        break;
                    case 3:
                        //hard
                        lblMixMatch.Text = correctItem.HardLabel;
                        audio.AppendFormat("h_{0}.mp3", MMIID.Text);
                        break;
                    default:
                        lblMixMatch.Text = correctItem.EasyLabel;
                        audio.AppendFormat("e_{0}.mp3", MMIID.Text);
                        break;
                }

                if(System.IO.File.Exists(Server.MapPath(audio.ToString()))) {
                    lblSound.Text = string.Format(
                        "<audio controls><source src='{0}' type='audio/mpeg'>Your browser does not support this audio format.</audio>",
                        VirtualPathUtility.ToAbsolute(audio.ToString()));
                    pnlAudio.Visible = true;
                }
            }

            Correct.Text = correctItemNumber.ToString();

            btn1.ImageUrl = string.Format("{0}{1}.png", MixMatchBasePath, i1.MMIID);
            btn2.ImageUrl = string.Format("{0}{1}.png", MixMatchBasePath, i2.MMIID);
            btn3.ImageUrl = string.Format("{0}{1}.png", MixMatchBasePath, i3.MMIID);
        }
Пример #13
0
        private void timer_tick(object sender, object e)
        {
            Random rand1 = new Random();
            answer = rand1.Next(1, 75);
            List<Data> data = new List<Data>();
            data.Add(new Data() { Category = rand1.ToString(), Value = answer });

            this.Graph1.DataContext = data;
        }
Пример #14
0
        private bool ValidateOperation()
        {
            return true;

            Thread.Sleep(3000);
            var validateResult = new Random().Next(0, 2) == 1 ? true : false;
            Console.WriteLine("Thread:" + Thread.CurrentThread.ManagedThreadId + "   Validate " + validateResult.ToString());
            return validateResult;
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetPictureid()
        {
            string id = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString().PadLeft(2, '0') + System.DateTime.Now.Day.ToString().PadLeft(2, '0') + System.DateTime.Now.Hour.ToString().PadLeft(2, '0') + System.DateTime.Now.Minute.ToString().PadLeft(2, '0') + System.DateTime.Now.Millisecond.ToString().PadLeft(3, '0');
            int    i  = new System.Random().Next(0, 5);
            int    k  = new System.Random().Next(0, 9);

            id = id + i.ToString() + k.ToString();
            return(id);
        }
 public string RandMD5()
 {
     var res = String.Empty;
     var source = new Random();
     using (MD5 md5Hash = MD5.Create())
     {
         res = GetMd5Hash(md5Hash, source.ToString());
     }
     return res;
 }
Пример #17
0
 public OrderShippingConfirmation SendRequestForDelivery(Order order)
 {
     var randomDelay = new Random().Next(10); 
     var trackId = new Random().Next(10000000);
     return new OrderShippingConfirmation()
     {
         ExpectedShipDate = DateTime.Today.AddDays(randomDelay),
         TrackingId = trackId.ToString()
     };
 }
Пример #18
0
 public object createPk()
 {
     int rangdomNum=new Random().Next(1000,9999);
     string pk = string.Format("{0}{1}"
         , DateTime.Now.ToString("yyyyMMddHHmmss")
         ,rangdomNum.ToString()
     );
     Thread.Sleep(50);
     return pk;
 }
Пример #19
0
        //==== Generate Random Number for Account ============================//

        private static string GenerateAccount()
        {
            Random random = new System.Random();
            int    value  = random.Next(0, 1000000); //returns integer of 0-1000000

            var byteArray = new byte[256];

            random.NextBytes(byteArray);//fill with random bytes
            return(random.ToString());
        }
 public void should_handle_one_number()
 {
     //arrange
     var calc = new StringCalculator();
     var randomNumber = new Random().Next(10);
     //act
     var result = calc.Add(randomNumber.ToString());
     //accert
     result.ShouldBeEquivalentTo(randomNumber);
 }
Пример #21
0
 static void Main(string[] args)
 {
     try
     {
         Win32Native.FreeConsole();
         string path    = string.Empty;
         string command = ConfigurationManager.AppSettings["WebServerCommand"];
         if (!File.Exists(command))
         {
             LogMessage("Web server does not exist: " + command);
             return;
         }
         string commandArgs = string.Empty;
         int    r           = new System.Random().Next(1024, 9000);
         string port        = r.ToString();
         if ((args.Length == 1) && !args[0].Contains("vshost.exe"))
         {
             path = args[0];
         }
         else
         {
             path = ConfigurationManager.AppSettings["DefaultDirectory"];
             if (!Directory.Exists(path))
             {
                 LogMessage("Path does not exist: " + path);
                 return;
             }
         }
         commandArgs = commandArgs + " /path:\"" + path + "\"";
         commandArgs = commandArgs + " /port:";
         commandArgs = commandArgs + port;
         commandArgs = commandArgs + " /vpath: \" / ";
         commandArgs = commandArgs + path.Substring(path.LastIndexOf(@"\\") + 1);
         commandArgs = commandArgs + "\\\"";
         LogMessage("path: " + path);
         LogMessage("commandArgs: " + commandArgs);
         ProcessStartInfo info = new ProcessStartInfo();
         info.Arguments        = commandArgs;
         info.CreateNoWindow   = true;
         info.FileName         = command;
         info.UseShellExecute  = false;
         info.WorkingDirectory = command.Substring(0, command.LastIndexOf(Path.DirectorySeparatorChar));
         Process.Start(info);
         string starupDelayStr = string.Empty;
         int    startupDelay   = 1000;
         int.TryParse(ConfigurationManager.AppSettings["StartupDelay"], out startupDelay);
         Thread.Sleep(startupDelay);
         Process.Start("http://localhost:" + port + "/");
     }
     catch (Exception ex)
     {
         LogMessage(ex.Message);
     }
 }
Пример #22
0
 public List<DbBuyer> GetNeastBuyerInfo(string groupName)
 {
     //消息分组  
     Groups.Add(Context.ConnectionId, groupName);
  
     //Clients.Group(groupName).addMessage(lisByer);
     var lisByer = new List<DbBuyer>();
     var _buyerid = new Random().Next(232432432);
     lisByer.Add(new DbBuyer() { BuyerUid = _buyerid.ToString(), Nick = "张三", Id = 1 , GoupName=groupName});
     return lisByer;
 }
Пример #23
0
        public frmP2PresourceDis()
        {
            InitializeComponent();

            // 窗口初始化数据
            IPAddress[] ips = Dns.GetHostAddresses("");
            tbxlocalip.Text =ips[3].ToString();
            int port = new Random().Next(48000, 50000);
            tbxlocalport.Text = port.ToString();
            tbxResourceName.Text = "Res01";
        }
Пример #24
0
 static void Main(string[] args)
 {
     try
     {
         Win32Native.FreeConsole();
         string path = string.Empty;
         string command = ConfigurationManager.AppSettings["WebServerCommand"];
         if (!File.Exists(command))
         {
             LogMessage("Web server does not exist: " + command);
             return;
         }
         string commandArgs = string.Empty;
         int r = new System.Random().Next(1024, 9000);
         string port = r.ToString();
         if ((args.Length == 1) && !args[0].Contains("vshost.exe"))
         {
             path = args[0];
         }
         else
         {
             path = ConfigurationManager.AppSettings["DefaultDirectory"];
             if (!Directory.Exists(path))
             {
                 LogMessage("Path does not exist: " + path);
                 return;
             }
         }
         commandArgs = commandArgs + " /path:\"" + path + "\"";
         commandArgs = commandArgs + " /port:";
         commandArgs = commandArgs + port;
         commandArgs = commandArgs + " /vpath: \" / ";
         commandArgs = commandArgs + path.Substring(path.LastIndexOf(@"\\") + 1);
         commandArgs = commandArgs + "\\\"";
         LogMessage("path: " + path);
         LogMessage("commandArgs: " + commandArgs);
         ProcessStartInfo info = new ProcessStartInfo();
         info.Arguments = commandArgs;
         info.CreateNoWindow = true;
         info.FileName = command;
         info.UseShellExecute = false;
         info.WorkingDirectory = command.Substring(0, command.LastIndexOf(Path.DirectorySeparatorChar));
         Process.Start(info);
         string starupDelayStr = string.Empty;
         int startupDelay = 1000;
         int.TryParse(ConfigurationManager.AppSettings["StartupDelay"], out startupDelay);
         Thread.Sleep(startupDelay);
         Process.Start("http://localhost:" + port + "/");
     }
     catch (Exception ex)
     {
         LogMessage(ex.Message);
     }
 }
Пример #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int x = new Random().Next(100);
            CookieUsers cuser = new CookieUsers(Global.ClientPool.ClientList[Global.PropertiesBucket], "COOKIE" + x.ToString());
            cuser.CookieName = "NOVO_IME";
            cuser.CookieValue = "2222";
            cuser.NumUsers = x;

            cuser.Add();
            cuser.InSync = false;
            cuser.Refresh();
            cuser.CookieName = "ime " + x.ToString();
            cuser.Set();

            CookieCounter counter = new CookieCounter(Global.ClientPool.ClientList[Global.WordBucket]);
            counter.Key = CookieCounter.GetFullKey(x, Convert.ToByte(DateTime.Now.Day));

            counter.Increment(1);
            counter.Refresh();
            Response.Write("// " + counter.Value.ToString());
        }
        public void should_handle_one_digit()
        {
            //arrange
            var calc = new StringCalculator();
            var d = new Random().Next(10);

            //act
            var result = calc.Add(d.ToString());

            //assert
            result.ShouldBeEquivalentTo(d);
        }
Пример #27
0
        public void TryStuff()
        {
            RandNum = new Random().Next(100);
            RandString = RandNum.ToString() + "abc";

            // checks whats been added to il for static constructor

            // read in static consructor with decompiler and see what load field value is set to

            var aa = typeof(StaticMan);

            var bb = typeof(StaticTemplateClass<int>);

            var fieldVal = TestField;

            /*var z = typeof(StaticTemplateClass<int>);

            foreach (var x in z.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static).OrderBy(f => f.Name))
            {
                var name = x.Name;

                var value = x.GetValue(null);

                int i = 0;
                i++;
            }*/

            try
            {
                StaticMan.HolyCow();

                var a = new NestedClass();

                string yy = null;
                yy = testVar;
                //testVar = "hello";

                a.DoStuff();

                var x = new int[] { 1, 2, 3, 4 };

                var y = x.Where(i => i > 2).ToArray();
            }
            catch (Exception ex)
            {

            }

            var t = new LibClass();
            t.TestMe = 5;
            t.DoMoreStuff();
        }
        public ActionResult GenerateNewOrderId()
        {
            var boleto = db.Boleto.FirstOrDefault();

            String numeroPedido = new Random().Next(99999).ToString() + DateTime.Now.Millisecond.ToString();
            boleto.order_id = numeroPedido.ToString() + "ABC";
            boleto.numero_pedido = numeroPedido;

            db.SaveChanges();

            ViewBag.numeroPedido = numeroPedido;

            return View("FormBoleto", boleto);
        }
Пример #29
0
        public ContactStore(string server, string database, string username, string password)
        {
            MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder();
            csb.Server = server;
            csb.UserID = username;
            csb.Password = password;

            // Log in using the default DB, and check if the store exists
            using (MySqlConnection testConnection = new MySqlConnection(csb.ConnectionString))
            {
                testConnection.Open();
                using (MySqlCommand cmd = testConnection.CreateCommand())
                {
                    cmd.CommandText = "SELECT schema_name FROM information_schema.schemata WHERE schema_name=?dbName;";
                    cmd.Parameters.AddWithValue("?dbName", database);
                    using (MySqlDataReader reader = cmd.ExecuteReader())
                        if (!reader.Read())
                            throw new DatabaseNotFoundException();
                }
            }

            // Now we know it exists, do something sensible with it!
            csb.Database = database;
            m_ConnectionString = csb.ConnectionString;
            m_Connection = new MySqlConnection(csb.ConnectionString);
            m_Connection.Open();

            DBMigrations.DbMigrator.UpgradeDatabase(m_Connection, DatabaseType.MySQL);

            using (MySqlCommand cmd = m_Connection.CreateCommand())
            {
                cmd.CommandText = "SELECT id FROM sources WHERE `default`=1;";
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    if (!reader.Read() || reader.IsDBNull(0))
                    {
                        m_SourceId = new Random().Next();
                        cmd.CommandText = "INSERT INTO sources (id, callsign, `default`) VALUES (?id, ?callsign, 1);";
                        cmd.Parameters.AddWithValue("?id", m_SourceId);
                        cmd.Parameters.AddWithValue("?callsign", m_SourceId.ToString()); // TODO: should really ask the user for this
                        reader.Close();
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        m_SourceId = reader.GetInt32(0);
                    }
                }
            }
        }
Пример #30
0
		public static string MakeTempFilename(string directory, string fileNamePrefix)
		{
			int num = new Random().Next();
			string text;
			while (true)
			{
				text = Path.Combine(directory, string.Format("{0}-{1}", fileNamePrefix, num.ToString()));
				if (!File.Exists(text))
				{
					break;
				}
				num++;
			}
			return text;
		}
Пример #31
0
        /// <summary>
        /// 记录当前用户到Cookie
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        public static void AddUserToCookie(string email,string password,bool rememberme)
        {
            UtopiaService utopiaService=new UtopiaService();
            Uto_User user=utopiaService.GetUserByEmail(email);

            HttpCookie cookie=new HttpCookie("authCookie");
            int randomNum = new Random().Next(100);
            cookie.Values["authAdd"] = randomNum.ToString();
            cookie.Values["authCookie"] = Utility.EncodeCookie(user.UserId,randomNum);

            if (rememberme)
                cookie.Expires = DateTime.Now.AddDays(7);

            HttpContext.Current.Response.AppendCookie(cookie);
        }
Пример #32
0
        /// <summary>
        /// Get the parameters as a FormParameter array
        /// </summary>
        /// <returns></returns>
        public override FormParameter[] Parameters()
        {
            var fileCondition = new Random().Next();

            var parameters = new List<FormParameter>
            {
                new FormParameter("file", $"[\"{fileCondition}\"]"),
                new FormParameter("type", "\"file\""),
                new FormParameter("create_list", $"{CreateList.ToString().ToLowerInvariant()}"),
                new FormParameter("destination", $"\"{Destination}\""),
                // From the documentation, the file must always be the last parameter
                new FileFormDataParameter(fileCondition.ToString(), Filename, File)
            };

            return parameters.ToArray();
        }
Пример #33
0
    void GetSeed()
    {
        if (seed == "seed")
        {
            seedGen = new System.Random(randomGen.Next(0, 100).GetHashCode());
        }
        else
        {
            seedGen = new System.Random(seed.GetHashCode());
        }

        if (debug)
        {
            Debug.Log("Using seed : " + seedGen.ToString());
        }
    }
Пример #34
0
        internal override void Init(CommandGroupBuilder cgb)
        {
            cgb.CreateCommand(Module.Prefix + "scsc")
                .Description("Starts an instance of cross server channel. You will get a token as a DM " +
                             $"that other people will use to tune in to the same instance. **Bot Owner Only.** | `{Prefix}scsc`")
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    var token = new Random().Next();
                    var set = new HashSet<Channel>();
                    if (Subscribers.TryAdd(token, set))
                    {
                        set.Add(e.Channel);
                        await e.User.SendMessage("This is your CSC token:" + token.ToString()).ConfigureAwait(false);
                    }
                });

            cgb.CreateCommand(Module.Prefix + "jcsc")
                .Description($"Joins current channel to an instance of cross server channel using the token. **Needs Manage Server Permissions.**| `{Prefix}jcsc`")
                .Parameter("token")
                .AddCheck(SimpleCheckers.ManageServer())
                .Do(async e =>
                {
                    int token;
                    if (!int.TryParse(e.GetArg("token"), out token))
                        return;
                    HashSet<Channel> set;
                    if (!Subscribers.TryGetValue(token, out set))
                        return;
                    set.Add(e.Channel);
                    await e.Channel.SendMessage(":ok:").ConfigureAwait(false);
                });

            cgb.CreateCommand(Module.Prefix + "lcsc")
                .Description($"Leaves Cross server channel instance from this channel. **Needs Manage Server Permissions.**| `{Prefix}lcsc`")
                .AddCheck(SimpleCheckers.ManageServer())
                .Do(async e =>
                {
                    foreach (var subscriber in Subscribers)
                    {
                        subscriber.Value.Remove(e.Channel);
                    }
                    await e.Channel.SendMessage(":ok:").ConfigureAwait(false);
                });
        }
        public void CreateProjectSiteHandlerTest()
        {
            var projectId = new Random().Next(1000);

            Test.Handler<CreateSiteRequestHandler>()
                .ExpectReply<CreateSiteResponse>(m =>
                    m.ProjectId == projectId &&
                    m.SiteUrl.StartsWith(string.Format("https://sharepoint.yourdomain.edu.au/research/project{0}",projectId.ToString())) &&
                    m.ProvisioningRequestStatus == ProvisioningRequestStatus.Provisioned && 
                    m.RequestId > 0)
                .OnMessage<CreateSiteRequest>(m =>
                {
                    m.ProjectId = projectId;
                   // m.SiteTitle = "Kalman Smoothing to Achieve Parametric Continuity of Sample-Based Robot Motion Plans in the Presence of Obstacles and Kinodynamic Constraints";
                    m.SiteTitle = "Project "+ projectId +" Site Title";
                    m.SiteDescription = "Sampling is an effective approach to robot motion planning but inherently produces jagged trajectories. We present a new approach to trajectory smoothing. Results suggest that this algorithm performs well for holonomic and kinodynamically-constrained robots and offers several advantages over shortcut methods, which cannot incorporate kinodynamic constraints. Given an initial trajectory, the algorithm combines Kalman Smoothing with a pseudo-dynamics model and specified smoothness constraints to compute a new trajectory that achieves parametric continuity of degree $k$. The input is treated as a noisy observation to ensure that the smoothed trajectory satisfies the kinodynamic constraints of the robot. A noise parameter, which determines the amount of smoothing, can be adapted automatically along the path based on local uncertainty and distance to the nearest obstacle, and can also incorporate a sensor model if one is available. We evaluate the algorithm on examples including a holonomic robot and a kinodynamic robot with car-like dynamics. The resulting trajectories are smooth, collision-free, and obey the kinodynamic robot constraints in environments with narrow passages and dense obstacles.";
                    m.UsersInRoles = _usersInRoles;
                });
        }
Пример #36
0
        public override string SampleMethod()
        {
            List <string> baseList = new List <string>();

            for (int i = 0; i < 255; i++)
            {
                baseList.Add(i.ToString());
            }

            int randomResult = new System.Random().Next() % 256;

            foreach (var item in baseList)
            {
                if (randomResult.ToString() == item)
                {
                    return(item);
                }
            }

            return(@"");
        }
Пример #37
0
        public override string SampleMethod()
        {
            List <string> baseList = new List <string>();

            for (int i = 0; i < 255; i++)
            {
                baseList.Add(i.ToString());
            }

            int randomResult = new System.Random().Next() % 256;

            foreach (var item in baseList)
            {
                if (randomResult.ToString() == item)
                {
                    return(item);
                }
            }

            var baseInstance = new BaseClass();
            var subInstance  = new SubClass();
            var fsubInstance = new FinallySubClass();

            baseInstance.DoSomethingA();
            baseInstance.DoSomethingA2();
            baseInstance.DoSomethingB();
            BaseClass.DoSomethingC();

            subInstance.DoSomethingA();
            subInstance.DoSomethingA2();
            subInstance.DoSomethingB();
            SubClass.DoSomethingC();

            fsubInstance.DoSomethingA();
            fsubInstance.DoSomethingA2();
            fsubInstance.DoSomethingB();
            FinallySubClass.DoSomethingC();

            return(@"");
        }
Пример #38
0
        public OAuthRequest(OAuthRequestObject request, OAuthClient client, OAuthToken token, OAuthSignature signature, Dictionary <string, string> body = null)
        {
            var uri        = new Uri(request.Url);
            var parameters = new Dictionary <string, string>();

            parameters.Add("oauth_consumer_key", client.ConsumerKey);
            if (token != null)
            {
                parameters.Add("oauth_token", token.Token);
            }

            var urlWithoutQuery = $"{uri.Scheme}://{uri.Authority}{uri.LocalPath}";
            var timestamp       = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var nonce           = new System.Random().Next(100000000);
            var queryParams     = HttpUtility.ParseQueryString(uri.Query);

            foreach (var key in queryParams.AllKeys)
            {
                parameters.Add(key, queryParams[key]);
            }
            if (body != null)
            {
                foreach (var kvp in body)
                {
                    parameters.Add(kvp.Key, kvp.Value);
                }
            }

            parameters.Add("oauth_timestamp", ((int)timestamp.TotalSeconds).ToString());
            parameters.Add("oauth_nonce", nonce.ToString());
            parameters.Add("oauth_version", Version);
            parameters.Add("oauth_signature_method", signature.Name);

            var oauthSignature = signature.GetSignature(request.Method, urlWithoutQuery, client, token, parameters);

            parameters.Add("oauth_signature", oauthSignature);
            m_parameters = parameters;
            m_request    = request;
        }
Пример #39
0
        /// <summary>
        ///     支付密码 6位数字支付密码
        /// </summary>
        /// <returns></returns>
        public static string PayPassWord()
        {
            var str = new System.Random().Next(100000, 999999);

            return(str.ToString().PadLeft(6, '0'));
        }
Пример #40
0
 public override String ToString()
 {
     return(_random.ToString());
 }