Inheritance: NancyModule
Exemplo n.º 1
0
        public async Task GetApiMinVersion()
        {
            var api = new Api(_serverCredential);
            var apiMinVersion = await api.GetApiMinVersion();

            Assert.True(10 <= apiMinVersion);
        }
Exemplo n.º 2
0
        public static void AddTestDataToIndex(Interface.IIndexService indexService, Api.Index index, string testData)
        {
            string[] lines = testData.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            string[] headers = lines[0].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in lines.Skip(1))
            {
                string[] items = line.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                var indexDocument = new Document();
                indexDocument.Id = items[0];
                indexDocument.Index = index.IndexName;
                indexDocument.Fields = new Api.KeyValuePairs();

                for (int i = 1; i < items.Length; i++)
                {
                    indexDocument.Fields.Add(headers[i], items[i]);
                }

                indexService.PerformCommand(
                    index.IndexName,
                    IndexCommand.NewCreate(indexDocument.Id, indexDocument.Fields));
            }

            indexService.PerformCommand(index.IndexName, IndexCommand.Commit);
            Thread.Sleep(100);
        }
Exemplo n.º 3
0
        public static FoundOps.Core.Models.CoreEntities.ContactInfo ConvertBack(Api.Models.ContactInfo contactInfoModel)
        {
            var contactInfo = new FoundOps.Core.Models.CoreEntities.ContactInfo
                {
                    Id = contactInfoModel.Id,
                    Type = contactInfoModel.Type,
                    Label = contactInfoModel.Label,
                    Data = contactInfoModel.Data,
                    ClientId = contactInfoModel.ClientId,
                    LocationId = contactInfoModel.LocationId,
                    CreatedDate = contactInfoModel.CreatedDate,
                    LastModified = contactInfoModel.LastModified,
                    LastModifyingUserId = contactInfoModel.LastModifyingUserId
                };

            //TODO Generalize this everywhere
            if (string.IsNullOrEmpty(contactInfo.Type))
                contactInfo.Type = "";
            if (string.IsNullOrEmpty(contactInfo.Label))
                contactInfo.Label = "";
            if (string.IsNullOrEmpty(contactInfo.Data))
                contactInfo.Data = "";

            return contactInfo;
        }
Exemplo n.º 4
0
        public void ResolvePackageSources(Api.IRequest requestObject) {
            if (requestObject == null) {
                throw new ArgumentNullException("requestObject");
            }

            requestObject.Debug("Called DummyProvider ResolvePackageSources");
        }
Exemplo n.º 5
0
        public void InitializeProvider(Api.IRequest requestObject) {
            if (requestObject == null) {
                throw new ArgumentNullException("requestObject");
            }

            requestObject.Debug("Called DummyProvider InitializeProvider");
        }
Exemplo n.º 6
0
        public async Task Test()
        {
            var api = new Api();

            var startElysee = new GeoLocation
            {
                Longitude = 2.316749,
                Latitude = 48.870663
            };
            var endTourEiffel = new GeoLocation
            {
                Longitude = 2.294555,
                Latitude = 48.858465
            };
            var arrivalTime = DateTimeOffset.Now.AddDays(3);

            var networks = new List<Network> {Network.Bus};

            var s =
                await
                    api.GetItinerary(startElysee, endTourEiffel, null, arrivalTime, networks, JourneyPreference.MinWait,
                        false, false, false);

            Assert.False(string.IsNullOrWhiteSpace(s));
        }
Exemplo n.º 7
0
 public TelegramWorker(string botTokenKey)
 {
     _botTokenKey = botTokenKey;
     _telegramApi = new Api(_botTokenKey);
     _logger = FullLogger.Init();
     _dialogManager = DialogManager.Init();
 }
 public Job(Api api,DroneSettings droneSettings, OmniRecordManager omniRecordManager,CreativePackagesStore creativePackagesStore)
 {
     _creativePackagesStore = creativePackagesStore;
     _omniRecordManager = omniRecordManager;
     _droneSettings = droneSettings;
     _api = api;
 }
 public async Task Repository_Establishments_Single_Return_One_Record()
 {
     var api = new Api<EstablishmentsModel>(new Mock<ILog>().Object);
     var result = await api.GetAsync("Establishments/1", string.Empty);
     Assert.IsNotNull(result);
     Assert.That(!string.IsNullOrEmpty(result.RatingValue));
 }
Exemplo n.º 10
0
 /// <summary>
 /// Constructor
 /// </summary>
 public VManageSessions(Api.Client.EventDefinition eventDefinition)
 {
     // TODO: Complete member initialization
     InitializeComponent();
     this.Loaded += VManageSessions_Loaded;
     (this.DataContext as ManageSessionsViewModel).EventDefinition = eventDefinition;
 }
		public WebSyncPreferencesWidget (Api.OAuth oauth, string server, EventHandler requiredPrefChanged) : base (false, 5)
		{
			this.oauth = oauth;
			
			Gtk.Table prefsTable = new Gtk.Table (1, 2, false);
			prefsTable.RowSpacing = 5;
			prefsTable.ColumnSpacing = 10;

			serverEntry = new Gtk.Entry ();
			serverEntry.Text = server;
			AddRow (prefsTable, serverEntry, Catalog.GetString ("Se_rver:"), 0);
			
			Add (prefsTable);

			authButton = new Gtk.Button ();
			// TODO: If Auth is valid, this text should change
			if (!Auth.IsAccessToken)
				authButton.Label = Catalog.GetString ("Connect to Server");
			else {
				authButton.Label = Catalog.GetString ("Connected");
				authButton.Sensitive = false;
			}
			authButton.Clicked += OnAuthButtonClicked;

			serverEntry.Changed += delegate {
				Auth = null;
			};
			serverEntry.Changed += requiredPrefChanged;

			Add (authButton);

			// TODO: Add a section that shows the user something to verify they put
			//       in the right URL...something that constructs their user URL, maybe?
			ShowAll ();
		}
 public override void PreMethodCall(Api.Interfaces.IApiMethodCall method, ASC.Api.Impl.ApiContext context, System.Collections.Generic.IEnumerable<object> arguments)
 {
     //Log method call
     TryLog(LogEntry.Actions.BeforeCall,method,context, null);
     base.PreMethodCall(method, context, arguments);
     Sw.Start();
 }
Exemplo n.º 13
0
		/// <summary>
		/// Gets the edit model for the category with the given id.
		/// </summary>
		/// <param name="api">The current api</param>
		/// <param name="id">The unique id</param>
		/// <returns>The edit model</returns>
		public static EditModel GetById(Api api, Guid id) {
			var category = api.Categories.GetSingle(id);

			if (category != null)
				return Mapper.Map<Piranha.Models.Category, EditModel>(category);
			return null;
		}
Exemplo n.º 14
0
		/// <summary>
		/// Tries to handle an incoming request.
		/// </summary>
		/// <param name="api">The current api</param>
		/// <param name="request">The incoming route request</param>
		/// <returns>The result</returns>
		public IResponse Handle(Api api, IRequest request) {
			// First try to get the alias for the complete url
			var alias = api.Aliases.GetSingle(request.RawUrl);

			if (alias == null) {
				if (request.Params.Length > 0) {
					// Try to get alias for the url without query
					alias = api.Aliases.GetSingle(request.Path);

					if (alias != null) {
						var response = request.RedirectResponse();

						response.IsPermanent = alias.IsPermanent;
						response.Url = alias.NewUrl + request.Query;

						return response;
					}
				}
			} else {
				var response = request.RedirectResponse();

				response.IsPermanent = alias.IsPermanent;
				response.Url = alias.NewUrl;

				return response;
			}
			return null;
		}
Exemplo n.º 15
0
        public void Setup()
        {
            string url = ConfigurationManager.AppSettings["url"];
            string clientKey = ConfigurationManager.AppSettings["client-key"];
            string clientSecret = ConfigurationManager.AppSettings["client-secret"];
            responsePath = ConfigurationManager.AppSettings["response-path"];

            Assert.IsNotNullOrEmpty(clientKey);
            Assert.IsNotNullOrEmpty(clientSecret);
            Assert.IsNotNullOrEmpty(url);
            // ReSharper disable UnusedVariable
            //##BEGIN EXAMPLE accessingapi##
            var api = new Api(url, clientKey, clientSecret);
            var tokenResponse = api.Authenticate();
            var rootLinks = api.Root;
            //##END EXAMPLE##
            // ReSharper restore UnusedVariable

            responses = ResponseReader.readResponses(responsePath);
            deserializer = new JsonDeserializer();
            TestUtils.Deserializer = deserializer;
             

            
        }
Exemplo n.º 16
0
    public DvbsDataLayout(Api.IniFile.Section iniSection)
    {
      this.satCount = iniSection.GetInt("satCount");
      this.satLength = iniSection.GetInt("satLength");
      this.transponderCount = iniSection.GetInt("transponderCount");
      this.transponderLength = iniSection.GetInt("transponderLength");
      this.sizeOfTransponderBlockHeader = 14 + transponderCount/8 + transponderCount*6 + 2;
      this.linkedListExtraDataLength = iniSection.GetInt("linkedListExtraDataLength");
      this.dvbsMaxChannelCount = iniSection.GetInt("dvbsChannelCount");
      this.dvbsChannelLength = iniSection.GetInt("dvbsChannelLength");
      this.lnbCount = iniSection.GetInt("lnbCount");
      this.lnbLength = iniSection.GetInt("lnbLength");
      this.satIndexFactor = iniSection.GetInt("satIndexFactor");
      if (satIndexFactor == 0)
        satIndexFactor = 2;

      this.dvbsSubblockLength = new[]
                                  {
                                    12, // header
                                    14 + 2 + this.satCount + this.satCount*this.satLength, // satellites
                                    sizeOfTransponderBlockHeader - 4 + transponderCount * transponderLength, // transponder
                                    12 + dvbsMaxChannelCount/8 + dvbsMaxChannelCount*sizeOfChannelLinkedListEntry + linkedListExtraDataLength + dvbsMaxChannelCount * dvbsChannelLength, // channels
                                    LnbBlockHeaderSize - 4 + lnbCount * lnbLength // sat/LNB-Config
                                  };
      
      foreach (int len in this.dvbsSubblockLength)
        this.dvbsBlockTotalLength += len + 4;
    }
Exemplo n.º 17
0
        private static void FullSearch()
        {
            ParamBuilder oParamBuilder = new ParamBuilder();
            SearchResults = new List<Item>();

            oParamBuilder.addParam("sid", StaticSessionSettings.sessionID);
            oParamBuilder.addParam("q", "");

            var oComm = new Api();
            var result = oComm.getResponseFromOrb<List<Item>>(Api.mediasearch, oParamBuilder.GetParamList());

            List<Item> Temp = new List<Item>();

            Temp = result;

            SearchResults.Clear();

            foreach (var item in Temp)
            {
                if (!string.IsNullOrWhiteSpace(item.field))
                    SearchResults.Add(item);
            }

            iveFullySearched = true;
        }
Exemplo n.º 18
0
        static async Task Run()
        {
            var Bot = new Api("Your Api Key");

            var me = await Bot.GetMe();

            Console.WriteLine("Hello my name is {0}", me.Username);

            var offset = 0;

            while (true)
            {
                var updates = await Bot.GetUpdates(offset);

                foreach (var update in updates)
                {
                    if (update.Message.Text != null)
                        await Bot.SendTextMessage(update.Message.Chat.Id, update.Message.Text);

                    offset = update.Id + 1;
                }

                await Task.Delay(1000);
            }

        }
Exemplo n.º 19
0
        public Functional()
        {
            var appEnv = CallContextServiceLocator.Locator.ServiceProvider.GetService(typeof(IApplicationEnvironment)) as IApplicationEnvironment;
            Debug.Assert(appEnv != null, "appEnv != null");
            var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath);
            builder.AddJsonFile("config.json");
            builder.AddJsonFile("config.private.json", true);
            var configuration = builder.Build();

            var uri = new Uri(configuration["ServerCredentialUri"]);
            var username = configuration["ServerCredentialUsername"];
            var password = configuration["ServerCredentialPassword"];

            _serverCredential = new ServerCredential(uri, username, password);

            _freeMusicTorrentFile =
                new HttpClient().GetByteArrayAsync(
                    new Uri("http://bt.etree.org/download.php/582271/hottuna2015-09-11.flac16.torrent")).Result;
            _freeMusicTorrentHash = "9ecc7229ff971d27552dd399509e188847dbbbf1";

            // Make sure there is no torrents before executing the tests
            var api = new Api(_serverCredential);
            var torrents = api.GetTorrents().Result;
            if (torrents.Any())
            {
                var result = api.Perform(Action.Removedata, torrents.Select(t => t.InfoHash)).Result;
                Assert.True(result);
            }
        }
Exemplo n.º 20
0
 public async Task Repository_Authority_AllAuthorities_Returns_All()
 {
     var api = new Api<AuthoritiesViewModel>(new Mock<ILog>().Object);
     var result = await api.GetAsync("Authorities", string.Empty);
     Assert.IsNotNull(result);
     Assert.That(result.Authorities.Any());
 }
 public async Task Repository_Establishments_AllAuthorities_Returns_All()
 {
     var api = new Api<EstablishmentsViewModel>(new Mock<ILog>().Object);
     var result = await api.GetAsync("Establishments?LocalAuthorityId=197", string.Empty);
     Assert.IsNotNull(result);
     Assert.That(result.Establishments.Any());
 }
Exemplo n.º 22
0
		/// <summary>
		/// Gets the edit model for the block with the given id.
		/// </summary>
		/// <param name="api">The current api</param>
		/// <param name="id">The unique id</param>
		/// <returns>The edit model</returns>
		public static EditModel GetById(Api api, Guid id) {
			var block = api.Blocks.GetSingle(id);

			if (block != null)
				return Mapper.Map<Piranha.Models.Block, EditModel>(block);
			return new EditModel();
		}
Exemplo n.º 23
0
 public PutioFileSystem(Api putio_api)
 {
     this.PutioApi = putio_api;
     this.OpenHandles = new Dictionary<Guid, PutioFileHandle>();
     this.Root = PutioFolder.GetRootFolder(this);
     this.DownloadManager = new DownloadManager(Constants.MAX_CONNECTIONS);
 }
Exemplo n.º 24
0
        public void GetDynamicOptions(string category, Api.IRequest requestObject) {
            if (requestObject == null) {
                throw new ArgumentNullException("requestObject");
            }

            requestObject.Debug("Called DummyProvider GetDynamicOptions");
        }
 public Job(Api api, LogsStore logsStore, DroneSettings droneSettings, OmniRecordManager omniRecordManager)
 {
     _omniRecordManager = omniRecordManager;
     _logsStore = logsStore;
     _droneSettings = droneSettings;
     _api = api;
 }
Exemplo n.º 26
0
		public int Execute(IEnumerable<string> args, IFileStorage fileSystem) {
			
			try {
				var interpreter = new Boo.Lang.Interpreter.InteractiveInterpreter2();

				var parser = new BooCommandLineParser(interpreter, args.ToArray());
				var api10 = new Api(parser, fileSystem);
				// api10.Parameters();

				interpreter.SetValue("api10", api10);

				
				CompilerContext context;
				try {
					context = interpreter.Eval(content);
				} catch (TargetInvocationException ex) {
					if (ex.InnerException == null) {
						throw ex.InnerException;
					}
					throw;
				}
				foreach (var e in context.Errors) {
					Console.WriteLine(e.ToString());
				}
				if (context.Errors.Count != 0) {
					return 2;
				}
			} catch (NonErrorTerminationException) {
				return 0;
			} catch (Exception ex) {
				WriteException(Console.Out, ex);
				return 1;
			}
			return 0;
		}
Exemplo n.º 27
0
 public static VehicleData GetVehicle( Api api, UserData user, RoutingProblemData problem )
 {
     TestData.CreateDemoData( problem, api );
     var vehicles = api.Navigate<VehicleDataSet>( problem.GetLink( "list-vehicles" ) );
     var vehicleLink = vehicles.Items.Find( v => v.Id == 1 );
     var vehicle = api.Navigate<VehicleData>(vehicleLink.GetLink("self"));
     return vehicle;
 }
Exemplo n.º 28
0
        public override void SetUp()
        {
            base.SetUp();
            
            worker = new MockApiWorker();

            api = new Api("facebook", System, Timers, Observers, worker);
        }
Exemplo n.º 29
0
 public void Init()
 {
     Account account = new Account("testcloud", "1234", "abcd");
     m_api = new Api(account);
     m_defaultRootPath = "http://res.cloudinary.com/testcloud/";
     m_defaultImgUpPath = m_defaultRootPath + "image/upload/";
     m_defaultVideoUpPath = m_defaultRootPath + "video/upload/";
 }
 public CreditCardController(Api application, 
                             QueryService query_service,
                             ICreditCardPaymentGateway credit_card_payment_gateway)
 {
     _queryService = query_service;
     _credit_card_payment_gateway = credit_card_payment_gateway;
     _application = application;
 }
Exemplo n.º 31
0
        public void RetrieveColumns()
        {
            bool     bit  = Any.Boolean;
            byte     b    = Any.Byte;
            short    i16  = Any.Int16;
            ushort   ui16 = Any.UInt16;
            int      i32  = Any.Int32;
            uint     ui32 = Any.UInt32;
            long     i64  = Any.Int64;
            ulong    ui64 = Any.UInt64;
            float    f    = Any.Float;
            double   d    = Any.Double;
            DateTime date = Any.DateTime;
            Guid     guid = Any.Guid;
            string   str  = Any.String;

            byte[] bytes = Any.BytesOfLength(1023);

            using (var trx = new Transaction(this.session))
                using (var update = new Update(this.session, this.tableid, JET_prep.Insert))
                {
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Boolean"], bit);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Byte"], b);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Int16"], i16);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["UInt16"], ui16);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Int32"], i32);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["UInt32"], ui32);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Int64"], i64);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["UInt64"], ui64);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Float"], f);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Double"], d);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["DateTime"], date);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Guid"], guid);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Unicode"], str, Encoding.Unicode);
                    Api.SetColumn(this.session, this.tableid, this.columnDict["Binary"], bytes);

                    update.SaveAndGotoBookmark();
                    trx.Commit(CommitTransactionGrbit.None);
                }

            var columnValues = new ColumnValue[]
            {
                new BoolColumnValue {
                    Columnid = this.columnDict["Boolean"]
                },
                new ByteColumnValue {
                    Columnid = this.columnDict["Byte"]
                },
                new Int16ColumnValue {
                    Columnid = this.columnDict["Int16"]
                },
                new UInt16ColumnValue {
                    Columnid = this.columnDict["UInt16"]
                },
                new Int32ColumnValue {
                    Columnid = this.columnDict["Int32"]
                },
                new UInt32ColumnValue {
                    Columnid = this.columnDict["UInt32"]
                },
                new Int64ColumnValue {
                    Columnid = this.columnDict["Int64"]
                },
                new UInt64ColumnValue {
                    Columnid = this.columnDict["UInt64"]
                },
                new FloatColumnValue {
                    Columnid = this.columnDict["Float"]
                },
                new DoubleColumnValue {
                    Columnid = this.columnDict["Double"]
                },
                new DateTimeColumnValue {
                    Columnid = this.columnDict["DateTime"]
                },
                new GuidColumnValue {
                    Columnid = this.columnDict["Guid"]
                },
                new StringColumnValue {
                    Columnid = this.columnDict["Unicode"]
                },
                new BytesColumnValue {
                    Columnid = this.columnDict["Binary"]
                },
            };

            Api.RetrieveColumns(this.session, this.tableid, columnValues);

            Assert.AreEqual(bit, columnValues[0].ValueAsObject);
            Assert.AreEqual(b, columnValues[1].ValueAsObject);
            Assert.AreEqual(i16, columnValues[2].ValueAsObject);
            Assert.AreEqual(ui16, columnValues[3].ValueAsObject);
            Assert.AreEqual(i32, columnValues[4].ValueAsObject);
            Assert.AreEqual(ui32, columnValues[5].ValueAsObject);
            Assert.AreEqual(i64, columnValues[6].ValueAsObject);
            Assert.AreEqual(ui64, columnValues[7].ValueAsObject);
            Assert.AreEqual(f, columnValues[8].ValueAsObject);
            Assert.AreEqual(d, columnValues[9].ValueAsObject);
            Assert.AreEqual(date, columnValues[10].ValueAsObject);
            Assert.AreEqual(guid, columnValues[11].ValueAsObject);
            Assert.AreEqual(str, columnValues[12].ValueAsObject);
            CollectionAssert.AreEqual(bytes, columnValues[13].ValueAsObject as byte[]);
        }
Exemplo n.º 32
0
        public void CreatePayment_ReturnsANewPayment()
        {
            _todelete = Api.CreatePayment(GetTestId(TestId.InvoiceId), 1, DateTime.Now, "Test Create Payment");

            Assert.Equal("Test Create Payment", _todelete.Notes);
        }
Exemplo n.º 33
0
        public void RetrieveColumnsWithNull()
        {
            using (var trx = new Transaction(this.session))
                using (var update = new Update(this.session, this.tableid, JET_prep.Insert))
                {
                    update.SaveAndGotoBookmark();
                    trx.Commit(CommitTransactionGrbit.None);
                }

            var columnValues = new ColumnValue[]
            {
                new BoolColumnValue {
                    Columnid = this.columnDict["Boolean"]
                },
                new ByteColumnValue {
                    Columnid = this.columnDict["Byte"]
                },
                new Int16ColumnValue {
                    Columnid = this.columnDict["Int16"]
                },
                new UInt16ColumnValue {
                    Columnid = this.columnDict["UInt16"]
                },
                new Int32ColumnValue {
                    Columnid = this.columnDict["Int32"]
                },
                new UInt32ColumnValue {
                    Columnid = this.columnDict["UInt32"]
                },
                new Int64ColumnValue {
                    Columnid = this.columnDict["Int64"]
                },
                new UInt64ColumnValue {
                    Columnid = this.columnDict["UInt64"]
                },
                new FloatColumnValue {
                    Columnid = this.columnDict["Float"]
                },
                new DoubleColumnValue {
                    Columnid = this.columnDict["Double"]
                },
                new DateTimeColumnValue {
                    Columnid = this.columnDict["DateTime"]
                },
                new GuidColumnValue {
                    Columnid = this.columnDict["Guid"]
                },
                new StringColumnValue {
                    Columnid = this.columnDict["Unicode"]
                },
                new BytesColumnValue {
                    Columnid = this.columnDict["Binary"]
                },
            };

            Api.RetrieveColumns(this.session, this.tableid, columnValues);

            foreach (var c in columnValues)
            {
                Assert.IsNull(c.ValueAsObject);
            }
        }
Exemplo n.º 34
0
 /// <summary>
 /// Sets the LongText column in the table from a string. An update must be prepared.
 /// </summary>
 /// <param name="s">The string to set.</param>
 private void SetColumnFromString(string s)
 {
     byte[] data = Encoding.Unicode.GetBytes(s);
     Api.JetSetColumn(this.sesid, this.tableid, this.columnidLongText, data, data.Length, SetColumnGrbit.None, null);
 }
Exemplo n.º 35
0
        public async Task CreatePaymentAsync_ReturnsANewPayment()
        {
            _todelete = await Api.CreatePaymentAsync(GetTestId(TestId.InvoiceId), 1, DateTime.Now, "Test Create Payment");

            Assert.Equal("Test Create Payment", _todelete.Notes);
        }
Exemplo n.º 36
0
 public async Task Login()
 {
     _api = new Api(Api.DemoEndpoint);
     await _api.Login(Api.DemoUsername, Api.DemoPassword);
 }
Exemplo n.º 37
0
        internal Tracer(TracerSettings settings, IAgentWriter agentWriter, ISampler sampler, IScopeManager scopeManager, IStatsd statsd)
        {
            // update the count of Tracer instances
            Interlocked.Increment(ref _liveTracerCount);

            Settings = settings ?? TracerSettings.FromDefaultSources();

            // if not configured, try to determine an appropriate service name
            DefaultServiceName = Settings.ServiceName ??
                                 GetApplicationName() ??
                                 UnknownServiceName;

            // only set DogStatsdClient if tracer metrics are enabled
            if (Settings.TracerMetricsEnabled)
            {
                // Run this first in case the port override is ready
                TracingProcessManager.SubscribeToDogStatsDPortOverride(
                    port =>
                {
                    Log.Debug("Attempting to override dogstatsd port with {0}", port);
                    Statsd = CreateDogStatsdClient(Settings, DefaultServiceName, port);
                });

                Statsd = statsd ?? CreateDogStatsdClient(Settings, DefaultServiceName, Settings.DogStatsdPort);
            }

            // Run this first in case the port override is ready
            TracingProcessManager.SubscribeToTraceAgentPortOverride(
                port =>
            {
                Log.Debug("Attempting to override trace agent port with {0}", port);
                var builder = new UriBuilder(Settings.AgentUri)
                {
                    Port = port
                };
                var baseEndpoint = builder.Uri;

                if (_agentWriter == null)
                {
                    IApi overridingApiClient = new Api(baseEndpoint, apiRequestFactory: null, Statsd);
                    _agentWriter             = _agentWriter ?? new AgentWriter(overridingApiClient, Statsd);
                }
                else
                {
                    _agentWriter.SetApiBaseEndpoint(baseEndpoint);
                }
            });

            // fall back to default implementations of each dependency if not provided
            _agentWriter = agentWriter ?? new AgentWriter(new Api(Settings.AgentUri, apiRequestFactory: null, Statsd), Statsd);

            _scopeManager = scopeManager ?? new AsyncLocalScopeManager();
            Sampler       = sampler ?? new RuleBasedSampler(new RateLimiter(Settings.MaxTracesSubmittedPerSecond));

            if (!string.IsNullOrWhiteSpace(Settings.CustomSamplingRules))
            {
                // User has opted in, ensure rate limiter is used
                RuleBasedSampler.OptInTracingWithoutLimits();

                foreach (var rule in CustomSamplingRule.BuildFromConfigurationString(Settings.CustomSamplingRules))
                {
                    Sampler.RegisterRule(rule);
                }
            }

            if (Settings.GlobalSamplingRate != null)
            {
                var globalRate = (float)Settings.GlobalSamplingRate;

                if (globalRate < 0f || globalRate > 1f)
                {
                    Log.Warning("{0} configuration of {1} is out of range", ConfigurationKeys.GlobalSamplingRate, Settings.GlobalSamplingRate);
                }
                else
                {
                    Sampler.RegisterRule(new GlobalSamplingRule(globalRate));
                }
            }

            // Register callbacks to make sure we flush the traces before exiting
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;
            AppDomain.CurrentDomain.DomainUnload       += CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Console.CancelKeyPress += Console_CancelKeyPress;

            // start the heartbeat loop
            _heartbeatTimer = new Timer(HeartbeatCallback, state: null, dueTime: TimeSpan.Zero, period: TimeSpan.FromMinutes(1));

            // If configured, add/remove the correlation identifiers into the
            // LibLog logging context when a scope is activated/closed
            if (Settings.LogsInjectionEnabled)
            {
                InitializeLibLogScopeEventSubscriber(_scopeManager, DefaultServiceName, Settings.ServiceVersion, Settings.Environment);
            }

            if (Interlocked.Exchange(ref _firstInitialization, 0) == 1 && Settings.StartupDiagnosticLogEnabled)
            {
                _ = WriteDiagnosticLog();
            }
        }
Exemplo n.º 38
0
        private void CreateTransactionTable(JET_DBID dbid)
        {
            JET_TABLEID tableid;

            Api.JetCreateTable(session, dbid, "transactions", 16, 100, out tableid);
            JET_COLUMNID columnid;

            Api.JetAddColumn(session, tableid, "tx_id", new JET_COLUMNDEF
            {
                cbMax  = 16,
                coltyp = JET_coltyp.Binary,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "local_id", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Long,
                grbit  = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnAutoincrement
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "queue", new JET_COLUMNDEF
            {
                cbMax  = 255,
                cp     = JET_CP.Unicode,
                coltyp = JET_coltyp.Text,
                grbit  = ColumndefGrbit.ColumnNotNULL
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "subqueue", new JET_COLUMNDEF
            {
                cbMax  = 255,
                cp     = JET_CP.Unicode,
                coltyp = JET_coltyp.Text,
                grbit  = ColumndefGrbit.None
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "bookmark_size", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Long,
                grbit  = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "bookmark_data", new JET_COLUMNDEF
            {
                cbMax  = 256,
                coltyp = JET_coltyp.Binary,
                grbit  = ColumndefGrbit.ColumnNotNULL
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "value_to_restore", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Long,
                grbit  = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL
            }, null, 0, out columnid);

            var indexDef = "+tx_id\0local_id\0\0";

            Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length,
                               100);

            indexDef = "+tx_id\0\0";
            Api.JetCreateIndex(session, tableid, "by_tx_id", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length,
                               100);

            indexDef = "+bookmark_size\0bookmark_data\0\0";
            Api.JetCreateIndex(session, tableid, "by_bookmark", CreateIndexGrbit.IndexDisallowNull | CreateIndexGrbit.IndexUnique, indexDef, indexDef.Length,
                               100);
        }
Exemplo n.º 39
0
        private static void Command_Bet(string user, Command cmd, string[] args)
        {
            if (Running)
            {
                if (args.Length > 0)
                {
                    int Value;
                    if (args[0] == "help")
                    {
                        if (Api.GetUnixTimeNow() - LastUsedHelp < 60 && Users.GetLevel(user) < 1)
                        {
                            return;
                        }

                        LastUsedHelp = Api.GetUnixTimeNow();

                        if (!Locked)
                        {
                            string temp = "Betting open for: ";
                            lock (Options) for (int i = 0; i < Options.Count; i++)
                                {
                                    temp += "(" + (i + 1).ToString() + ") " + Options[i] + " - " + getNumberOfBets(Options[i]) + " bets (" + getTotalBetsOn(Options[i]) + " " + Currency.Name + ")" + (i + 1 < Options.Count ? ", " : "");
                                }
                            Chat.SendMessage(temp + ".");
                            Chat.SendMessage("Bet by typing \"!bet 50 #1\" to bet 50 " + Currency.Name + " on option 1, \"bet 25 #2\" to bet 25 " + Currency.Name + " on option 2, etc.");
                        }
                        else
                        {
                            string temp = "The pool is now closed, the following options were open for betting: ";
                            lock (Options) for (int i = 0; i < Options.Count; i++)
                                {
                                    temp += "(" + (i + 1).ToString() + ") " + Options[i] + " - " + getNumberOfBets(Options[i]) + " bets (" + getTotalBetsOn(Options[i]) + " " + Currency.Name + ")" + (i + 1 < Options.Count ? ", " : "");
                                }
                            Chat.SendMessage(temp + ".");
                        }
                    }
                    else if (!Locked && int.TryParse(args[0], out Value) && args.Length > 1)
                    {
                        bool   inQuote = false;
                        string option  = "";
                        for (int i = 1; i < args.Length; i++)
                        {
                            if (args[i].StartsWith("\""))
                            {
                                inQuote = true;
                            }
                            if (!inQuote)
                            {
                                option = args[i];
                            }
                            if (inQuote)
                            {
                                option += args[i] + " ";
                            }
                            if (args[i].EndsWith("\""))
                            {
                                option  = option.Substring(1, option.Length - 3);
                                inQuote = false;
                            }
                        }

                        if (option.ToLower() == args[1].ToLower())
                        {
                            if (option.StartsWith("#"))
                            {
                                int optionnumber = 0;
                                if (int.TryParse(option.Substring(1), out optionnumber))
                                {
                                    option = GetOptionFromNumber(optionnumber);
                                    if (option == "")
                                    {
                                        //Chat.SendMessage(user + " the option number does not exist");
                                        lock (FalseEntries)
                                        {
                                            if (!FalseEntries.ContainsKey(user))
                                            {
                                                FalseEntries.Add(user, 0);
                                                BetQueue.Change(10000, Timeout.Infinite);
                                            }
                                        }

                                        return;
                                    }
                                }
                            }
                        }

                        placeBet(user, option, Value);
                    }
                }
                else
                {
                    //if (isInPool(user)) Chat.SendMessage(user + ": " + bets[user].Key + " (" + bets[user].Value + ")");
                }
            }
        }
Exemplo n.º 40
0
 // Token: 0x06002196 RID: 8598 RVA: 0x0009BAA5 File Offset: 0x00099CA5
 private void SetSystemParameter(JET_param parameter, string value)
 {
     Api.JetSetSystemParameter(this.m_jetConsumer, JET_SESID.Nil, parameter, 0, value);
 }
Exemplo n.º 41
0
        private void CreateOutgoingHistoryTable(JET_DBID dbid)
        {
            JET_TABLEID tableid;

            Api.JetCreateTable(session, dbid, "outgoing_history", 16, 100, out tableid);
            JET_COLUMNID columnid;

            Api.JetAddColumn(session, tableid, "msg_id", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Binary,
                cbMax  = 16,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);


            Api.JetAddColumn(session, tableid, "tx_id", new JET_COLUMNDEF
            {
                cbMax  = 16,
                coltyp = JET_coltyp.Binary,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "address", new JET_COLUMNDEF
            {
                cbMax  = 255,
                cp     = JET_CP.Unicode,
                coltyp = JET_coltyp.Text,
                grbit  = ColumndefGrbit.ColumnNotNULL
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "port", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Long,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "number_of_retries", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Long,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "size_of_data", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Long,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "time_to_send", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.DateTime,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "sent_at", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.DateTime,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "send_status", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.Long,
                grbit  = ColumndefGrbit.ColumnNotNULL | ColumndefGrbit.ColumnFixed,
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "queue", new JET_COLUMNDEF
            {
                cbMax  = 255,
                coltyp = JET_coltyp.Text,
                grbit  = ColumndefGrbit.ColumnNotNULL,
                cp     = JET_CP.Unicode
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "subqueue", new JET_COLUMNDEF
            {
                cbMax  = 255,
                coltyp = JET_coltyp.Text,
                grbit  = ColumndefGrbit.None,
                cp     = JET_CP.Unicode
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "headers", new JET_COLUMNDEF
            {
                cbMax  = 8192,
                cp     = JET_CP.Unicode,
                coltyp = JET_coltyp.LongText,
                grbit  = ColumndefGrbit.None
            }, null, 0, out columnid);

            Api.JetAddColumn(session, tableid, "data", new JET_COLUMNDEF
            {
                coltyp = JET_coltyp.LongBinary,
                // For Win2k3 support, it doesn't support long binary columsn that are not null
                grbit = ColumndefGrbit.None
            }, null, 0, out columnid);

            var indexDef = "+msg_id\0\0";

            Api.JetCreateIndex(session, tableid, "pk", CreateIndexGrbit.IndexPrimary, indexDef, indexDef.Length,
                               100);

            indexDef = "+tx_id\0\0";
            Api.JetCreateIndex(session, tableid, "by_tx_id", CreateIndexGrbit.IndexDisallowNull, indexDef, indexDef.Length,
                               100);
        }
Exemplo n.º 42
0
 // Token: 0x06002197 RID: 8599 RVA: 0x0009BABB File Offset: 0x00099CBB
 private void SetSystemParameter(JET_param parameter, int value)
 {
     Api.JetSetSystemParameter(this.m_jetConsumer, JET_SESID.Nil, parameter, value, null);
 }
Exemplo n.º 43
0
		public void Update(Session session, JET_DBID dbid, Action<string> output)
		{
			using (var tbl = new Table(session, dbid, "documents", OpenTableGrbit.None))
			{
				Api.JetDeleteIndex(session, tbl, "by_key");
				Api.JetCreateIndex2(session, tbl, new[]
                {
                    new JET_INDEXCREATE
                    {
                        szIndexName = "by_key",
                        cbKey = 6,
                        cbKeyMost = SystemParameters.KeyMost,
                        cbVarSegMac = SystemParameters.KeyMost,
                        szKey = "+key\0\0",
                        grbit = CreateIndexGrbit.IndexDisallowNull | CreateIndexGrbit.IndexUnique,
                    }
                }, 1);
			}

			// So first we allocate ids and crap
			// and write that to disk in a safe manner
			// I might want to look at keeping a list of written files to delete if it all goes t**s up at any point
			var filesToDelete = new List<string>();
			var nameToIds = new Dictionary<string, int>();
			var indexDefPath = Path.Combine(configuration.DataDirectory, "IndexDefinitions");

			var indexDefinitions = Directory.GetFiles(indexDefPath, "*.index")
										.Select(x => { filesToDelete.Add(x); return x; })
										.Select(index => JsonConvert.DeserializeObject<IndexDefinition>(File.ReadAllText(index), Default.Converters))
										.ToList();

			indexDefinitions.ForEach(x => x.MaxIndexOutputsPerDocument = x.MaxIndexOutputsPerDocument ?? (16 * 1024));

			var transformDefinitions = Directory.GetFiles(indexDefPath, "*.transform")
										.Select(x => { filesToDelete.Add(x); return x; })
										.Select(index => JsonConvert.DeserializeObject<TransformerDefinition>(File.ReadAllText(index), Default.Converters))
										.ToArray();

			int maxIndexId = 0;

			for (var i = 0; i < indexDefinitions.Count; i++)
			{
				var definition = indexDefinitions[i];
				definition.IndexId = i;
				nameToIds[definition.Name] = definition.IndexId;
				var path = Path.Combine(indexDefPath, definition.IndexId + ".index");

				// TODO: This can fail, rollback
				File.WriteAllText(path, JsonConvert.SerializeObject(definition, Formatting.Indented, Default.Converters));

				var indexDirectory = FixupIndexName(definition.Name, configuration.IndexStoragePath);
				var oldStorageDirectory = Path.Combine(configuration.IndexStoragePath, MonoHttpUtility.UrlEncode(indexDirectory));
				var newStorageDirectory = Path.Combine(configuration.IndexStoragePath, definition.IndexId.ToString());

				if (Directory.Exists(oldStorageDirectory)) // in-memory index
					Directory.Move(oldStorageDirectory, newStorageDirectory);

				maxIndexId = i;
			}

			for (var i = 0; i < transformDefinitions.Length; i++)
			{
				var definition = transformDefinitions[i];
				definition.TransfomerId = maxIndexId = indexDefinitions.Count + i;
				nameToIds[definition.Name] = definition.TransfomerId;
				var path = Path.Combine(indexDefPath, definition.TransfomerId + ".transform");

				// TODO: This can file, rollback
				File.WriteAllText(path, JsonConvert.SerializeObject(definition, Formatting.Indented, Default.Converters));
			}



			var tablesAndColumns = new[]
		    {
		        new {table = "scheduled_reductions", column = "view"},
		        new {table = "mapped_results", column = "view"},
		        new {table = "reduce_results", column = "view"},
		        new {table = "reduce_keys_counts", column = "view"},
		        new {table = "reduce_keys_status", column = "view"},
		        new {table = "indexed_documents_references", column = "view"},
		        new {table = "tasks", column = "for_index"},
		        new {table = "indexes_stats", column = "key"},
		        new {table = "indexes_etag", column = "key"},
		        new {table = "indexes_stats_reduce", column = "key"}
		    };

			foreach (var item in tablesAndColumns)
			{
				var newTable = item.table + "_new";
				JET_TABLEID newTableId;

				using (var sr = new Table(session, dbid, item.table, OpenTableGrbit.None))
				{
					Api.JetCreateTable(session, dbid, newTable, 1, 80, out newTableId);
					var existingColumns = Api.GetTableColumns(session, sr).ToList();
					var existingIndexes = Api.GetTableIndexes(session, sr).ToList();

					foreach (var column in existingColumns)
					{
						JET_COLUMNDEF columnDef = null;
						Api.JetGetColumnInfo(session, dbid, item.table, column.Name, out columnDef);
						JET_COLUMNID newColumndId;

						if (column.Name == item.column)
						{
							Api.JetAddColumn(session, newTableId, item.column, new JET_COLUMNDEF
							{
								coltyp = JET_coltyp.Long,
								grbit = ColumndefGrbit.ColumnFixed | ColumndefGrbit.ColumnNotNULL
							}, null, 0, out newColumndId);
						}
						else
						{
							var defaultValue = column.DefaultValue == null ? null : column.DefaultValue.ToArray();
							var defaultValueLength = defaultValue == null ? 0 : defaultValue.Length;
							{
								Api.JetAddColumn(session, newTableId, column.Name, columnDef, defaultValue,
									defaultValueLength, out newColumndId);
							}
						}
					}

					foreach (var index in existingIndexes)
					{
						var indexDesc = String.Join("\0", index.IndexSegments.Select(x => "+" + x.ColumnName)) +
										"\0\0";
						SchemaCreator.CreateIndexes(session, newTableId, new JET_INDEXCREATE()
						{
							szIndexName = index.Name,
							szKey = indexDesc,
							grbit = index.Grbit
						});
					}

					var rows = 0;
					using (var destTable = new Table(session, dbid, newTable, OpenTableGrbit.None))
					{
						Api.MoveBeforeFirst(session, sr);
						Api.MoveBeforeFirst(session, destTable);

						while (Api.TryMoveNext(session, sr))
						{
							using (var insert = new Update(session, destTable, JET_prep.Insert))
							{
								bool save = true;
								foreach (var column in existingColumns)
								{
									var destcolumn = Api.GetTableColumnid(session, destTable, column.Name);
									if (column.Name == item.column)
									{
										var viewName = Api.RetrieveColumnAsString(session, sr, column.Columnid,
											Encoding.Unicode);
										int value;
										if (nameToIds.TryGetValue(viewName, out value) == false)
										{
											insert.Cancel();
											save = false;
											break;
										}
										Api.SetColumn(session, destTable, destcolumn, value);
									}
									else if ((column.Grbit & ColumndefGrbit.ColumnAutoincrement) == ColumndefGrbit.None)
									{
										var value = Api.RetrieveColumn(session, sr, column.Columnid);
										Api.SetColumn(session, destTable, destcolumn, value);
									}
								}
								if (save)
									insert.Save();
							}

							if (rows++ % 10000 == 0)
							{
								output("Processed " + (rows) + " rows in " + item.table);
								Api.JetCommitTransaction(session, CommitTransactionGrbit.LazyFlush);
								Api.JetBeginTransaction2(session, BeginTransactionGrbit.None);
							}
						}
					}
					output("Processed " + (rows - 1) + " rows in " + item.table + ", and done with this table");
				}
				Api.JetCommitTransaction(session, CommitTransactionGrbit.None);
				Api.JetDeleteTable(session, dbid, item.table);
				Api.JetRenameTable(session, dbid, newTable, item.table);
				Api.JetBeginTransaction2(session, BeginTransactionGrbit.None);
			}

			filesToDelete.ForEach(File.Delete);
			UpdateLastIdentityForIndexes(session, dbid, maxIndexId + 1);
			SchemaCreator.UpdateVersion(session, dbid, "5.0");
		}
Exemplo n.º 44
0
        public void Dispose()
        {
            if (lists != null)
            {
                lists.Dispose();
            }

            if (reduceKeysCounts != null)
            {
                reduceKeysCounts.Dispose();
            }

            if (reduceKeysStatus != null)
            {
                reduceKeysStatus.Dispose();
            }

            if (indexedDocumentsReferences != null)
            {
                indexedDocumentsReferences.Dispose();
            }

            if (reducedResults != null)
            {
                reducedResults.Dispose();
            }

            if (queue != null)
            {
                queue.Dispose();
            }

            if (directories != null)
            {
                directories.Dispose();
            }

            if (details != null)
            {
                details.Dispose();
            }

            if (identity != null)
            {
                identity.Dispose();
            }

            if (mappedResults != null)
            {
                mappedResults.Dispose();
            }

            if (scheduledReductions != null)
            {
                scheduledReductions.Dispose();
            }

            if (indexesStats != null)
            {
                indexesStats.Dispose();
            }

            if (files != null)
            {
                files.Dispose();
            }

            if (documents != null)
            {
                documents.Dispose();
            }

            if (tasks != null)
            {
                tasks.Dispose();
            }

            if (Equals(dbid, JET_DBID.Nil) == false && session != null)
            {
                Api.JetCloseDatabase(session.JetSesid, dbid, CloseDatabaseGrbit.None);
            }

            sessionAndTransactionDisposer();
        }
Exemplo n.º 45
0
        public void SetColumns()
        {
            bool     bit  = true;
            byte     b    = Any.Byte;
            short    i16  = Any.Int16;
            ushort   ui16 = Any.UInt16;
            int      i32  = Any.Int32;
            uint     ui32 = Any.UInt32;
            long     i64  = Any.Int64;
            ulong    ui64 = Any.UInt64;
            float    f    = Any.Float;
            double   d    = Any.Double;
            DateTime date = Any.DateTime;
            Guid     guid = Any.Guid;
            string   s    = Any.String;

            byte[] bytes = Any.BytesOfLength(1023);

            var columnValues = new ColumnValue[]
            {
                new BoolColumnValue {
                    Columnid = this.columnDict["Boolean"], Value = bit
                },
                new ByteColumnValue {
                    Columnid = this.columnDict["Byte"], Value = b
                },
                new Int16ColumnValue {
                    Columnid = this.columnDict["Int16"], Value = i16
                },
                new UInt16ColumnValue {
                    Columnid = this.columnDict["UInt16"], Value = ui16
                },
                new Int32ColumnValue {
                    Columnid = this.columnDict["Int32"], Value = i32
                },
                new UInt32ColumnValue {
                    Columnid = this.columnDict["UInt32"], Value = ui32
                },
                new Int64ColumnValue {
                    Columnid = this.columnDict["Int64"], Value = i64
                },
                new UInt64ColumnValue {
                    Columnid = this.columnDict["UInt64"], Value = ui64
                },
                new FloatColumnValue {
                    Columnid = this.columnDict["Float"], Value = f
                },
                new DoubleColumnValue {
                    Columnid = this.columnDict["Double"], Value = d
                },
                new DateTimeColumnValue {
                    Columnid = this.columnDict["DateTime"], Value = date
                },
                new GuidColumnValue()
                {
                    Columnid = this.columnDict["Guid"], Value = guid
                },
                new StringColumnValue {
                    Columnid = this.columnDict["Unicode"], Value = s
                },
                new BytesColumnValue {
                    Columnid = this.columnDict["Binary"], Value = bytes
                },
            };

            using (var trx = new Transaction(this.session))
                using (var update = new Update(this.session, this.tableid, JET_prep.Insert))
                {
                    Api.SetColumns(this.session, this.tableid, columnValues);
                    update.Save();
                    trx.Commit(CommitTransactionGrbit.None);
                }

            Api.TryMoveFirst(this.session, this.tableid);

            Assert.AreEqual(bit, Api.RetrieveColumnAsBoolean(this.session, this.tableid, this.columnDict["Boolean"]));
            Assert.AreEqual(b, Api.RetrieveColumnAsByte(this.session, this.tableid, this.columnDict["Byte"]));
            Assert.AreEqual(i16, Api.RetrieveColumnAsInt16(this.session, this.tableid, this.columnDict["Int16"]));
            Assert.AreEqual(ui16, Api.RetrieveColumnAsUInt16(this.session, this.tableid, this.columnDict["UInt16"]));
            Assert.AreEqual(i32, Api.RetrieveColumnAsInt32(this.session, this.tableid, this.columnDict["Int32"]));
            Assert.AreEqual(ui32, Api.RetrieveColumnAsUInt32(this.session, this.tableid, this.columnDict["UInt32"]));
            Assert.AreEqual(i64, Api.RetrieveColumnAsInt64(this.session, this.tableid, this.columnDict["Int64"]));
            Assert.AreEqual(ui64, Api.RetrieveColumnAsUInt64(this.session, this.tableid, this.columnDict["UInt64"]));
            Assert.AreEqual(f, Api.RetrieveColumnAsFloat(this.session, this.tableid, this.columnDict["Float"]));
            Assert.AreEqual(d, Api.RetrieveColumnAsDouble(this.session, this.tableid, this.columnDict["Double"]));
            Assert.AreEqual(date, Api.RetrieveColumnAsDateTime(this.session, this.tableid, this.columnDict["DateTime"]));
            Assert.AreEqual(guid, Api.RetrieveColumnAsGuid(this.session, this.tableid, this.columnDict["Guid"]));
            Assert.AreEqual(s, Api.RetrieveColumnAsString(this.session, this.tableid, this.columnDict["Unicode"]));
            CollectionAssert.AreEqual(bytes, Api.RetrieveColumn(this.session, this.tableid, this.columnDict["Binary"]));
        }
Exemplo n.º 46
0
        private static void Command_Gamble(string user, Command cmd, string[] args)
        {
            if (args.Length > 0)
            {
                if (args[0].ToLower() == "open" && args.Length > 4)
                {
                    if (!Running)
                    {
                        int min, max, reward;
                        if (int.TryParse(args[1], out min) && int.TryParse(args[2], out max) && int.TryParse(args[3], out reward))
                        {
                            if (min > 0)
                            {
                                if (max >= min)
                                {
                                    if (reward >= 0)
                                    {
                                        List <string> lOptions = buildBetOptions(args, 4);
                                        if (lOptions.Count > 1)
                                        {
                                            LastUsedHelp = Api.GetUnixTimeNow();

                                            CreatePool(min, max, reward, lOptions);
                                            Chat.SendMessage("New Betting Pool opened! Min bet: " + MinBet + " " + Currency.Name + ", Max bet: " + MaxBet + " " + Currency.Name + ".");
                                            string temp = "Betting open for: ";
                                            for (int i = 0; i < lOptions.Count; i++)
                                            {
                                                temp += "(" + (i + 1).ToString() + ") " + lOptions[i];
                                                if (i + 1 < lOptions.Count)
                                                {
                                                    temp += ", ";
                                                }
                                            }
                                            Chat.SendMessage(temp + ".");
                                            Chat.SendMessage("Bet by typing \"!bet 50 #1\" to bet 50 " + Currency.Name + " on option 1, \"!bet 25 #2\" to bet 25 " + Currency.Name + " on option 2, etc.");
                                        }
                                        else
                                        {
                                            Chat.SendMessage("You need at least two betting options in order to start a betting pool!");
                                        }
                                    }
                                    else
                                    {
                                        Chat.SendMessage("WinReward can not be lower than 0!");
                                    }
                                }
                                else
                                {
                                    Chat.SendMessage("MaxBet can not be lower than MinBet!");
                                }
                            }
                            else
                            {
                                Chat.SendMessage("MinBet can not be lower than 1!");
                            }
                        }
                        else
                        {
                            Chat.SendMessage("Invalid syntax. Open a betting pool with: !gamble open {MinBet} {MaxBet} {WinReward} {option1} {option2} ... {optionN} (space delimited options)");
                        }
                    }
                    else
                    {
                        Chat.SendMessage("Betting Pool already opened. Close or cancel the current one before starting a new one.");
                    }
                }
                else if (args[0].ToLower() == "close")
                {
                    if (Running)
                    {
                        if (!Locked)
                        {
                            Locked = true;
                            BetQueue.Change(0, Timeout.Infinite);
                            Chat.SendMessage("Bets locked in. Good luck everyone!");
                            string temp = "The following options were open for betting: ";
                            lock (Options) for (int i = 0; i < Options.Count; i++)
                                {
                                    temp += "(" + (i + 1).ToString() + ") " + Options[i] + " - " + getNumberOfBets(Options[i]) + " bets (" + getTotalBetsOn(Options[i]) + " " + Currency.Name + ")" + (i + 1 < Options.Count ? ", " : "");
                                }
                            Chat.SendMessage(temp + ".");
                        }
                        else
                        {
                            Chat.SendMessage("Pool is already locked.");
                        }
                    }
                    else
                    {
                        Chat.SendMessage("The betting pool is not running.");
                    }
                }
                else if (args[0].ToLower() == "winner" && args.Length > 1)
                {
                    if (Running && Locked)
                    {
                        bool   inQuote = false;
                        string option  = "";
                        for (int i = 1; i < args.Length; i++)
                        {
                            if (args[i].StartsWith("\""))
                            {
                                inQuote = true;
                            }
                            if (!inQuote)
                            {
                                option = args[i];
                            }
                            if (inQuote)
                            {
                                option += args[i] + " ";
                            }
                            if (args[i].EndsWith("\""))
                            {
                                option  = option.Substring(1, option.Length - 3);
                                inQuote = false;
                            }
                        }
                        if (option.ToLower() == args[1].ToLower())
                        {
                            if (option.StartsWith("#"))
                            {
                                int optionnumber = 0;
                                if (int.TryParse(option.Substring(1), out optionnumber))
                                {
                                    option = GetOptionFromNumber(optionnumber);
                                }
                            }
                        }

                        lock (Options)
                        {
                            if (Options.Contains(option))
                            {
                                closePool(option);
                                Chat.SendMessage("Betting Pool closed! A total of " + getTotalBets() + " " + Currency.Name + " were bet.");
                                string output = "Bets for:";
                                for (int i = 0; i < Options.Count; i++)
                                {
                                    double x = ((double)getTotalBetsOn(Options[i]) / getTotalBets()) * 100;
                                    output += " " + Options[i] + " - " + getNumberOfBets(Options[i]) + " (" + Math.Round(x) + "%);";
                                    //Console.WriteLine("TESTING: getTotalBetsOn(" + i + ") = " + getTotalBetsOn(i) + " --- getTotalBets() = " + getTotalBets() + " ---  (double)betsOn(i)/totalBets() = " + (double)(getTotalBetsOn(i) / getTotalBets()) + " --- *100 = " + (double)(getTotalBetsOn(i) / getTotalBets()) * 100 + " --- Converted to a double = " + (double)((getTotalBetsOn(i) / getTotalBets()) * 100) + " --- Rounded double = " + Math.Round((double)((getTotalBetsOn(i) / getTotalBets()) * 100)));
                                }
                                Chat.SendMessage(output);
                                Dictionary <string, int> wins = Winners;
                                output = "Winners:";
                                if (wins.Count == 0)
                                {
                                    output += " No One!";
                                }

                                for (int i = 0; i < wins.Count; i++)
                                {
                                    Currency.Add(wins.ElementAt(i).Key, wins.ElementAt(i).Value);
                                    string msg = " " + wins.ElementAt(i).Key + " - " + wins.ElementAt(i).Value + " (Bet " + bets[wins.ElementAt(i).Key].Value + ")";
                                    if (output.Length + msg.Length > 996)
                                    {
                                        Chat.SendMessage(output);
                                        output = "";
                                    }
                                    output += msg;
                                }

                                Chat.SendMessage(output);

                                Clear();
                            }
                            else
                            {
                                Chat.SendMessage("The option you specified is not available in the current pool!");
                            }
                        }
                    }
                    else
                    {
                        Chat.SendMessage("Betting pool must be running and bets must be locked before you can specify a winner, lock the bets by using \"!gamble close\".");
                        Chat.SendMessage("Pick a winning option by typing \"!gamble winner #1\" if option 1 won, \"!gamble winner #2\" for option 2, etc.");
                        Chat.SendMessage("You can type \"!bet help\" to get a list of the options as a reminder.");
                    }
                }
                else if (args[0].ToLower() == "cancel")
                {
                    if (Running)
                    {
                        Cancel();
                        Chat.SendMessage("Betting Pool canceled. All bets refunded");
                    }
                    else
                    {
                        Chat.SendMessage("The betting pool is not running.");
                    }
                }
            }
        }
Exemplo n.º 47
0
        public void JetRetrieveColumnsSameBuffer()
        {
            short  s   = Any.Int16;
            string str = Any.String;
            double d   = Any.Double;

            var setcolumns = new[]
            {
                new JET_SETCOLUMN {
                    cbData = sizeof(short), columnid = this.columnDict["Int16"], pvData = BitConverter.GetBytes(s)
                },
                new JET_SETCOLUMN {
                    cbData = sizeof(double), columnid = this.columnDict["Double"], pvData = BitConverter.GetBytes(d)
                },
                new JET_SETCOLUMN {
                    cbData = str.Length * sizeof(char), columnid = this.columnDict["Unicode"], pvData = Encoding.Unicode.GetBytes(str)
                },
                new JET_SETCOLUMN {
                    cbData = 0, columnid = this.columnDict["Binary"], pvData = null
                },
            };

            using (var trx = new Transaction(this.session))
                using (var update = new Update(this.session, this.tableid, JET_prep.Insert))
                {
                    Api.JetSetColumns(this.session, this.tableid, setcolumns, setcolumns.Length);
                    update.Save();
                    trx.Commit(CommitTransactionGrbit.None);
                }

            Api.TryMoveFirst(this.session, this.tableid);

            byte[] buffer          = new byte[1024];
            var    retrievecolumns = new[]
            {
                new JET_RETRIEVECOLUMN {
                    cbData = sizeof(short), columnid = this.columnDict["Int16"], pvData = buffer, ibData = 100
                },
                new JET_RETRIEVECOLUMN {
                    cbData = sizeof(double), columnid = this.columnDict["Double"], pvData = buffer, ibData = 200
                },
                new JET_RETRIEVECOLUMN {
                    cbData = str.Length * sizeof(char) * 2, columnid = this.columnDict["Unicode"], pvData = new byte[str.Length * sizeof(char) * 2]
                },
                new JET_RETRIEVECOLUMN {
                    cbData = 10, columnid = this.columnDict["Binary"], pvData = buffer
                },
            };

            for (int i = 0; i < retrievecolumns.Length; ++i)
            {
                retrievecolumns[i].itagSequence = 1;
            }

            Api.JetRetrieveColumns(this.session, this.tableid, retrievecolumns, retrievecolumns.Length);

            // retrievecolumns[0] = short
            Assert.AreEqual(sizeof(short), retrievecolumns[0].cbActual);
            Assert.AreEqual(JET_wrn.Success, retrievecolumns[0].err);
            Assert.AreEqual(s, BitConverter.ToInt16(retrievecolumns[0].pvData, retrievecolumns[0].ibData));

            // retrievecolumns[1] = double
            Assert.AreEqual(sizeof(double), retrievecolumns[1].cbActual);
            Assert.AreEqual(JET_wrn.Success, retrievecolumns[1].err);
            Assert.AreEqual(d, BitConverter.ToDouble(retrievecolumns[1].pvData, retrievecolumns[1].ibData));

            // retrievecolumns[2] = string
            Assert.AreEqual(str.Length * sizeof(char), retrievecolumns[2].cbActual);
            Assert.AreEqual(JET_wrn.Success, retrievecolumns[2].err);
            Assert.AreEqual(str, Encoding.Unicode.GetString(retrievecolumns[2].pvData, retrievecolumns[2].ibData, retrievecolumns[2].cbActual));

            // retrievecolumns[3] = null
            Assert.AreEqual(0, retrievecolumns[3].cbActual);
            Assert.AreEqual(JET_wrn.ColumnNull, retrievecolumns[3].err);
        }
Exemplo n.º 48
0
        public IList <Report> GetReports()
        {
            List <Report> reports = new List <Report>();

            using (EsentSession session = new EsentSession(_database))
            {
                session.Open();

                JET_SESID   sessionId  = session.GetSessionId();
                JET_DBID    databaseId = session.GetDatabaseId();
                JET_TABLEID tableId;

                if (DatabaseTableExists(sessionId, databaseId, TABLE_STATUS_REPORT))
                {
                    Api.OpenTable(sessionId, databaseId, TABLE_STATUS_REPORT, OpenTableGrbit.ReadOnly, out tableId);

                    Api.MoveBeforeFirst(session.GetSessionId(), tableId);

                    while (Api.TryMoveNext(sessionId, tableId))
                    {
                        IDictionary <string, JET_COLUMNID> columnDictionary = Api.GetColumnDictionary(sessionId, tableId);

                        Report report = new Report()
                        {
                            Id                   = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["Id"]),
                            JobId                = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["JobId"]),
                            NodeName             = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["NodeName"]),
                            IPAddress            = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["IPAddress"]),
                            RerfreshMode         = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["RefreshMode"]),
                            OperationType        = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["OperationType"]),
                            Status               = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["Status"]),
                            RebootRequested      = Api.RetrieveColumnAsBoolean(sessionId, tableId, columnDictionary["RebootRequested"]).GetValueOrDefault(),
                            StartTime            = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["StartTime"]).GetValueOrDefault(),
                            EndTime              = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["EndTime"]).GetValueOrDefault(),
                            LastModifiedTime     = Api.RetrieveColumnAsDateTime(sessionId, tableId, columnDictionary["LastModifiedTime"]).GetValueOrDefault(),
                            LCMVersion           = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["LCMVersion"]),
                            ConfigurationVersion = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ConfigurationVersion"]),
                            ReportFormatVersion  = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["ReportFormatVersion"]),
                            Errors               = (List <string>)Api.DeserializeObjectFromColumn(sessionId, tableId, columnDictionary["Errors"]),
                            StatusData           = (List <string>)Api.DeserializeObjectFromColumn(sessionId, tableId, columnDictionary["StatusData"])
                        };

                        // Field AdditionalData is only available on WS2016 and WMF 5.1
                        if (columnDictionary.Keys.Contains("AdditionalData"))
                        {
                            report.AdditionalData = Api.RetrieveColumnAsString(sessionId, tableId, columnDictionary["AdditionalData"]);
                        }

                        reports.Add(report);
                    }

                    Api.JetCloseTable(sessionId, tableId);
                }
                else
                {
                    _logger.Log(10091, String.Format("Database table {0} not found!", TABLE_STATUS_REPORT), LogLevel.Warning);
                }
            }

            return(reports.OrderBy(r => r.StartTime).ToList());
        }
Exemplo n.º 49
0
        /// <summary>
        /// Create the data table.
        /// </summary>
        /// <param name="session">The session to use.</param>
        /// <param name="dbid">The database to create the table in.</param>
        private void CreateDataTable(Session session, JET_DBID dbid)
        {
            JET_TABLEID  tableid;
            JET_COLUMNID keyColumnid;
            JET_COLUMNID valueColumnid;

            Api.JetCreateTable(session, dbid, this.config.DataTableName, 128, 100, out tableid);
            var columndef = new JET_COLUMNDEF {
                coltyp = this.converters.KeyColtyp, cp = JET_CP.Unicode, grbit = ColumndefGrbit.None
            };

            if (ColumnCanBeCompressed(columndef))
            {
                columndef.grbit |= Windows7Grbits.ColumnCompressed;
            }

            Api.JetAddColumn(
                session,
                tableid,
                this.config.KeyColumnName,
                columndef,
                null,
                0,
                out keyColumnid);

            columndef = new JET_COLUMNDEF {
                coltyp = this.converters.ValueColtyp, cp = JET_CP.Unicode, grbit = ColumndefGrbit.None
            };
            if (ColumnCanBeCompressed(columndef))
            {
                columndef.grbit |= Windows7Grbits.ColumnCompressed;
            }

            Api.JetAddColumn(
                session,
                tableid,
                this.config.ValueColumnName,
                columndef,
                null,
                0,
                out valueColumnid);

            string indexKey     = String.Format(CultureInfo.InvariantCulture, "+{0}\0\0", this.config.KeyColumnName);
            var    indexcreates = new[]
            {
                new JET_INDEXCREATE
                {
                    cbKeyMost   = SystemParameters.KeyMost,
                    grbit       = CreateIndexGrbit.IndexPrimary,
                    szIndexName = "primary",
                    szKey       = indexKey,
                    cbKey       = indexKey.Length,
                    pidxUnicode = new JET_UNICODEINDEX
                    {
                        lcid       = CultureInfo.CurrentCulture.LCID,
                        dwMapFlags = Conversions.LCMapFlagsFromCompareOptions(CompareOptions.None),
                    },
                },
            };

            Api.JetCreateIndex2(session, tableid, indexcreates, indexcreates.Length);

            Api.JetCloseTable(session, tableid);
        }
Exemplo n.º 50
0
        protected override void PrepareFeature(List <IProtoEntity> entityList, List <IProtoEntity> requiredItemList)
        {
            entityList.AddRange(Api.FindProtoEntities <IProtoObjectMineral>());

            requiredItemList.AddRange(Api.FindProtoEntities <IProtoItemToolMining>());
        }
Exemplo n.º 51
0
        /// <summary>
        /// Create the globals table.
        /// </summary>
        /// <param name="session">The session to use.</param>
        /// <param name="dbid">The database to create the table in.</param>
        private void CreateGlobalsTable(Session session, JET_DBID dbid)
        {
            JET_TABLEID  tableid;
            JET_COLUMNID versionColumnid;
            JET_COLUMNID countColumnid;
            JET_COLUMNID keyTypeColumnid;
            JET_COLUMNID valueTypeColumnid;

            Api.JetCreateTable(session, dbid, this.config.GlobalsTableName, 1, 100, out tableid);
            Api.JetAddColumn(
                session,
                tableid,
                this.config.VersionColumnName,
                new JET_COLUMNDEF {
                coltyp = JET_coltyp.LongText
            },
                null,
                0,
                out versionColumnid);

            byte[] defaultValue = BitConverter.GetBytes(0);

            Api.JetAddColumn(
                session,
                tableid,
                this.config.CountColumnName,
                new JET_COLUMNDEF {
                coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnEscrowUpdate
            },
                defaultValue,
                defaultValue.Length,
                out countColumnid);

            Api.JetAddColumn(
                session,
                tableid,
                this.config.FlushColumnName,
                new JET_COLUMNDEF {
                coltyp = JET_coltyp.Long, grbit = ColumndefGrbit.ColumnEscrowUpdate
            },
                defaultValue,
                defaultValue.Length,
                out countColumnid);

            Api.JetAddColumn(
                session,
                tableid,
                this.config.KeyTypeColumnName,
                new JET_COLUMNDEF {
                coltyp = JET_coltyp.LongBinary
            },
                null,
                0,
                out keyTypeColumnid);

            Api.JetAddColumn(
                session,
                tableid,
                this.config.ValueTypeColumnName,
                new JET_COLUMNDEF {
                coltyp = JET_coltyp.LongBinary
            },
                null,
                0,
                out valueTypeColumnid);

            using (var update = new Update(session, tableid, JET_prep.Insert))
            {
                Api.SerializeObjectToColumn(session, tableid, keyTypeColumnid, typeof(TKey));
                Api.SerializeObjectToColumn(session, tableid, valueTypeColumnid, typeof(TValue));
                Api.SetColumn(session, tableid, versionColumnid, this.config.Version, Encoding.Unicode);
                update.Save();
            }

            Api.JetCloseTable(session, tableid);
        }
Exemplo n.º 52
0
        internal void Timings()
        {
            _paused = false;
            Tick++;
            Tick10   = Tick % 10 == 0;
            Tick20   = Tick % 20 == 0;
            Tick60   = Tick % 60 == 0;
            Tick120  = Tick % 120 == 0;
            Tick180  = Tick % 180 == 0;
            Tick300  = Tick % 300 == 0;
            Tick600  = Tick % 600 == 0;
            Tick1800 = Tick % 1800 == 0;
            Tick3600 = Tick % 3600 == 0;

            if (Tick60)
            {
                if (Av.ExplosionCounter - 5 >= 0)
                {
                    Av.ExplosionCounter -= 5;
                }
                else
                {
                    Av.ExplosionCounter = 0;
                }
            }

            if (++SCount == 60)
            {
                SCount = 0;
            }
            if (++QCount == 15)
            {
                QCount = 0;
            }
            if (++AwakeCount == AwakeBuckets)
            {
                AwakeCount = 0;
            }
            if (++AsleepCount == AsleepBuckets)
            {
                AsleepCount = 0;
            }

            if (Count++ == 119)
            {
                Count       = 0;
                UiBkOpacity = MyAPIGateway.Session.Config.UIBkOpacity;
                UiOpacity   = MyAPIGateway.Session.Config.UIOpacity;
                CheckAdminRights();
                if (IsServer && MpActive && (AuthLogging || ConnectedAuthors.Count > 0))
                {
                    AuthorDebug();
                }

                if (IsServer && PbActivate && !PbApiInited)
                {
                    Api.PbInit();
                }

                if (HandlesInput && !ClientCheck && Tick > 1200)
                {
                    if (IsClient)
                    {
                        if (ServerVersion != ModContext.ModName)
                        {
                            var message = $"::WeaponCore Version Mismatch::    Server:{ServerVersion} - Client:{ModContext.ModName} -   Unexpected behavior may occur.";
                            MyAPIGateway.Utilities.ShowNotification(message, 10000, "Red");
                        }
                    }

                    if (!string.IsNullOrEmpty(PlayerMessage))
                    {
                        MyAPIGateway.Utilities.ShowNotification(PlayerMessage, 10000, "White");
                    }

                    ClientCheck = true;
                }
            }
            LCount++;
            if (LCount == 129)
            {
                LCount = 0;
            }

            if (!GameLoaded)
            {
                if (FirstLoop)
                {
                    if (!MiscLoaded)
                    {
                        MiscLoaded = true;
                    }

                    InitRayCast();

                    GameLoaded = true;
                    if (LocalVersion)
                    {
                        Log.Line($"Local WeaponCore Detected");
                    }
                }
                else if (!FirstLoop)
                {
                    FirstLoop = true;
                    foreach (var t in AllDefinitions)
                    {
                        var name = t.Id.SubtypeName;
                        if (name.Contains("Armor"))
                        {
                            var normalArmor = name.Contains("ArmorBlock") || name.Contains("HeavyArmor") || name.StartsWith("LargeRoundArmor") || name.Contains("BlockArmor");
                            var blast       = !normalArmor && (name == "ArmorCenter" || name == "ArmorCorner" || name == "ArmorInvCorner" || name == "ArmorSide" || name.StartsWith("SmallArmor"));
                            if (normalArmor || blast)
                            {
                                AllArmorBaseDefinitions.Add(t);
                                if (blast || name.Contains("Heavy"))
                                {
                                    HeavyArmorBaseDefinitions.Add(t);
                                }
                            }
                        }
                    }
                }
            }

            if (!PlayersLoaded && KeenFuckery())
            {
                PlayersLoaded = true;
            }

            if (WaterMod && !WaterApiLoaded && !Settings.ClientWaiting && WApi.Waters != null)
            {
                WaterApiLoaded = true;
                WApiReceiveData();
            }
        }
Exemplo n.º 53
0
        private Boolean DatabaseTableExists(JET_SESID sessionId, JET_DBID databaseId, String tableName)
        {
            IEnumerable <String> tableNames = Api.GetTableNames(sessionId, databaseId);

            return(tableNames.Contains(tableName));
        }
Exemplo n.º 54
0
        public static async Task Main(string[] args)
        {
            var home = new AppHome("file_map_uploader");

            if (!home.ConfigPresent())
            {
                Console.WriteLine("Need to generate a config file.");

                home.CreateConfig(new DocumentSyntax {
                    Tables =
                    {
                        new TableSyntax("tokens")
                        {
                            Items =
                            {
                                { "token", "PUT_TOKEN_HERE"                                            }
                            }
                        },
                        new TableSyntax("data")
                        {
                            Items =
                            {
                                { "map_file",          "RELATIVE_MAP_FILE_PATH_HERE"                             },
                                { "id_is_sis",         true                                                      },
                                { "target_canvas_dir", "uploaded"                                                },
                                { "send_message",      true                                                      },
                                { "message",           "An important file was pushed to your account."           }
                            }
                        }
                    }
                });

                Console.WriteLine("Created a new config file. Please go put in your token and map info.");
                return;
            }

            Console.WriteLine("Found config file.");

            var config = home.GetConfig();

            Debug.Assert(config != null, nameof(config) + " != null");

            var token = config.GetTable("tokens").Get <string>("token");

            var data         = config.GetTable("data");
            var mapFileName  = data.Get <string>("map_file");
            var idIsSis      = data.GetOr("id_is_sis", true);
            var targetFolder = data.Get <string>("target_canvas_dir");
            var sendMessage  = data.Get <bool>("send_message");
            var message      = data.Get <string>("message");

            var mapFilePath = Path.Combine(home.NsDir, mapFileName);

            Console.WriteLine($"Sourcing map from {mapFilePath}");

            var startedAt = DateTime.Now;

            // ------------------------------------------------------------------------

            var list = File.ReadAllLines(mapFilePath).ToList();

            List <string>[] taskLists = list.Chunk(Math.Min(Math.Max(list.Count / 7, 2), list.Count - 1))
                                        .ToArray();

            var nThreads = taskLists.Length;

            var apis = new Api[nThreads];

            for (int i = 0; i < nThreads; i++)
            {
                apis[i] = new Api(token, "https://uview.instructure.com/api/v1/");
            }

            Console.WriteLine($"Using {nThreads} threads.");

            var completed = new ConcurrentBag <string>();
            var notFound  = new ConcurrentBag <string>();
            var error     = new ConcurrentBag <string>();
            var keys      = new ConcurrentBag <string>();

            using (var countdown = new CountdownEvent(nThreads)) {
                for (int i = 0; i < nThreads; i++)
                {
                    ThreadPool.QueueUserWorkItem(o => {
                        try {
                            var n = (int)o;
                            foreach (var line in taskLists[n])
                            {
                                string[] halves = line.Split(',');
                                Debug.Assert(halves.Length == 2);

                                var(userKey, userFile) = (halves[0], halves[1]);
                                keys.Add(userKey);

                                var api = apis[n];

                                try {
                                    var user = idIsSis switch {
                                        true => api.GetUserBySis(userKey).Result,
                                        _ => api.GetUser(ulong.Parse(userKey)).Result
                                    };

                                    if (user == null)
                                    {
                                        Console.WriteLine($"WARN: Couldn't find the user for sis {userKey} !!");
                                        notFound.Add(userKey);
                                        continue;
                                    }

                                    var bytes = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(mapFilePath),
                                                                               userFile));

                                    Console.WriteLine($"Preparing to upload filename {userFile} to user " +
                                                      $"{userKey}, Id {user.Id}, SIS {user.SisUserId}");

                                    api.MasqueradeAs(user.Id);

                                    var file = api.UploadPersonalFile(bytes,
                                                                      userFile,
                                                                      targetFolder)
                                               .Result;

                                    Console.WriteLine($"Uploaded as {file.Id}!");
                                    completed.Add(userKey);

                                    if (sendMessage)
                                    {
                                        api.StopMasquerading();
                                        api.CreateConversation(new QualifiedId(user.Id).Yield(),
                                                               message,
                                                               forceNew: true);
                                    }
                                } catch (Exception e) {
                                    Console.WriteLine($"Caught an exception during upload for {userKey}: {e}");
                                    error.Add(userKey);
                                } finally {
                                    api.StopMasquerading();
                                }
                            }
                        } finally {
                            countdown.Signal();
                        }
                    }, i);
                }
                countdown.Wait();
            }

            var completedE = completed.Distinct().ToList();
            var errorE     = error.Distinct().ToList();
            var notFoundE  = notFound.Distinct().ToList();

            Console.WriteLine($"{completedE.Count} out of {list.Count} operations were completed.");

            if (errorE.Any())
            {
                Console.WriteLine($"Operation failed for the following SIS IDs: {errorE.ToPrettyString()}");
            }

            if (notFoundE.Any())
            {
                Console.WriteLine($"The following SIS IDs could not be resolved: {notFoundE.ToPrettyString()}");
            }

            var document = new JObject {
                ["dateStarted"]   = startedAt.ToIso8601Date(),
                ["dateCompleted"] = DateTime.Now.ToIso8601Date(),
                ["completed"]     = new JArray(completedE),
                ["error"]         = new JArray(errorE),
                ["notFound"]      = new JArray(notFoundE)
            };

            var outPath = Path.Combine(home.NsDir, $"FileMapUploader_Log_{startedAt.Ticks}.json");

            File.WriteAllText(outPath, document.ToString(Formatting.Indented) + "\n");
            Console.WriteLine($"Wrote log to {outPath}");
        }
Exemplo n.º 55
0
 /// <summary>
 /// Returns the value in the LongText column as a string. The cursor must be on a record.
 /// </summary>
 /// <returns>The value of the LongText column as a string.</returns>
 private string RetrieveColumnAsString()
 {
     return(Api.RetrieveColumnAsString(this.sesid, this.tableid, this.columnidLongText, Encoding.Unicode));
 }
Exemplo n.º 56
0
        protected override void Init()
        {
            using (var api = new Api(options, storage)) {
                Piranha.App.Init(api);

                var builder = new PageTypeBuilder(api)
                              .AddType(typeof(MyPage))
                              .AddType(typeof(MyCollectionPage));
                builder.Build();

                var site = new Data.Site()
                {
                    Id         = SITE_ID,
                    Title      = "Default Site",
                    InternalId = "DefaultSite",
                    IsDefault  = true
                };
                api.Sites.Save(site);

                var page1 = MyPage.Create(api);
                page1.Id      = PAGE_1_ID;
                page1.SiteId  = SITE_ID;
                page1.Title   = "My first page";
                page1.Ingress = "My first ingress";
                page1.Body    = "My first body";
                api.Pages.Save(page1);

                var page2 = MyPage.Create(api);
                page2.Id      = PAGE_2_ID;
                page2.SiteId  = SITE_ID;
                page2.Title   = "My second page";
                page2.Ingress = "My second ingress";
                page2.Body    = "My second body";
                api.Pages.Save(page2);

                var page3 = MyPage.Create(api);
                page3.Id      = PAGE_3_ID;
                page3.SiteId  = SITE_ID;
                page3.Title   = "My third page";
                page3.Ingress = "My third ingress";
                page3.Body    = "My third body";
                api.Pages.Save(page3);

                var page4 = MyCollectionPage.Create(api);
                page4.SiteId    = SITE_ID;
                page4.Title     = "My collection page";
                page4.SortOrder = 1;
                page4.Texts.Add(new TextField()
                {
                    Value = "First text"
                });
                page4.Texts.Add(new TextField()
                {
                    Value = "Second text"
                });
                page4.Texts.Add(new TextField()
                {
                    Value = "Third text"
                });
                api.Pages.Save(page4);
            }
        }
 private void Create(string name)
 {
     CheckError(Api.rtPostProcessingStageCreateBuiltin(mContext.InternalPtr, name, ref InternalPtr));
 }
Exemplo n.º 58
0
 public Collection <string> GetPublicKeyFileNames(Api contextApi)
 {
     return(new Collection <string> {
         "Tc.PublicKey.xml"
     });
 }
Exemplo n.º 59
0
        /// <summary>
        /// Tries to handle an incoming request.
        /// </summary>
        /// <param name="api">The current api</param>
        /// <param name="request">The incoming route request</param>
        /// <returns>The result</returns>
        public IResponse Handle(Api api, IRequest request)
        {
            var type  = api.PostTypes.GetSingle(request.Segments[0]);
            var route = "";

            if (type != null)
            {
                // First try to resolve a unique permalink
                if (request.Segments.Length > 1)
                {
                    var post = Client.Models.PostModel.GetBySlug(request.Segments[1], type.Id);

                    if (post != null)
                    {
                        route = !String.IsNullOrWhiteSpace(post.Route) ? post.Route : (!String.IsNullOrWhiteSpace(type.Route) ? type.Route : "post");

                        if (request.Segments.Length > 2 && request.Segments[2] == "comment")
                        {
                            var response = request.RewriteResponse();

                            response.Route  = !String.IsNullOrWhiteSpace(type.CommentRoute) ? type.CommentRoute : "comment/add";
                            response.Params = request.Params;

                            return(response);
                        }
                        else
                        {
                            route = !String.IsNullOrWhiteSpace(post.Route) ? post.Route : (!String.IsNullOrWhiteSpace(type.Route) ? type.Route : "post");

                            // Append extra url segments
                            for (var n = 2; n < request.Segments.Length; n++)
                            {
                                route += "/" + request.Segments[n];
                            }

                            // Set current
                            App.Env.SetCurrent(new Client.Models.Content()
                            {
                                Id          = post.Id,
                                Title       = post.Title,
                                Keywords    = post.Keywords,
                                Description = post.Description,
                                VirtualPath = "~/" + type.Slug + "/" + post.Slug,
                                Type        = Client.Models.ContentType.Post
                            });

                            var response = request.RewriteResponse();

                            response.Route  = route;
                            response.Params = request.Params.Concat(new Param[] {
                                new Param()
                                {
                                    Key = "id", Value = post.Id.ToString()
                                }
                            }).ToArray();

                            return(response);
                        }
                    }
                }

                // Check if we should continue
                if (request.Segments.Length > 1 && request.Segments[1] != "page" && !IsNumber(request.Segments[1]))
                {
                    return(null);
                }

                // Secondly try to resolve an archive request
                if (type.EnableArchive)
                {
                    route = !String.IsNullOrWhiteSpace(type.ArchiveRoute) ? type.ArchiveRoute : "archive";

                    int? page      = null;
                    int? year      = null;
                    int? month     = null;
                    bool foundPage = false;

                    for (var n = 1; n < request.Segments.Length; n++)
                    {
                        if (request.Segments[n] == "page")
                        {
                            foundPage = true;
                            continue;
                        }

                        if (foundPage)
                        {
                            try {
                                page = Convert.ToInt32(request.Segments[n]);
                            } catch { }
                            break;
                        }

                        if (!year.HasValue)
                        {
                            try {
                                year = Convert.ToInt32(request.Segments[n]);

                                if (year.Value > DateTime.Now.Year)
                                {
                                    year = DateTime.Now.Year;
                                }
                            } catch { }
                        }
                        else
                        {
                            try {
                                month = Math.Max(Math.Min(Convert.ToInt32(request.Segments[n]), 12), 1);
                            } catch { }
                        }
                    }

                    // Set current
                    App.Env.SetCurrent(new Client.Models.Content()
                    {
                        Id          = type.Id,
                        Title       = type.ArchiveTitle,
                        Keywords    = type.MetaKeywords,
                        Description = type.MetaDescription,
                        VirtualPath = "~/" + type.Slug + (year.HasValue ? "/" + year + (month.HasValue ? "/" + month : "") : ""),
                        Type        = Client.Models.ContentType.Archive
                    });

                    var response = request.RewriteResponse();

                    response.Route  = route;
                    response.Params = request.Params.Concat(new Param[] {
                        new Param()
                        {
                            Key = "id", Value = type.Id.ToString()
                        },
                        new Param()
                        {
                            Key = "year", Value = year.ToString()
                        },
                        new Param()
                        {
                            Key = "month", Value = month.ToString()
                        },
                        new Param()
                        {
                            Key = "page", Value = page.ToString()
                        }
                    }).ToArray();

                    return(response);
                }
            }
            return(null);
        }
Exemplo n.º 60
0
 public void IsCached()
 {
     using (var api = new Api(GetDb(), storage, cache)) {
         Assert.Equal(this.GetType() == typeof(AliasesCached), api.IsCached);
     }
 }