Example #1
0
        public static Session Deserialize(string data)
        {
            var session = new Session(Game.Settings.Game.Mods);

            var ys = MiniYaml.FromString(data);
            foreach (var y in ys)
            {
                var yy = y.Key.Split('@');

                switch (yy[0])
                {
                    case "GlobalSettings":
                        FieldLoader.Load(session.GlobalSettings, y.Value);
                        break;

                    case "Client":
                        session.Clients.Add(FieldLoader.Load<Session.Client>(y.Value));
                        break;

                    case "Slot":
                        var s = FieldLoader.Load<Session.Slot>(y.Value);
                        session.Slots.Add(s.PlayerReference, s);
                        break;
                }
            }

            return session;
        }
Example #2
0
        /// <summary>動画を検索する</summary>
        /// <param name="Keyword">検索キーワード</param>
        /// <param name="SearchPage">検索ページの指定、1~nの間の数値を指定する</param>
        /// <param name="SearchType">検索方法を指定する</param>
        /// <param name="SearchOption">検索オプションを指定する、Filterメンバは無効</param>
        public Session<Response<VideoInfo[]>> Search(
            string Keyword,
            int SearchPage,
            SearchType SearchType,
            SearchOption SearchOption)
        {
            var session = new Session<Response<VideoInfo[]>>();

            session.SetAccessers(new Func<byte[], APIs.IAccesser>[]
            {
                (data) =>
                {
                    var accesser = new APIs.search.Accesser();
                    accesser.Setting(
                        context.CookieContainer,
                        SearchType.ToKey(),
                        Keyword,
                        SearchPage.ToString(),
                        SearchOption.SortOrder.ToKey(),
                        SearchOption.SortTarget.ToKey());

                    return accesser;
                }
            },
            (data) =>
                Converter.VideoInfoResponse(context, new APIs.search.Parser().Parse(data)));

            return session;
        }
 protected void btnQuery_Click(object sender, ImageClickEventArgs e)
 {
     using (ISession session = new Session())
     {
         this.QueryAndBindData(session, 1, this.magicPagerMain.PageSize, true);
     }
 }
Example #4
0
    public CustomDialog(Session session)
        : base(session)
    {
        InitializeComponent();

        LoadResources();
    }
    protected void MagicItemCommand(object sender, MagicItemEventArgs e)
    {
        if (e.CommandName != "Download")
            return;

        using (ISession session = new Session())
        {
            DateTime startDate = Cast.DateTime(this.txtDateFrom.Text, new DateTime(1900, 1, 1));
            DateTime endDate = Cast.DateTime(this.txtDateTo.Text, new DateTime(1900, 1, 1));

            int count = 0;
            DataSet ds = Report.SaleByCategoryStat(session, startDate, endDate, -1, 0, false, ref count);
            string fileName = DownloadUtil.DownloadXls("Sale_ByCat_" + DateTime.Now.ToString("yyMMdd") + ".xls", "RPT_SALE_BYCAT_",
                new List<DownloadFormat>()
                    {
                        new DownloadFormat(DataType.Text, "产品类别", "CatName"),
                        new DownloadFormat(DataType.Number, "销售量", "SaleQty"),
                        new DownloadFormat(DataType.Number, "销售金额", "SaleAmt"),
                        new DownloadFormat(DataType.Number, "总采购", "PurQty"),
                        new DownloadFormat(DataType.Number, "销售率(%)", "SaleRate"),
                        new DownloadFormat(DataType.Number, "换货量", "ExcgQty"),
                        new DownloadFormat(DataType.Number, "换货率(%)", "ExcgRate"),
                        new DownloadFormat(DataType.Number, "退货量", "RtnQty"),
                        new DownloadFormat(DataType.Number, "退货率(%)", "RtnRate")
                    }, ds);
            this.frameDownload.Attributes["src"] = fileName;
        }
        WebUtil.DownloadHack(this, "txtDateFrom", "txtDateTo");
    }
Example #6
0
        static void Main(string[] args)
        {
            //Create an instance of Session
            Session s1 = new Session();
            s1.Id = 1;
            s1.Name = "OOP";
            s1.Cost = 200.00M;
            // "10/31/2015"
            s1.StartDate = new DateTime(2015, 10, 31, 5, 0, 0);
            s1.EndDate = new DateTime(2015, 12, 31, 5, 0, 0);
            s1.Roster = new List<Student>();

            Student s = new Student();
            s.Id = 101;
            s.Name = "Sindhu";

            Student stu2 = new Student();
            stu2.Id = 102;
            stu2.Name = "Paromita";

            Student stu3 = new Student();
            stu3.Id = 103;
            stu3.Name = "Padma";

            s1.Register(s);
            s1.Register(stu2);
            s1.Register(stu3);
        }
Example #7
0
        public void MongoQueryExplainsExecutionPlansForFlyweightQueries()
        {
            using (var session = new Session())
            {
                session.Drop<TestProduct>();

                session.DB.GetCollection<TestProduct>().CreateIndex(p => p.Supplier.Name, "TestIndex", true, IndexOption.Ascending);

                session.Add(new TestProduct
                                {
                                    Name = "ExplainProduct",
                                    Price = 10,
                                    Supplier = new Supplier { Name = "Supplier", CreatedOn = DateTime.Now }
                                });

                // To see this manually you can run the following command in Mongo.exe against
                //the Product collection db.Product.ensureIndex({"Supplier.Name":1})

                // Then you can run this command to see a detailed explain plan
                // db.Product.find({"Supplier.Name":"abc"})

                // The following query is the same as running: db.Product.find({"Supplier.Name":"abc"}).explain()
                var query = new Expando();
                query["Supplier.Name"] = Q.Equals("Supplier");

                var result = session.DB.GetCollection<TestProduct>().Explain(query);

                Assert.Equal("BtreeCursor TestIndex", result.Cursor);
            }
        }
Example #8
0
 public static string GetSequencePrefix(IDataLayer dataLayer) {
     if (dataLayer == null)
         throw new ArgumentNullException("dataLayer");
     lock (SyncRoot) {
         if (dataLayerForCachedServerPrefix/*.Target*/ != dataLayer) {
             using (var session = new Session(dataLayer)) {
                 var sid = session.GetObjectByKey<XpoServerId>(0);
                 if (sid == null) {
                     // we can throw exception here instead of creating random prefix
                     sid = new XpoServerId(session) {
                         SequencePrefix = XpoDefault.NewGuid().ToString()
                     };
                     try {
                         sid.Save();
                     } catch {
                         sid = session.GetObjectByKey<XpoServerId>(0, true);
                         if (sid == null)
                             throw;
                     }
                 }
                 cachedSequencePrefix = sid.SequencePrefix;
                 dataLayerForCachedServerPrefix = dataLayer;
                 // dataLayerForCachedServerPrefix.Target = dataLayer; <<< if WeakReference
             }
         }
         return cachedSequencePrefix;
     }
 }
Example #9
0
 private XPClassInfo GetClassInfo(Session session, string assemblyQualifiedName, IEnumerable<Type> persistentTypes) {
     Type classType = persistentTypes.Where(type => type.FullName == assemblyQualifiedName).SingleOrDefault();
     if (classType != null) {
         return session.GetClassInfo(classType);
     }
     return null;
 }
        /// <summary>
        /// Initializes the loggly logger
        /// </summary>
        /// <param name="session">Current encompass session, used to load the config file</param>
        /// <param name="config">Config file to load.  Will re-initialize when this is used.</param>
        /// <param name="tags">Collection of loggly tags.  If null, we will load the Loggly.Tags element from the config.</param>
        public static void Init(Session session, IEncompassConfig config, ICollection<string> tags = null)
        {
            config.Init(session);
            if (tags != null)
            {
                foreach (string tag in tags)
                {
                    AddTag(tag);
                }
            }
            
           foreach (var tag in config.GetValue(LOGGLY_TAGS, string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            { 
                    AddTag(tag);
            }

            string configLogglyUrl = config.GetValue(LOGGLY_URL);

            if (configLogglyUrl != null)
            {
                SetPostUrl(configLogglyUrl);
            }
            bool allEnabled = config.GetValue(LOGGLY_ALL, false);
            bool errorEnabled = config.GetValue(LOGGLY_ERROR, false);
            bool warnEnabled = config.GetValue(LOGGLY_WARN, false);
            bool infoEnabled = config.GetValue(LOGGLY_INFO, false);
            bool debugEnabled = config.GetValue(LOGGLY_DEBUG, false);
            bool fatalEnabled = config.GetValue(LOGGLY_FATAL, false);

            Instance.ErrorEnabled = allEnabled || errorEnabled;
            Instance.WarnEnabled = allEnabled || warnEnabled;
            Instance.InfoEnabled = allEnabled || infoEnabled;
            Instance.DebugEnabled = allEnabled || debugEnabled;
            Instance.FatalEnabled = allEnabled || fatalEnabled;
        }
 public async void TestAlreadyLoggedOn()
 {
     var session = new Session(BasicServerConnectionMock);
     await session.LogOn(BasicAuthenticationMock);
     Assert.IsNotNull(session.UserInfo);
     await AssertEx.ThrowsAsync<InvalidOperationException>(async () => await session.LogOn(BasicAuthenticationMock));
 }
Example #12
0
 public static void Close(RCVHead head)
 {
     try
     {
         using (ISession session = new Session())
         {
             try
             {
                 session.BeginTransaction();
                 head.Close(session, false);
                 session.Commit();
             }
             catch (Exception er1)
             {
                 session.Rollback();
                 log.Error(string.Format("�ջ���{0}ǩ����ɣ��Զ��ر�ʱ�����쳣", head.OrderNumber), er1);
                 return;
             }
         }
     }
     catch (Exception er)
     {
         log.Error(string.Format("�ջ���{0}ǩ����ɣ��Զ��ر�ʱ�����쳣���޷��������ݿ�", head.OrderNumber), er);
         return;
     }
 }
    protected void MagicItemCommand(object sender, MagicItemEventArgs e)
    {
        if (e.CommandName != "Download")
            return;

        using (ISession session = new Session())
        {
            DateTime startDate = Cast.DateTime(this.txtDateFrom.Text, new DateTime(1900, 1, 1));
            DateTime endDate = Cast.DateTime(this.txtDateTo.Text, new DateTime(1900, 1, 1));

            int count = 0;
            DataSet ds = Report.SaleBySKUStat(session, startDate, endDate, this.txtItemCode.Text, Cast.Enum<Report_SaleByCode_OrderBy>(this.drpSort.SelectedValue), this.chkIncludeNoSale.Checked, -1, 0, false, ref count);
            string fileName = DownloadUtil.DownloadXls("Sale_BySKU_" + DateTime.Now.ToString("yyMMdd") + ".xls", "RPT_SALE_BYSKU_",
                new List<DownloadFormat>()
                    {
                        new DownloadFormat(DataType.NumberText, "货号", "ItemCode"),
                        new DownloadFormat(DataType.Text, "名称", "ItemName"),
                        new DownloadFormat(DataType.Text, "颜色", "ColorCode", "ColorText"),
                        new DownloadFormat(DataType.Text, "尺码", "SizeCode"),
                        new DownloadFormat(DataType.Number, "销售量", "SaleQty"),
                        new DownloadFormat(DataType.Number, "销售金额", "SaleAmt"),
                        new DownloadFormat(DataType.Number, "总采购", "PurQty"),
                        new DownloadFormat(DataType.Number, "销售率(%)", "SaleRate"),
                        new DownloadFormat(DataType.Number, "换货量", "ExcgQty"),
                        new DownloadFormat(DataType.Number, "换货率(%)", "ExcgRate"),
                        new DownloadFormat(DataType.Number, "退货量", "RtnQty"),
                        new DownloadFormat(DataType.Number, "退货率(%)", "RtnRate"),
                        new DownloadFormat(DataType.Number, "现有库存", "StoQty")
                    }, ds);
            this.frameDownload.Attributes["src"] = fileName;
        }
        WebUtil.DownloadHack(this, "txtDateFrom", "txtDateTo");
    }
        public static void ShowColorDropDown(DropDownButtonWidget color, Session.Client client,
			OrderManager orderManager, ColorPickerPaletteModifier preview)
        {
            Action<ColorRamp> onSelect = c =>
            {
                if (client.Bot == null)
                {
                    Game.Settings.Player.ColorRamp = c;
                    Game.Settings.Save();
                }

                color.RemovePanel();
                orderManager.IssueOrder(Order.Command("color {0} {1}".F(client.Index, c)));
            };

            Action<ColorRamp> onChange = c => preview.Ramp = c;

            var colorChooser = Game.LoadWidget(orderManager.world, "COLOR_CHOOSER", null, new WidgetArgs()
            {
                { "onSelect", onSelect },
                { "onChange", onChange },
                { "initialRamp", client.ColorRamp }
            });

            color.AttachPanel(colorChooser);
        }
 protected void MagicItemCommand(object sender, MagicItemEventArgs e)
 {
     if (e.CommandName == "Delete")
     {
         bool deleted = false;
         using (ISession session = new Session())
         {
             session.BeginTransaction();
             try
             {
                 foreach (RepeaterItem item in this.rptVendor.Items)
                 {
                     HtmlInputCheckBox chk = item.FindControl("checkbox") as HtmlInputCheckBox;
                     if (chk != null && chk.Checked)
                     {
                         int mid = Cast.Int(chk.Attributes["mid"]), lid = Cast.Int(chk.Attributes["lid"]);
                         deleted = deleted || RestrictLogis2Member.Delete(session, lid, mid) > 0;
                     }
                 }
                 session.Commit();
                 if (deleted)
                     QueryAndBindData(session, magicPagerMain.CurrentPageIndex, magicPagerMain.PageSize, true);
             }
             catch (Exception ex)
             {
                 session.Rollback();
                 WebUtil.ShowError(this, ex);
             }
         }
     }
 }
 public MapLayerCompiler(MapLayer _layer, Session _session)
 {
     map_layer = _layer;
     session = _session;
     paged = true;
     depth_first = true;
 }
Example #17
0
        public static CriteriaOperator GetClassTypeFilter(this Type type, Session session) {
            XPClassInfo xpClassInfo = session.GetClassInfo(type);
            XPObjectType xpObjectType = session.GetObjectType(xpClassInfo);

            return XPObject.Fields.ObjectType.IsNull() |
                   XPObject.Fields.ObjectType == new OperandValue(xpObjectType.Oid);
        }
        public override int OnReceive(Session session, Object data)
        {
            if (data is WebMessage)
            {
                WebMessage msg = data as WebMessage;

                if (msg.MessageType == WebMessage.MSG_TYPE_HANDSHAKE)
                {
                    Task.Factory.StartNew(() => { OnHandshake(session); });
                }
                else if (msg.MessageType == WebMessage.MSG_TYPE_PING)
                {
                    Task.Factory.StartNew(() => { OnPing(session, msg.RawContent); });
                }
                else if (msg.MessageType == WebMessage.MSG_TYPE_PONG)
                {
                    Task.Factory.StartNew(() => { OnPong(session, msg.RawContent); });
                }
                else
                {
                    // run further decode process here (or may run it within the thread, see ProcessMessage())
                    MessageCodec.DecodeMessage(session, msg);

                    ProcessMessage(new SessionContext(session, data));

                }
            }
            return base.OnReceive(session, data);
        }
        private ScriptResult CompileAndExecute(string code, Session session)
        {
            Logger.Debug("Compiling submission");
            try
            {
                var submission = session.CompileSubmission<object>(code);

                using (var exeStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    var result = submission.Compilation.Emit(exeStream, pdbStream: pdbStream);

                    if (result.Success)
                    {
                        Logger.Debug("Compilation was successful.");

                        var assembly = LoadAssembly(exeStream.ToArray(), pdbStream.ToArray());

                        return InvokeEntryPointMethod(session, assembly);
                    }

                    var errors = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                    
                    Logger.ErrorFormat("Error occurred when compiling: {0})", errors);

                    return new ScriptResult(compilationException: new ScriptCompilationException(errors));
                }
            }
            catch (Exception compileException)
            {
                //we catch Exception rather than CompilationErrorException because there might be issues with assembly loading too
                return new ScriptResult(compilationException: new ScriptCompilationException(compileException.Message, compileException));
            }
        }
Example #20
0
        public void ConnectShouldSkipHeadersWhenHttpProxyReturnsHttpStatus200()
        {
            var proxyEndPoint = new IPEndPoint(IPAddress.Loopback, 8123);
            var serverEndPoint = new IPEndPoint(IPAddress.Loopback, 8122);

            using (var proxyStub = new HttpProxyStub(proxyEndPoint))
            {
                proxyStub.Responses.Add(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n"));
                proxyStub.Responses.Add(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n"));
                proxyStub.Responses.Add(Encoding.ASCII.GetBytes("\r\n"));
                proxyStub.Responses.Add(Encoding.ASCII.GetBytes("SSH-666-SshStub"));
                proxyStub.Start();

                using (var session = new Session(CreateConnectionInfoWithProxy(proxyEndPoint, serverEndPoint, "anon"), _serviceFactoryMock.Object))
                {
                    try
                    {
                        session.Connect();
                        Assert.Fail();
                    }
                    catch (SshConnectionException ex)
                    {
                        Assert.IsNull(ex.InnerException);
                        Assert.AreEqual("Server version '666' is not supported.", ex.Message);
                    }
                }
            }
        }
        public virtual void OnPing(Session session, byte[] data)
        {
            WebSocketEventPackage events = Events as WebSocketEventPackage;
            if (events != null) events.FirePingEvent(session, data);

            session.Send(WebMessage.CreatePongMessage(data));
        }
Example #22
0
        public void ConnectShouldThrowProxyExceptionWhenHttpProxyResponseDoesNotContainStatusLine()
        {
            var proxyEndPoint = new IPEndPoint(IPAddress.Loopback, 8123);
            var serverEndPoint = new IPEndPoint(IPAddress.Loopback, 8122);

            using (var proxyStub = new HttpProxyStub(proxyEndPoint))
            {
                proxyStub.Responses.Add(Encoding.ASCII.GetBytes("Whatever\r\n"));
                proxyStub.Start();

                using (var session = new Session(CreateConnectionInfoWithProxy(proxyEndPoint, serverEndPoint, "anon"), _serviceFactoryMock.Object))
                {
                    try
                    {
                        session.Connect();
                        Assert.Fail();
                    }
                    catch (ProxyException ex)
                    {
                        Assert.IsNull(ex.InnerException);
                        Assert.AreEqual("HTTP response does not contain status line.", ex.Message);
                    }
                }
            }
        }
 protected void MagicItemCommand(object sender, MagicItemEventArgs e)
 {
     if (e.CommandName == "Delete")
     {
         try
         {
             using (ISession session = new Session())
             {
                 session.BeginTransaction();
                 try
                 {
                     for (int i = 0; i < this.rptSDHead.Items.Count; i++)
                     {
                         System.Web.UI.HtmlControls.HtmlInputCheckBox objCheckBox = this.rptSDHead.Items[i].FindControl("checkbox") as System.Web.UI.HtmlControls.HtmlInputCheckBox;
                         if (objCheckBox.Checked)
                             INVCheckHead.Delete(session, objCheckBox.Attributes["value"].Trim());
                     }
                     session.Commit();
                     QueryAndBindData(session, 1, this.magicPagerMain.PageSize, true);
                 }
                 catch (Exception ex)
                 {
                     session.Rollback();
                     throw ex;
                 }
             }
         }
         catch (Exception ex)
         {
             WebUtil.ShowError(this, "ɾ��ʧ��,�������Ա��ϵ!\r\nʧ����Ϣ:" + ex.Message);
             return;
         }
     }
 }
Example #24
0
    public static ActionResult RunAsAdminInstall(Session session)
    {
        MessageBox.Show("RunAsAdminInstall", "Embedded Managed CA");
        session.Log("Begin RunAsAdminInstall Hello World");

        return ActionResult.Success;
    }
Example #25
0
 public void Handle(Session Session, String data)
 {
     SFDataPacket Packet = new SFDataPacket(new string[] { "L", "1", "0", "0", "0" });
     byte[] InitDisplay = Encoding.Default.GetBytes(Encoders.DecryptMsg(Packet.create_message(), false) + "\0");
     Session.Sock.NoDelay = true;
     Session.Sock.Send(InitDisplay);
 }
Example #26
0
    public static ActionResult MyAdminAction(Session session)
    {
        MessageBox.Show("Hello World!!!!!!!!!!!", "Embedded Managed CA (Admin)");
        session.Log("Begin MyAdminAction Hello World");

        return ActionResult.Success;
    }
Example #27
0
    public static ActionResult MyCheckSql(Session session)
    {
        MessageBox.Show("MyCheckSql", "Embedded Managed CA");
        session.Log("Begin MyCheckSql Hello World");

        return ActionResult.Success;
    }
Example #28
0
        public void Load(IServiceProvider serviceProvider)
        {
            try
            {
                s_traceContext = (ITraceContext)serviceProvider.GetService(typeof(ITraceContext));

                //must have the icelib sdk license to get the session as a service
                s_session = (Session)serviceProvider.GetService(typeof(Session));
                s_connection = new Connection.Connection(s_session);
            }
            catch (ArgumentNullException)
            {
                s_traceContext.Error("unable to get Icelib Session, is the ICELIB SDK License available?");
                Debug.Fail("unable to get service.  Is the ICELIB SDK licence available?");
                throw;
            }

            s_interactionManager = new InteractionManager(s_session, (IQueueService)serviceProvider.GetService(typeof(IQueueService)), s_traceContext);
            s_statusManager = new CicStatusService(s_session, s_traceContext);
            s_notificationService = (INotificationService)serviceProvider.GetService(typeof(INotificationService));

            s_settingsManager = new SettingsManager();
            s_deviceManager = new DeviceManager(s_traceContext, new SpokesDebugLogger(s_traceContext));

            s_statusChanger = new StatusChanger(s_session, s_statusManager, s_deviceManager, s_settingsManager);
            s_notificationServer = new NotificationServer(s_deviceManager, s_settingsManager, s_notificationService);

            s_hookSwitchManager = new InteractionSyncManager(s_interactionManager, s_deviceManager, (IQueueService)serviceProvider.GetService(typeof(IQueueService)), s_traceContext, s_connection);

            s_outboundEventNotificationService = new OutboundEventNotificationService(s_session, s_statusManager, s_deviceManager, s_traceContext);

            s_traceContext.Always("Plantronics AddIn Loaded");
        }
Example #29
0
    public static ActionResult CompareVersionAtUpgrade(Session session)
    {
        MessageBox.Show("CompareVersionAtUpgrade", "Embedded Managed CA");
        session.Log("Begin CompareVersionAtUpgrade Hello World");

        return ActionResult.Success;
    }
Example #30
0
        public void ConnectShouldThrowProxyExceptionWhenHttpProxyReturnsHttpStatusOtherThan200()
        {
            var proxyEndPoint = new IPEndPoint(IPAddress.Loopback, 8123);
            var serverEndPoint = new IPEndPoint(IPAddress.Loopback, 8122);

            using (var proxyStub = new HttpProxyStub(proxyEndPoint))
            {
                proxyStub.Responses.Add(Encoding.ASCII.GetBytes("HTTP/1.0 501 Custom\r\n"));
                proxyStub.Start();

                using (var session = new Session(CreateConnectionInfoWithProxy(proxyEndPoint, serverEndPoint, "anon"), _serviceFactoryMock.Object))
                {
                    try
                    {
                        session.Connect();
                        Assert.Fail();
                    }
                    catch (ProxyException ex)
                    {
                        Assert.IsNull(ex.InnerException);
                        Assert.AreEqual("HTTP: Status code 501, \"Custom\"", ex.Message);
                    }
                }
            }
        }
Example #31
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");
		}
Example #32
0
 public CDS_SYS_SYS_Status(Session session) : base(session)
 {
 }
Example #33
0
 protected void BtnCerrarSesion_Click(object sender, EventArgs e)
 {
     Session.RemoveAll();
     Response.Redirect("servicios.aspx");
 }
Example #34
0
        public void Update()
        {
            _UpdateApplicationLifecycle();

            // Hide snackbar when currently tracking at least one plane.
            Session.GetTrackables <DetectedPlane>(m_AllPlanes);
            bool showSearchingUI = true;

            for (int i = 0; i < m_AllPlanes.Count; i++)
            {
                if (m_AllPlanes[i].TrackingState == TrackingState.Tracking)
                {
                    showSearchingUI = false;
                    break;
                }
            }

            SearchingForPlaneUI.SetActive(showSearchingUI);

            // If the player has not touched the screen, we are done with this update.
            Touch touch;

            if (Input.touchCount < 1 || (touch = Input.GetTouch(0)).phase != TouchPhase.Began)
            {
                return;
            }

            // Raycast against the location the player touched to search for planes.
            TrackableHit      hit;
            TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinPolygon |
                                              TrackableHitFlags.FeaturePointWithSurfaceNormal;

            if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit) && spawned == false)
            {
                spawned = true;
                // Use hit pose and camera pose to check if hittest is from the
                // back of the plane, if it is, no need to create the anchor.
                if ((hit.Trackable is DetectedPlane) &&
                    Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
                                hit.Pose.rotation * Vector3.up) < 0)
                {
                    Debug.Log("Hit at back of the current DetectedPlane");
                }
                else
                {
                    // Instantiate Andy model at the hit pose.
                    var andyObject = Instantiate(AndyAndroidPrefab, hit.Pose.position, hit.Pose.rotation);

                    // Compensate for the hitPose rotation facing away from the raycast (i.e. camera).
                    andyObject.transform.Rotate(0, k_ModelRotation, 0, Space.Self);

                    // Create an anchor to allow ARCore to track the hitpoint as understanding of the physical
                    // world evolves.
                    var anchor = hit.Trackable.CreateAnchor(hit.Pose);

                    dragonControls.Dragon = andyObject.transform;
                    dragonControls.Dragon.localEulerAngles = new Vector3(0, 360, 0);
                    dragonControls.gameObject.SetActive(true);

                    // Make Andy model a child of the anchor.
                    andyObject.transform.parent = anchor.transform;
                }
            }
        }
 public ActionResult LogOut()
 {
     Session.Abandon();
     return(RedirectToAction("Index", "Login"));
 }
Example #36
0
 protected override void InitializeLink(Session session)
 {
     _senderLink = new SenderLink(session, $"{Address}-sender", Address);
 }
Example #37
0
        void hover_token_changed(object sender, EventArgs e)
        {
            SplitContainer splitter = Controls[0] as SplitContainer;
            MapView        map      = splitter.Panel1.Controls[0] as MapView;

            fParentMap.HoverToken = map.HoverToken;

            string title = "";
            string info  = null;

            if (map.HoverToken is CreatureToken)
            {
                CreatureToken ct       = map.HoverToken as CreatureToken;
                EncounterSlot slot     = map.Encounter.FindSlot(ct.SlotID);
                ICreature     creature = Session.FindCreature(slot.Card.CreatureID, SearchType.Global);

                int hp_total    = slot.Card.HP;
                int hp_current  = hp_total - ct.Data.Damage;
                int hp_bloodied = hp_total / 2;

                if (map.ShowCreatureLabels)
                {
                    title = ct.Data.DisplayName;
                }
                else
                {
                    title = creature.Category;
                    if (title == "")
                    {
                        title = "Creature";
                    }
                }

                if (ct.Data.Damage == 0)
                {
                    info = "Not wounded";
                }
                if (hp_current < hp_total)
                {
                    info = "Wounded";
                }
                if (hp_current < hp_bloodied)
                {
                    info = "Bloodied";
                }
                if (hp_current <= 0)
                {
                    info = "Dead";
                }

                if (ct.Data.Conditions.Count != 0)
                {
                    info += Environment.NewLine;

                    foreach (OngoingCondition oc in ct.Data.Conditions)
                    {
                        info += Environment.NewLine;
                        info += oc.ToString(fParentMap.Encounter, false);
                    }
                }
            }

            if (map.HoverToken is Hero)
            {
                Hero hero = map.HoverToken as Hero;

                title = hero.Name;

                info  = hero.Race + " " + hero.Class;
                info += Environment.NewLine;
                info += "Player: " + hero.Player;
            }

            if (map.HoverToken is CustomToken)
            {
                CustomToken ct = map.HoverToken as CustomToken;

                if (map.ShowCreatureLabels)
                {
                    title = ct.Name;
                    info  = "(custom token)";
                }
            }

            Tooltip.ToolTipTitle = title;
            Tooltip.ToolTipIcon  = ToolTipIcon.Info;
            Tooltip.SetToolTip(map, info);
        }
Example #38
0
 { // Inherit from a different class to provide a custom primary key, concurrency and deletion behavior, etc. (https://documentation.devexpress.com/eXpressAppFramework/CustomDocument113146.aspx).
     public OrderBook(Session session)
         : base(session)
     {
     }
Example #39
0
        //
        // Sample invocation: Interop.Server amqp://guest:guest@localhost:5672
        //
        static int Main(string[] args)
        {
            String url = "amqp://*****:*****@127.0.0.1:5672";
            String requestQueueName = "service_queue";

            if (args.Length > 0)
            {
                url = args[0];
            }

            Connection.DisableServerCertValidation = true;
            // uncomment the following to write frame traces
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (l, f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            Connection connection = null;

            try
            {
                Address address = new Address(url);
                connection = new Connection(address);
                Session session = new Session(connection);

                // Create server receiver link
                // When messages arrive, reply to them
                ReceiverLink receiver = new ReceiverLink(session, "Interop.Server-receiver", requestQueueName);
                int          linkId   = 0;
                while (true)
                {
                    Message request = receiver.Receive();
                    if (null != request)
                    {
                        receiver.Accept(request);
                        String     replyTo = request.Properties.ReplyTo;
                        SenderLink sender  = new SenderLink(session, "Interop.Server-sender-" + (++linkId).ToString(), replyTo);

                        Message response = new Message(GetContent(request).ToUpper());
                        response.Properties = new Properties()
                        {
                            CorrelationId = request.Properties.MessageId
                        };

                        try
                        {
                            sender.Send(response);
                        }
                        catch (Exception exception)
                        {
                            Console.Error.WriteLine("Error waiting for response to be sent: {0} exception {1}",
                                                    GetContent(response), exception.Message);
                            break;
                        }
                        sender.Close();
                        Console.WriteLine("Processed request: {0} -> {1}",
                                          GetContent(request), GetContent(response));
                    }
                    else
                    {
                        // timed out waiting for request. This is normal.
                        Console.WriteLine("Timeout waiting for request. Keep waiting...");
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Exception {0}.", e);
                if (null != connection)
                {
                    connection.Close();
                }
            }
            return(1);
        }
Example #40
0
 protected void Button_LogOut_Click(object sender, EventArgs e)
 {
     Session.Abandon();
     Response.Redirect("Login.aspx");
 }
Example #41
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            Classi.SiteModule _SiteModule = (Classi.SiteModule)HttpContext.Current.Items["SiteModule"];

            this.btnsCompletaOdl.Visible = _SiteModule.IsEditable;

            FunId    = _SiteModule.ModuleId;
            HelpLink = _SiteModule.HelpLink;
            this.PageTitle1.Title             = _SiteModule.ModuleTitle;
            this.GridTitle1.hplsNuovo.Visible = false;

            String scriptString = "<script language=JavaScript>var dettaglio;\n";

            scriptString += "function chiudi() {\n";
            scriptString += "if (dettaglio!=null)";
            scriptString += "if (document.Form1.hidRicerca.value=='0'){";
            scriptString += " dettaglio.close();}";
            scriptString += " else{";
            scriptString += "document.Form1.hidRicerca.value='1';}}<";
            scriptString += "/";
            scriptString += "script>";


            if (!this.IsClientScriptBlockRegistered("clientScript"))
            {
                this.RegisterClientScriptBlock("clientScript", scriptString);
            }

            System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
            sbValid.Append("if (typeof(ControllaData) == 'function') { ");
            sbValid.Append("if (ControllaData() == false) { return false; }} ");
            sbValid.Append(this.Page.GetPostBackEventReference(this.btnsCompletaOdl));
            sbValid.Append(";");
            this.btnsCompletaOdl.Attributes.Add("onclick", sbValid.ToString());

            if (!Page.IsPostBack)
            {
                Session.Remove("DatiListMP");

                if (Context.Handler is TheSite.ManutenzioneProgrammata.CompletamentoMP)
                {
                    _fp = (TheSite.ManutenzioneProgrammata.CompletamentoMP)Context.Handler;
                    this.ViewState.Add("mioContenitore", _fp._Contenitore);
                }
                if (Context.Handler is TheSite.ManutenzioneProgrammata.SfogliaRdlOdl_MP)
                {
                    SfogliaRdlOdl_MP _fp2 = (TheSite.ManutenzioneProgrammata.SfogliaRdlOdl_MP)Context.Handler;
                    this.ViewState.Add("mioContenitore", _fp2._Contenitore);
                    this.ViewState.Add("paginardl", "paginardl");
                }

                ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
                if (Request.QueryString["wo_id"] != null)
                {
                    this.wo_id = Request.QueryString["wo_id"];
                }
                if (Context.Items["wo_id"] != null)
                {
                    this.wo_id = (string)Context.Items["wo_id"];
                }

                Ricerca(Int32.Parse(this.wo_id));
            }
            else
            {
                if (hiddenreload.Value == "1")
                {
                    Ricerca(Int32.Parse(this.wo_id));
                }
            }
        }
Example #42
0
		public async Task<ActionResult> LogOut(){
			Session.Abandon();
			return RedirectToAction("Forum", "Home");
		}
        /// <summary>
        /// Preprocess
        /// </summary>
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            Session.AssertAuthentication();
        }
Example #44
0
 protected void btnLogout_Click(object sender, EventArgs e)
 {
     Session.Abandon();
     Response.Redirect("Home.aspx");
 }
Example #45
0
    public StatementArg(int statementReportType, string dayBegin, string dayTo, string IDs, string rdlc, AsyncResult asyncResult, Session session)
        : base(session)
    {
        this._StatementReportType = statementReportType;
        this._DayBegin            = dayBegin;
        this._DayTo = dayTo;
        this._IDs   = IDs;
        this._Rdlc  = rdlc;

        this._AsyncResult = asyncResult;
    }
Example #46
0
        internal static bool WriteStream(StreamWriter swOutput, Session[] oSessions, bool bUseV1dot2Format, EventHandler <ProgressCallbackEventArgs> evtProgressNotifications, int iMaxTextBodyLength, int iMaxBinaryBodyLength)
        {
            HTTPArchiveJSONExport._iMaxTextBodyLength   = iMaxTextBodyLength;
            HTTPArchiveJSONExport._iMaxBinaryBodyLength = iMaxBinaryBodyLength;
            Hashtable hashtable = new Hashtable();

            hashtable.Add("version", bUseV1dot2Format ? "1.2" : "1.1");
            hashtable.Add("pages", new ArrayList(0));
            if (bUseV1dot2Format)
            {
                hashtable.Add("comment", "exported @ " + DateTime.Now.ToString());
            }
            Hashtable hashtable2 = new Hashtable();

            hashtable2.Add("name", "Fiddler");
            hashtable2.Add("version", Application.ProductVersion);
            if (bUseV1dot2Format)
            {
                hashtable2.Add("comment", "http://www.fiddler2.com");
            }
            hashtable.Add("creator", hashtable2);
            ArrayList arrayList = new ArrayList();
            int       num       = 0;
            int       i         = 0;

            while (i < oSessions.Length)
            {
                Session session = oSessions[i];
                try
                {
                    if (session.get_state() < 11)
                    {
                        goto IL_24D;
                    }
                    Hashtable hashtable3 = new Hashtable();
                    hashtable3.Add("startedDateTime", session.Timers.ClientBeginRequest.ToString("o"));
                    hashtable3.Add("request", HTTPArchiveJSONExport.getRequest(session));
                    hashtable3.Add("response", HTTPArchiveJSONExport.getResponse(session, bUseV1dot2Format));
                    hashtable3.Add("cache", new Hashtable());
                    Hashtable timings = HTTPArchiveJSONExport.getTimings(session.Timers, bUseV1dot2Format);
                    hashtable3.Add("time", HTTPArchiveJSONExport.getTotalTime(timings));
                    hashtable3.Add("timings", timings);
                    if (bUseV1dot2Format)
                    {
                        string value = session.get_Item("ui-comments");
                        if (!string.IsNullOrEmpty(value))
                        {
                            hashtable3.Add("comment", session.get_Item("ui-comments"));
                        }
                        string arg_1A9_0 = session.m_hostIP;
                        if (!string.IsNullOrEmpty(value) && !session.isFlagSet(2048))
                        {
                            hashtable3.Add("serverIPAddress", session.m_hostIP);
                        }
                        hashtable3.Add("connection", session.get_clientPort().ToString());
                    }
                    arrayList.Add(hashtable3);
                }
                catch (Exception ex)
                {
                    FiddlerApplication.ReportException(ex, "Failed to Export Session");
                }
                goto IL_20B;
IL_24D:
                i++;
                continue;
IL_20B:
                num++;
                if (evtProgressNotifications == null)
                {
                    goto IL_24D;
                }
                ProgressCallbackEventArgs progressCallbackEventArgs = new ProgressCallbackEventArgs((float)num / (float)oSessions.Length, "Wrote " + num.ToString() + " sessions to HTTPArchive.");
                evtProgressNotifications(null, progressCallbackEventArgs);
                if (progressCallbackEventArgs.get_Cancel())
                {
                    return(false);
                }
                goto IL_24D;
            }
            hashtable.Add("entries", arrayList);
            swOutput.WriteLine(JSON.JsonEncode(new Hashtable
            {
                {
                    "log",
                    hashtable
                }
            }));
            return(true);
        }
Example #47
0
 protected void Page_Load(object sender, EventArgs e)
 {
     Session.Add("tipo", "modificar");
     this.MaintainScrollPositionOnPostBack = true;
 }
Example #48
0
 public static Task AsyncStart(Session session, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Task.Run(() => Start(session, cancellationToken), cancellationToken));
 }
 /// <summary>
 /// 查找当前会话里已经打开的相同对话框
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="session"></param>
 /// <returns></returns>
 public static T FindCurrentTypeFormInSession <T>(Session session) where T : DialogBase
 {
     return(Application.OpenForms.OfType <T>().FirstOrDefault(s => s.Session == session));
 }
Example #50
0
 void LoadIndividual(string ID)
 {
     this.individual = Session.Get <Individual>(ID);
 }
Example #51
0
 public wartungWartungsPosition(Session session)
     : base(session)
 {
 }
 /// <summary>
 /// 执行初始化
 /// </summary>
 /// <param name="session"></param>
 public virtual void InitSession(Session session)
 {
     Session = session;
 }
Example #53
0
 public Line(Session session) : base(session)
 {
 }
        /// <summary>
        /// Resolve the parameters supplied by the player into usable values.
        /// </summary>
        /// <param name="session">the session of the player who sent the command</param>
        /// <param name="aceParsedParameters">the collection of parameters supplied by the default parameter parser</param>
        /// <param name="parameters">the resolution details for every parameter</param>
        /// <param name="rawIncluded">whether or not the raw unparsed command line minus the command name was included as the first parameter</param>
        /// <returns>the parameters were successfully resolved or not</returns>
        public static bool ResolveACEParameters(Session session, IEnumerable <string> aceParsedParameters, IEnumerable <ACECommandParameter> parameters, bool rawIncluded = false)
        {
            string parameterBlob = "";

            if (rawIncluded)
            {
                parameterBlob = aceParsedParameters.First();
            }
            else
            {
                parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
            }
            int commaCount = parameterBlob.Count(x => x == ',');

            List <ACECommandParameter> acps = parameters.ToList();

            for (int i = acps.Count - 1; i > -1; i--)
            {
                ACECommandParameter acp = acps[i];
                acp.ParameterNo = i + 1;
                if (parameterBlob.Length > 0)
                {
                    try
                    {
                        switch (acp.Type)
                        {
                        case ACECommandParameterType.PositiveLong:
                            Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                            if (match4.Success)
                            {
                                if (!long.TryParse(match4.Groups[1].Value, out long val))
                                {
                                    return(false);
                                }
                                if (val <= 0)
                                {
                                    return(false);
                                }
                                acp.Value     = val;
                                acp.Defaulted = false;
                                parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
                            }
                            break;

                        case ACECommandParameterType.Long:
                            Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                            if (match3.Success)
                            {
                                if (!long.TryParse(match3.Groups[1].Value, out long val))
                                {
                                    return(false);
                                }
                                acp.Value     = val;
                                acp.Defaulted = false;
                                parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
                            }
                            break;

                        case ACECommandParameterType.ULong:
                            Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                            if (match2.Success)
                            {
                                if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
                                {
                                    return(false);
                                }
                                acp.Value     = val;
                                acp.Defaulted = false;
                                parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
                            }
                            break;

                        case ACECommandParameterType.Location:
                            Position position = null;
                            Match    match    = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
                            if (match.Success)
                            {
                                string ns = match.Groups[1].Value;
                                string ew = match.Groups[2].Value;
                                if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
                                {
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(errorMessage);
                                    }
                                    return(false);
                                }
                                else
                                {
                                    acp.Value     = position;
                                    acp.Defaulted = false;
                                    int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
                                    parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
                                }
                            }
                            break;

                        case ACECommandParameterType.OnlinePlayerName:
                            if (i != 0)
                            {
                                throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                            }
                            parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                            Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
                            if (targetPlayer == null)
                            {
                                string errorMsg = $"Unable to find player {parameterBlob}";
                                if (session != null)
                                {
                                    ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                }
                                else
                                {
                                    Console.WriteLine(errorMsg);
                                }
                                return(false);
                            }
                            else
                            {
                                acp.Value     = targetPlayer;
                                acp.Defaulted = false;
                            }
                            break;
 protected void LogoutBtn_Click(object sender, EventArgs e)
 {
     Session.Clear();
     Session.Abandon();
     Response.Redirect("Login.aspx");
 }
Example #56
0
 protected void linkOut_Click(object sender, EventArgs e)
 {
     Session.Clear();
     Request.Cookies.Clear();
     Response.Redirect("login.aspx");
 }
Example #57
0
        private UserType _AssignValues(UserType request, DocConstantPermission permission, Session session)
        {
            if (permission != DocConstantPermission.ADD && (request == null || request.Id <= 0))
            {
                throw new HttpError(HttpStatusCode.NotFound, $"No record");
            }

            if (permission == DocConstantPermission.ADD && !DocPermissionFactory.HasPermissionTryAdd(currentUser, "UserType"))
            {
                throw new HttpError(HttpStatusCode.Forbidden, "You do not have ADD permission for this route.");
            }

            request.Select = request.Select ?? new List <string>();

            UserType ret = null;

            request = _InitAssignValues <UserType>(request, permission, session);
            //In case init assign handles create for us, return it
            if (permission == DocConstantPermission.ADD && request.Id > 0)
            {
                return(request);
            }

            var cacheKey = GetApiCacheKey <UserType>(DocConstantModelName.USERTYPE, nameof(UserType), request);

            //First, assign all the variables, do database lookups and conversions
            DocEntityLookupTable pPayrollStatus = GetLookup(DocConstantLookupTable.USERPAYROLLSTATUS, request.PayrollStatus?.Name, request.PayrollStatus?.Id);
            DocEntityLookupTable pPayrollType   = GetLookup(DocConstantLookupTable.USERPAYROLLTYPE, request.PayrollType?.Name, request.PayrollType?.Id);
            DocEntityLookupTable pType          = GetLookup(DocConstantLookupTable.USEREMPLOYEETYPE, request.Type?.Name, request.Type?.Id);
            var pUsers    = GetVariable <Reference>(request, nameof(request.Users), request.Users?.ToList(), request.UsersIds?.ToList());
            var pArchived = true == request.Archived;
            var pLocked   = request.Locked;

            var entity = InitEntity <DocEntityUserType, UserType>(request, permission, session);

            if (AllowPatchValue <UserType, bool>(request, DocConstantModelName.USERTYPE, pArchived, permission, nameof(request.Archived), pArchived != entity.Archived))
            {
                entity.Archived = pArchived;
            }
            if (AllowPatchValue <UserType, DocEntityLookupTable>(request, DocConstantModelName.USERTYPE, pPayrollStatus, permission, nameof(request.PayrollStatus), pPayrollStatus != entity.PayrollStatus))
            {
                entity.PayrollStatus = pPayrollStatus;
            }
            if (AllowPatchValue <UserType, DocEntityLookupTable>(request, DocConstantModelName.USERTYPE, pPayrollType, permission, nameof(request.PayrollType), pPayrollType != entity.PayrollType))
            {
                entity.PayrollType = pPayrollType;
            }
            if (AllowPatchValue <UserType, DocEntityLookupTable>(request, DocConstantModelName.USERTYPE, pType, permission, nameof(request.Type), pType != entity.Type))
            {
                entity.Type = pType;
            }
            if (request.Locked && AllowPatchValue <UserType, bool>(request, DocConstantModelName.USERTYPE, pArchived, permission, nameof(request.Locked), pLocked != entity.Locked))
            {
                entity.Archived = pArchived;
            }
            entity.SaveChanges(permission);

            var idsToInvalidate = new List <int>();

            idsToInvalidate.AddRange(PatchCollection <UserType, DocEntityUserType, Reference, DocEntityUser>(request, entity, pUsers, permission, nameof(request.Users)));
            if (idsToInvalidate.Any())
            {
                idsToInvalidate.Add(entity.Id);
                DocCacheClient.RemoveByEntityIds(idsToInvalidate);
                DocCacheClient.RemoveSearch(DocConstantModelName.USERTYPE);
            }

            entity.SaveChanges(permission);
            DocPermissionFactory.SetSelect <UserType>(currentUser, nameof(UserType), request.Select);
            ret = entity.ToDto();

            var cacheExpires = DocResources.Metadata.GetCacheExpiration(DocConstantModelName.USERTYPE);

            DocCacheClient.Set(key: cacheKey, value: ret, entityId: request.Id, entityType: DocConstantModelName.USERTYPE, cacheExpires);

            return(ret);
        }
 public ActionResult logout()
 {
     Session.Clear();
     FormsAuthentication.SignOut();
     return(RedirectToAction("Index", "Login"));
 }
Example #59
0
 public XPOUnivBaseBall(Session session) : base(session) { }
 protected void LinkButton2_Click(object sender, EventArgs e)
 {
     Session.Remove("admin");
     Response.Redirect("AdminLogin.aspx");
 }