コード例 #1
0
        private static void OnCacheItemRemoved(string key, object value, CacheItemRemovedReason reason)
        {
            s_log.Debug("end session " + key + " because of " + reason);

            try
            {
                HttpSessionState ss = CreateSessionState(key, value);

                VirtualEnvironment.RaiseEndSession(ss, reason);
            }
            catch (Exception ex)
            {
                string msg = "Failure during EndSession event handling";
                // are we on a current request?
                if (HttpContext.Current != null)
                {
                    s_log.Error(msg, ex);
                }
                else
                {
                    // this is an async session timout - log as fatal since this is the thread's exit point!
                    s_log.Fatal(msg, ex);
                }
            }
            finally
            {
                if (s_originalCallback != null)
                {
                    s_originalCallback(key, value, reason);
                }
            }
        }
コード例 #2
0
    public void Reduce(VirtualEnvironment virtualEnvironment, Room targetRoom, Room currentRoom, Bound2D realSpace)
    {
        float xMinDist = realSpace.Min.x - targetRoom.Min.x;
        float xMaxDist = realSpace.Max.x - targetRoom.Max.x;
        float yMinDist = realSpace.Min.y - targetRoom.Min.y;
        float yMaxDist = realSpace.Max.y - targetRoom.Max.y;

        if (xMinDist > 0) // 1벽
        {
            virtualEnvironment.MoveWall(targetRoom, 1, xMinDist, currentRoom);
        }
        if (xMaxDist < 0) // 3벽
        {
            virtualEnvironment.MoveWall(targetRoom, 3, xMaxDist, currentRoom);
        }

        if (yMinDist > 0) // 2벽
        {
            virtualEnvironment.MoveWall(targetRoom, 2, yMinDist, currentRoom);
        }
        if (yMaxDist < 0) // 0벽
        {
            virtualEnvironment.MoveWall(targetRoom, 0, yMaxDist, currentRoom);
        }
    }
コード例 #3
0
ファイル: WebObjectUtils.cs プロジェクト: silence99/FrameWork
        /// <summary>
        /// Calls the underlying ASP.NET infrastructure to obtain the compiled page type
        /// relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>.
        /// </summary>
        /// <param name="pageUrl">
        /// The filename of the ASPX page relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>
        /// </param>
        /// <returns>
        /// The <see cref="System.Type"/> of the ASPX page
        /// referred to by the supplied <paramref name="pageUrl"/>.
        /// </returns>
        public static Type GetCompiledPageType(string pageUrl)
        {
            if (s_log.IsDebugEnabled)
            {
                s_log.Debug("getting page type for " + pageUrl);
            }

            string rootedVPath = WebUtils.CombineVirtualPaths(VirtualEnvironment.CurrentExecutionFilePath, pageUrl);

            if (s_log.IsDebugEnabled)
            {
                s_log.Debug("page vpath is " + rootedVPath);
            }

            Type pageType = VirtualEnvironment.GetCompiledType(rootedVPath);

//#if NET_2_0
//            pageType = BuildManager.GetCompiledType( rootedVPath ); // requires rooted virtual path!
//#else
//            pageType = CreatePageInstance(pageUrl).GetType();
//#endif

            if (s_log.IsDebugEnabled)
            {
                s_log.Debug(string.Format("got page type '{0}' for vpath '{1}'", pageType.FullName, rootedVPath));
            }
            return(pageType);
        }
コード例 #4
0
        /// <summary>
        /// Registers this module for all events required by the Spring.Web framework
        /// </summary>
        public virtual void Init(HttpApplication app)
        {
            lock (typeof(WebSupportModule))
            {
                s_log.Debug("Initializing Application instance");
                if (!s_isInitialized)
                {
                    HttpModuleCollection modules = app.Modules;
                    foreach (string moduleKey in modules.AllKeys)
                    {
                        if (modules[moduleKey] is SessionStateModule)
                        {
                            HookSessionEvent((SessionStateModule)modules[moduleKey]);
                        }
                    }
                }
                s_isInitialized = true;

                // signal, that VirtualEnvironment is ready to accept
                // handler registrations for EndRequest and EndSession events
                VirtualEnvironment.SetInitialized();
            }

            app.PreRequestHandlerExecute += new EventHandler(OnConfigureHandler);
            app.EndRequest += new EventHandler(VirtualEnvironment.RaiseEndRequest);

#if NET_2_0
            // TODO: this is only a workaround to get us up & running in IIS7/integrated mode
            // We must review all code for relative virtual paths - they must be resolved to application-relative paths
            // during parsing of the object definitions
            bool hideRequestResponse = false;
            if (ContextHideRequestResponse != null)
            {
                hideRequestResponse = (bool)ContextHideRequestResponse.GetValue(app.Context);
                ContextHideRequestResponse.SetValue(app.Context, false);
            }
#endif
            try
            {
                // ensure context is instantiated
                IConfigurableApplicationContext appContext = WebApplicationContext.GetRootContext() as IConfigurableApplicationContext;
                // configure this app + it's module instances
                if (appContext == null)
                {
                    throw new InvalidOperationException("Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
                }

                HttpApplicationConfigurer.Configure(appContext, app);
            }
            finally
            {
#if NET_2_0
                if (ContextHideRequestResponse != null)
                {
                    ContextHideRequestResponse.SetValue(app.Context, hideRequestResponse);
                }
#endif
            }
        }
        private VirtualEnvironment Convert(VirtualHPartitioningEnvironment env)
        {
            VirtualEnvironment result = new VirtualEnvironment();

            result.WorkloadAnalysisID = context.WorkloadAnalysis.ID;
            result.Type = VirtualEnvironmentType.HPartitionings;
            return(result);
        }
        private VirtualEnvironment Convert(VirtualIndicesEnvironment env)
        {
            VirtualEnvironment result = new VirtualEnvironment();

            result.WorkloadAnalysisID = context.WorkloadAnalysis.ID;
            result.Type = VirtualEnvironmentType.Indices;
            return(result);
        }
        private VirtualEnvironmentPossibleIndex Convert(VirtualEnvironment environment, PossibleIndex possibleIndex, VirtualIndicesEnvironmentIndexEvaluation indexEval)
        {
            VirtualEnvironmentPossibleIndex result = new VirtualEnvironmentPossibleIndex();

            result.PossibleIndexID      = possibleIndex.ID;
            result.VirtualEnvironemntID = environment.ID;
            result.ImprovementRatio     = indexEval.ImprovementRatio;
            return(result);
        }
 private VirtualEnvironmentPossibleCoveringIndex Convert(VirtualEnvironment env, long statementID, PossibleIndex createdIndex)
 {
     return(new VirtualEnvironmentPossibleCoveringIndex()
     {
         VirtualEnvironmentID = env.ID,
         PossibleIndexID = createdIndex.ID,
         NormalizedStatementID = statementID,
     });
 }
 private DAL.Contracts.VirtualEnvironmentStatementEvaluation Convert(VirtualEnvironment env, long statementID, ExecutionPlan plan, VirtualEnvironmentStatementEvaluation eval)
 {
     DAL.Contracts.VirtualEnvironmentStatementEvaluation result = new DAL.Contracts.VirtualEnvironmentStatementEvaluation();
     result.ExecutionPlanID        = plan.ID;
     result.NormalizedStatementID  = statementID;
     result.VirtualEnvironmentID   = env.ID;
     result.GlobalImprovementRatio = eval.GlobalImprovementRatio;
     result.LocalImprovementRatio  = eval.LocalImprovementRatio;
     return(result);
 }
コード例 #10
0
ファイル: PagerProvider.cs プロジェクト: maznabili/nledger
        public string GetDefaultPagerPath()
        {
            var defaultPager = MainApplicationContext.Current.DefaultPager;

            if (String.IsNullOrEmpty(defaultPager))
            {
                defaultPager = VirtualEnvironment.GetEnvironmentVariable("PAGER");
            }

            return(defaultPager);
        }
コード例 #11
0
ファイル: QuoteProvider.cs プロジェクト: taiab/nledger
        public bool Get(string command, out string response)
        {
            if (String.IsNullOrWhiteSpace(command))
            {
                throw new ArgumentNullException("command");
            }

            var getQuotePath = VirtualEnvironment.GetEnvironmentVariable("GETQUOTEPATH");

            return(MainApplicationContext.Current.ProcessManager.Execute("cmd", "/c " + command, getQuotePath, out response) == 0);
        }
コード例 #12
0
    void Adjust(VirtualEnvironment virtualEnvironment, Room currentRoom, UserBody user)
    {
        List <Door> connectedDoors = virtualEnvironment.GetConnectedDoors(currentRoom);

        foreach (var door in connectedDoors)
        {
            if (!user.IsTargetInUserFov(door.Position))
            {
                virtualEnvironment.MoveDoor(currentRoom, door, door.GetThisRoomWrapper(currentRoom).originWeight);
            }
        }
    }
        private VirtualEnvironmentPossibleHPartitioning Convert(VirtualEnvironment environment, DBMS.Contracts.HPartitioningDefinition partitioning, VirtualHPartitioningEnvironmentHPartitioningEvaluation eval)
        {
            VirtualEnvironmentPossibleHPartitioning result = new VirtualEnvironmentPossibleHPartitioning();
            var definition = dbObjectDefinitionGenerator.Generate(partitioning);

            result.PartitioningStatement = definition.PartitioningStatement;
            result.PartitionStatements   = definition.PartitionStatements;
            result.RelationID            = partitioning.Relation.ID;
            result.VirtualEnvironmentID  = environment.ID;
            result.ImprovementRatio      = eval.ImprovementRatio;
            return(result);
        }
 private DAL.Contracts.VirtualEnvironmentStatementEvaluation Convert(VirtualEnvironment env, long statementID, ExecutionPlan plan, VirtualEnvironmentStatementEvaluation eval,
                                                                     HashSet <long> affectingIndicesIds, HashSet <long> usedIndicesIds)
 {
     DAL.Contracts.VirtualEnvironmentStatementEvaluation result = new DAL.Contracts.VirtualEnvironmentStatementEvaluation();
     result.ExecutionPlanID        = plan.ID;
     result.NormalizedStatementID  = statementID;
     result.VirtualEnvironmentID   = env.ID;
     result.GlobalImprovementRatio = eval.GlobalImprovementRatio;
     result.LocalImprovementRatio  = eval.LocalImprovementRatio;
     result.AffectingIndices       = affectingIndicesIds;
     result.UsedIndices            = usedIndicesIds;
     return(result);
 }
コード例 #15
0
    static bool NeedAdjust(VirtualEnvironment virtualEnvironment, Room currentRoom)
    {
        List <Door> connectedDoors = virtualEnvironment.GetConnectedDoors(currentRoom);

        foreach (var door in connectedDoors)
        {
            if (Mathf.Abs(door.GetThisRoomWrapper(currentRoom).weight - door.GetThisRoomWrapper(currentRoom).originWeight) > 0.01f)
            {
                return(true);
            }
        }

        return(false);
    }
コード例 #16
0
ファイル: WebObjectUtils.cs プロジェクト: silence99/FrameWork
        /// <summary>
        /// Gets the controls type from a given filename
        /// </summary>
        public static Type GetControlType(string controlName)
        {
            AssertUtils.ArgumentHasText(controlName, "controlName");
            if (s_log.IsDebugEnabled)
            {
                s_log.Debug("getting control type for " + controlName);
            }

//            HttpContext ctx = HttpContext.Current;
//            if (ctx == null)
//            {
//                throw new ObjectCreationException( "Unable to get control type. HttpContext is not defined." );
//            }

            string rootedVPath = WebUtils.CombineVirtualPaths(VirtualEnvironment.CurrentExecutionFilePath, controlName);

            if (s_log.IsDebugEnabled)
            {
                s_log.Debug("control vpath is " + rootedVPath);
            }

            Type controlType;

            try
            {
//#if NET_2_0
//                controlType = BuildManager.GetCompiledType( rootedVPath ); // requires rooted virtual path!
//#else
//              controlType = (Type) miGetCompiledUserControlType.Invoke(null, new object[] { rootedVPath, null, ctx });
//#endif
                controlType = VirtualEnvironment.GetCompiledType(rootedVPath);
            }
            catch (HttpException httpEx)
            {
                // for better error-handling suppress 404 HttpExceptions here
                if (httpEx.GetHttpCode() == 404)
                {
                    throw new FileNotFoundException(string.Format("Control '{0}' does not exist", rootedVPath));
                }
                throw;
            }

            if (s_log.IsDebugEnabled)
            {
                s_log.Debug(string.Format("got control type '{0}' for vpath '{1}'", controlType.FullName, rootedVPath));
            }
            return(controlType);
        }
コード例 #17
0
        /// <summary>
        /// Resolves the <see cref="System.IO.FileInfo"/> handle
        /// for the supplied <paramref name="resourceName"/>.
        /// </summary>
        /// <param name="resourceName">
        /// The name of the file system resource.
        /// </param>
        /// <returns>
        /// The <see cref="System.IO.FileInfo"/> handle for this resource.
        /// </returns>
        protected override FileInfo ResolveFileHandle(string resourceName)
        {
            this.absolutePath = ResolveResourceNameWithoutProtocol(resourceName);
            if (!this.absolutePath.StartsWith("/"))
            {
                string currentPath = VirtualEnvironment.CurrentVirtualFilePath;
                int    n           = currentPath.LastIndexOfAny(new char[] { '/', '\\' });
                if (n >= 0)
                {
                    currentPath = currentPath.Substring(0, n);
                }
                this.absolutePath = currentPath + '/' + this.absolutePath;
            }

            return(new FileInfo(VirtualEnvironment.MapPath(this.absolutePath)));
        }
コード例 #18
0
    public bool[] CheckWallMovable(VirtualEnvironment virtualEnvironment, Room currentRoom, UserBody userBody, float[] translate) // translate은 xx,y 좌표계 기준으로 부호가 결정
    {
        bool[] isMovable = new bool[4];
        for (int i = 0; i < 4; i++)
        {
            isMovable[i] = true; // i와 i+1 사이 wall
        }

        // 벽이 사용자와 충분히 멀리 있는지를 판단
        for (int i = 0; i < 4; i++)
        {
            Vector2 wallPosition = currentRoom.GetEdge2D(i, Space.World);

            if (i % 2 == 0 && Mathf.Abs(wallPosition.y - userBody.Position.y) < 0.4f) // 현재 벽 i가 0, 2번 벽이고 user와 너무 가까운 경우, 0.1f는 여유 boundary , user.Size.y / 2
            {
                isMovable[i] = false;
            }
            else if (i % 2 != 0 && Mathf.Abs(wallPosition.x - userBody.Position.x) < 0.4f) // user.Size.x / 2
            {
                isMovable[i] = false;
            }
        }

        // 벽이 사용자 시야에 있는지를 판단
        for (int i = 0; i < 4; i++)
        {
            Vector2 vertexPosition = currentRoom.GetVertex2D(i, Space.World);
            Vector2 wallPosition   = currentRoom.GetEdge2D(i, Space.World);

            if (userBody.IsTargetInUserFov(vertexPosition))
            {
                isMovable[Utility.mod(i, 4)]     = false;
                isMovable[Utility.mod(i - 1, 4)] = false;
            }

            if (userBody.IsTargetInUserFov(wallPosition))
            {
                isMovable[Utility.mod(i, 4)] = false;
            }
        }

        return(isMovable);
    }
コード例 #19
0
ファイル: WebObjectUtils.cs プロジェクト: silence99/FrameWork
        /// <summary>
        /// Creates the raw handler instance without any exception handling
        /// </summary>
        /// <param name="pageUrl"></param>
        /// <returns></returns>
        internal static IHttpHandler CreateHandler(string pageUrl)
        {
            IHttpHandler page;

//            HttpContext ctx = HttpContext.Current;
//#if NET_1_1
//                string physicalPath = ctx.Server.MapPath(pageUrl);
//				s_log.Debug(string.Format("constructing page virtual path '{0}' from physical file '{1}'", pageUrl, physicalPath));
//              page = PageParser.GetCompiledPageInstance(pageUrl, physicalPath, ctx);
//#else
//            string rootedVPath = WebUtils.CombineVirtualPaths( ctx.Request.CurrentExecutionFilePath, pageUrl );
//            if (s_log.IsDebugEnabled)
//            {
//                s_log.Debug( "page vpath is " + rootedVPath );
//            }
//
//            page = BuildManager.CreateInstanceFromVirtualPath( rootedVPath, typeof( IHttpHandler ) ) as IHttpHandler;
//#endif
            page = VirtualEnvironment.CreateInstanceFromVirtualPath(pageUrl, typeof(IHttpHandler)) as IHttpHandler;
            return(page);
        }
コード例 #20
0
        /// <summary>
        /// Calls the underlying ASP.NET infrastructure to obtain the compiled page type
        /// relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>.
        /// </summary>
        /// <param name="pageUrl">
        /// The filename of the ASPX page relative to the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath"/>
        /// </param>
        /// <returns>
        /// The <see cref="System.Type"/> of the ASPX page
        /// referred to by the supplied <paramref name="pageUrl"/>.
        /// </returns>
        public static Type GetCompiledPageType(string pageUrl)
        {
            if (s_log.IsDebugEnabled)
            {
                s_log.Debug("getting page type for " + pageUrl);
            }

            string rootedVPath = WebUtils.CombineVirtualPaths(VirtualEnvironment.CurrentExecutionFilePath, pageUrl);

            if (s_log.IsDebugEnabled)
            {
                s_log.Debug("page vpath is " + rootedVPath);
            }

            Type pageType = VirtualEnvironment.GetCompiledType(rootedVPath);

            if (s_log.IsDebugEnabled)
            {
                s_log.Debug(string.Format("got page type '{0}' for vpath '{1}'", pageType.FullName, rootedVPath));
            }
            return(pageType);
        }
コード例 #21
0
        public VirtualEnvironmentMock(string currentVirtualFilePath, string pathInfo, string queryText, string applicationVirtualPath, bool autoInitialize)
        {
            _currentVirtualFilePath   = currentVirtualFilePath;
            _currentExecutionFilePath = currentVirtualFilePath;
            _pathInfo = (pathInfo == null || pathInfo.Length == 0) ? "" : "/" + pathInfo.TrimStart('/'); // prevent null string and ensure '/' prefixed
            _query    = new HttpValueCollection(queryText);
            _applicationVirtualPath = "/" + ("" + applicationVirtualPath).Trim('/');
            if (!_applicationVirtualPath.EndsWith("/"))
            {
                _applicationVirtualPath = _applicationVirtualPath + "/";
            }

//            if (!_currentVirtualFilePath.StartsWith(_applicationVirtualPath))
//            {
//                throw new ArgumentException("currentVirtualFilePath must begin with applicationVirtualPath");
//            }

            _prevEnvironment = VirtualEnvironment.SetInstance(this);
            if (autoInitialize)
            {
                VirtualEnvironment.SetInitialized();
            }
        }
コード例 #22
0
    public void Restore(VirtualEnvironment virtualEnvironment, Room currentRoom, UserBody user, Vector2 scale, Vector2 translate)
    {
        Room v = currentRoom;

        float[] wallMovement = new float[4]; // Sign을 결정하는 역할만 함
        wallMovement[0] = (scale.y - 1) * v.Size.y / 2 + translate.y;
        wallMovement[1] = (1 - scale.x) * v.Size.x / 2 + translate.x;
        wallMovement[2] = (1 - scale.y) * v.Size.y / 2 + translate.y;
        wallMovement[3] = (scale.x - 1) * v.Size.x / 2 + translate.x;

        bool[] isWallMovable = CheckWallMovable(virtualEnvironment, currentRoom, user, wallMovement);

        //wall을 이동 시키는 로직 start
        for (int i = 0; i < 4; i++)
        {
            if (isWallMovable[i])
            {
                float translation = Mathf.Sign(wallMovement[i]) * DT * Time.deltaTime;
                virtualEnvironment.MoveWall(v, i, translation);
            }
        }
        // end
    }
コード例 #23
0
    private void FixedUpdate()
    {
        VirtualEnvironment virtualEnvironment = VE;
        Room     currentRoom = VE.CurrentRoom;
        UserBody user        = VE.userBody;

        // 알고리즘 시작
        Tuple <Vector2, Vector2> st = GetScaleTranlslate(currentRoom, realSpace);
        Vector2 scale = st.Item1, translate = st.Item2;

        if ((scale - Vector2.one).magnitude > 0.01f || (translate - Vector2.zero).magnitude > 0.01f) // 복원 연산
        {
            Debug.Log("Restore");
            Restore(virtualEnvironment, currentRoom, user, scale, translate);
        }
        else if (NeedAdjust(virtualEnvironment, currentRoom)) // 조정 연산
        {
            Debug.Log("Adjust");
            Adjust(virtualEnvironment, currentRoom, user);
        }
        else // 축소 연산
        {
            Debug.Log("Reduce");
            List <Room> neighborRooms = virtualEnvironment.GetConnectedRooms(currentRoom);
            foreach (var room in neighborRooms)
            {
                if (!room.IsInside(realSpace))
                {
                    Reduce(virtualEnvironment, room, currentRoom, realSpace);
                }
            }

            SwitchEnable();
        }
        // 알고리즘 끝
    }
コード例 #24
0
        private WorkloadAnalysisEnvironment Convert(VirtualEnvironment source)
        {
            WorkloadAnalysisEnvironment result = new WorkloadAnalysisEnvironment();

            result.ID = source.ID;
            if (source.VirtualEnvironmentPossibleHPartitionings != null)
            {
                foreach (var item in source.VirtualEnvironmentPossibleHPartitionings)
                {
                    result.HPartitionings.Add(item.ID, Convert(item));
                }
            }
            if (source.VirtualEnvironmentPossibleIndices != null)
            {
                foreach (var item in source.VirtualEnvironmentPossibleIndices)
                {
                    result.Indices.Add(item.PossibleIndexID, new WorkloadAnalysisEnvironmentIndex()
                    {
                        ID = item.PossibleIndexID, ImprovementRatio = item.ImprovementRatio
                    });
                }
            }
            return(result);
        }
コード例 #25
0
    // Start is called before the first frame update
    public virtual void Start()
    {
        foreach (Transform child in transform)
        {
            Transform2D tf = child.GetComponent <Transform2D>();
            if (tf != null)
            {
                tf.Initializing();
            }

            if (tf is VirtualEnvironment)
            {
                virtualEnvironment = tf as VirtualEnvironment;
            }
            else if (tf is User)
            {
                user = tf as User;
            }
            else if (tf is RealSpace)
            {
                realSpace = tf as RealSpace;
            }
        }
    }
コード例 #26
0
 private void Start()
 {
     virtualEnvironment = GetComponent <VirtualEnvironment>();
     StartCoroutine(ApplyGain());
 }
コード例 #27
0
 /// <summary>
 /// Creates the raw handler instance without any exception handling
 /// </summary>
 /// <param name="pageUrl"></param>
 /// <returns></returns>
 internal static IHttpHandler CreateHandler(string pageUrl)
 {
     return(VirtualEnvironment.CreateInstanceFromVirtualPath(pageUrl, typeof(IHttpHandler)) as IHttpHandler);
 }
コード例 #28
0
ファイル: MapPathTest.cs プロジェクト: van800/OsTestFramework
 public void Test()
 {
     var vm = new VirtualEnvironment("XPx64W");
       vm.CopyFileFromHostToGuest(@"C:\1.txt", @"C:\Temp\1.txt", CopyMethod.network);
       Thread.Sleep(TimeSpan.FromSeconds(2400));
 }
コード例 #29
0
ファイル: Select.cs プロジェクト: taiab/nledger
        /// <summary>
        /// Ported from value_t select_command(call_scope_t& args)
        /// </summary>
        public static Value SelectCommand(CallScope args)
        {
            string text = "select " + CallScope.JoinArgs(args);

            if (String.IsNullOrEmpty(text))
            {
                throw new LogicError(LogicError.ErrorMessageUsageSelectText);
            }

            Report report = args.FindScope <Report>();

            // Our first step is to divide the select statement into its principal
            // parts:
            //
            //   SELECT <VALEXPR-LIST>
            //   FROM <NAME>
            //   WHERE <VALEXPR>
            //   DISPLAY <VALEXPR>
            //   COLLECT <VALEXPR>
            //   GROUP BY <VALEXPR>
            //   STYLE <NAME>

            Mask selectRe = new Mask(SelectRe);

            Mask fromAccountsRe = new Mask(FromAccountsRe);
            bool accountsReport = fromAccountsRe.Match(text);

            ExprOp        reportFunctor = null;
            StringBuilder formatter     = new StringBuilder();

            foreach (var match in selectRe.Matches(text))
            {
                string keyword = match.Groups[1].Value;
                string arg     = match.Groups[2].Value;

                Logger.Current.Debug("select.parse", () => String.Format("keyword: {0}", keyword));
                Logger.Current.Debug("select.parse", () => String.Format("arg: {0}", arg));

                if (keyword == "select")
                {
                    Expr   argsExpr = new Expr(arg);
                    Value  columns  = ExprOp.SplitConsExpr(argsExpr.Op);
                    bool   first    = true;
                    string thusFar  = String.Empty;

                    int cols = 0;

                    if (report.ColumnsHandler.Handled)
                    {
                        cols = Int32.Parse(report.ColumnsHandler.Value);
                    }
                    else
                    {
                        string columnsEnv = VirtualEnvironment.GetEnvironmentVariable("COLUMNS");
                        if (!Int32.TryParse(columnsEnv, out cols))
                        {
                            cols = VirtualConsole.WindowWidth;
                            if (cols == 0)
                            {
                                cols = 80;
                            }
                        }
                    }

                    int dateWidth = report.DateWidthHandler.Handled ? Int32.Parse(report.DateWidthHandler.Str()) :
                                    Times.TimesCommon.Current.FormatDate(Times.TimesCommon.Current.CurrentDate, Times.FormatTypeEnum.FMT_PRINTED).Length;
                    int payeeWidth = report.PayeeWidthHandler.Handled ? Int32.Parse(report.PayeeWidthHandler.Str()) :
                                     (int)(((double)cols) * 0.263157);
                    int accountWidth = report.AccountWidthHandler.Handled ? Int32.Parse(report.AccountWidthHandler.Str()) :
                                       (int)(((double)cols) * 0.302631);
                    int amountWidth = report.AmountWidthHandler.Handled ? Int32.Parse(report.AmountWidthHandler.Str()) :
                                      (int)(((double)cols) * 0.157894);
                    int totalWidth = report.TotalWidthHandler.Handled ? Int32.Parse(report.TotalWidthHandler.Str()) :
                                     amountWidth;
                    int metaWidth = report.MetaWidthHandler.Handled ? Int32.Parse(report.MetaWidthHandler.Str()) :
                                    10;

                    bool sawPayee   = false;
                    bool sawAccount = false;

                    int colsNeeded = 0;
                    foreach (Value column in columns.AsSequence)
                    {
                        string ident = null;
                        if (GetPrincipalIdentifiers(Expr.AsExpr(column), ref ident))
                        {
                            if (ident == "date" || ident == "aux_date")
                            {
                                colsNeeded += dateWidth + 1;
                            }
                            else if (ident == "payee")
                            {
                                colsNeeded += payeeWidth + 1;
                                sawPayee    = true;
                            }
                            else if (ident == "account")
                            {
                                colsNeeded += accountWidth + 1;
                                sawAccount  = true;
                            }
                            else if (ident == "amount")
                            {
                                colsNeeded += amountWidth + 1;
                            }
                            else if (ident == "total")
                            {
                                colsNeeded += totalWidth + 1;
                            }
                            else
                            {
                                colsNeeded += metaWidth + 1;
                            }
                        }
                    }

                    while ((sawAccount || sawPayee) && colsNeeded < cols)
                    {
                        if (sawAccount && colsNeeded < cols)
                        {
                            ++accountWidth;
                            ++colsNeeded;
                            if (colsNeeded < cols)
                            {
                                ++accountWidth;
                                ++colsNeeded;
                            }
                        }
                        if (sawPayee && colsNeeded < cols)
                        {
                            ++payeeWidth;
                            ++colsNeeded;
                        }
                    }

                    while ((sawAccount || sawPayee) && colsNeeded > cols &&
                           accountWidth > 5 && payeeWidth > 5)
                    {
                        Logger.Current.Debug("auto.columns", () => "adjusting account down");
                        if (sawAccount && colsNeeded > cols)
                        {
                            --accountWidth;
                            --colsNeeded;
                            if (colsNeeded > cols)
                            {
                                --accountWidth;
                                --colsNeeded;
                            }
                        }
                        if (sawPayee && colsNeeded > cols)
                        {
                            --payeeWidth;
                            --colsNeeded;
                        }
                        Logger.Current.Debug("auto.columns", () => String.Format("account_width now = {0}", accountWidth));
                    }

                    if (!report.DateWidthHandler.Handled)
                    {
                        report.DateWidthHandler.Value = dateWidth.ToString();
                    }
                    if (!report.PayeeWidthHandler.Handled)
                    {
                        report.PayeeWidthHandler.Value = payeeWidth.ToString();
                    }
                    if (!report.AccountWidthHandler.Handled)
                    {
                        report.AccountWidthHandler.Value = accountWidth.ToString();
                    }
                    if (!report.AmountWidthHandler.Handled)
                    {
                        report.AmountWidthHandler.Value = amountWidth.ToString();
                    }
                    if (!report.TotalWidthHandler.Handled)
                    {
                        report.TotalWidthHandler.Value = totalWidth.ToString();
                    }

                    foreach (Value column in columns.AsSequence)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            formatter.Append(" ");
                        }

                        formatter.Append("%(");

                        string ident = null;
                        if (GetPrincipalIdentifiers(Expr.AsExpr(column), ref ident, true))
                        {
                            if (ident == "date" || ident == "aux_date")
                            {
                                formatter.Append("ansify_if(");
                                formatter.Append("ansify_if(justify(format_date(");

                                PrintColumn(column, formatter);

                                formatter.Append("), int(date_width)),");
                                formatter.Append("green if color and date > today),");
                                formatter.Append("bold if should_bold)");

                                if (!String.IsNullOrEmpty(thusFar))
                                {
                                    thusFar += " + ";
                                }
                                thusFar += "int(date_width) + 1";
                            }
                            else if (ident == "payee")
                            {
                                formatter.Append("ansify_if(");
                                formatter.Append("ansify_if(justify(truncated(");

                                PrintColumn(column, formatter);

                                formatter.Append(", int(payee_width)), int(payee_width)),");
                                formatter.Append("bold if color and !cleared and actual),");
                                formatter.Append("bold if should_bold)");

                                if (!String.IsNullOrEmpty(thusFar))
                                {
                                    thusFar += " + ";
                                }
                                thusFar += "int(payee_width) + 1";
                            }
                            else if (ident == "account")
                            {
                                formatter.Append("ansify_if(");

                                if (accountsReport)
                                {
                                    formatter.Append("ansify_if(");
                                    formatter.Append("partial_account(options.flat), blue if color),");
                                }
                                else
                                {
                                    formatter.Append("justify(truncated(");
                                    PrintColumn(column, formatter);
                                    formatter.Append(", int(account_width), int(abbrev_len)),");
                                    formatter.Append("int(account_width), -1, ");
                                    formatter.Append("false, color),");

                                    if (!String.IsNullOrEmpty(thusFar))
                                    {
                                        thusFar += " + ";
                                    }
                                    thusFar += "int(account_width) + 1";
                                }

                                formatter.Append(" bold if should_bold)");
                            }
                            else if (ident == "amount" || ident == "total")
                            {
                                formatter.Append("ansify_if(");
                                formatter.Append("justify(scrub(");

                                PrintColumn(column, formatter);

                                formatter.Append("), ");

                                if (ident == "amount")
                                {
                                    formatter.Append("int(amount_width),");
                                }
                                else
                                {
                                    formatter.Append("int(total_width),");
                                }

                                if (!String.IsNullOrEmpty(thusFar))
                                {
                                    thusFar += " + ";
                                }

                                if (ident == "amount")
                                {
                                    thusFar += "int(amount_width)";
                                }
                                else
                                {
                                    thusFar += "int(total_width)";
                                }

                                if (String.IsNullOrEmpty(thusFar))
                                {
                                    formatter.Append("-1");
                                }
                                else
                                {
                                    formatter.Append(thusFar);
                                }

                                formatter.Append(", true, color),");
                                formatter.Append(" bold if should_bold)");

                                thusFar += " + 1";
                            }
                            else
                            {
                                formatter.Append("ansify_if(");
                                formatter.Append("justify(truncated(");

                                PrintColumn(column, formatter);

                                formatter.Append(", int(meta_width or 10)), int(meta_width) or 10),");
                                formatter.Append("bold if should_bold)");

                                if (!String.IsNullOrEmpty(thusFar))
                                {
                                    thusFar += " + ";
                                }
                                thusFar += "(int(meta_width) or 10) + 1";
                            }
                        }
                        formatter.Append(")");
                    }
                    formatter.AppendLine();
                    Logger.Current.Debug("select.parse", () => String.Format("formatter: {0}", formatter.ToString()));
                }
                else if (keyword == "from")
                {
                    if (arg == "xacts" || arg == "txns" || arg == "transactions")
                    {
                        var reporter = new Reporter <Post, PostHandler>(new PrintXacts(report, report.RawHandler.Handled), report, "#select", report.PostsReport);
                        reportFunctor = ExprOp.WrapFunctor(scope => reporter.Handle((CallScope)scope));
                    }
                    else if (arg == "posts" || arg == "postings")
                    {
                        var reporter = new Reporter <Post, PostHandler>(new FormatPosts(report, formatter.ToString()), report, "#select", report.PostsReport);
                        reportFunctor = ExprOp.WrapFunctor(scope => reporter.Handle((CallScope)scope));
                    }
                    else if (arg == "accounts")
                    {
                        var reporter = new Reporter <Account, AccountHandler>(new FormatAccounts(report, formatter.ToString()), report, "#select", report.AccountsReport);
                        reportFunctor = ExprOp.WrapFunctor(scope => reporter.Handle((CallScope)scope));
                    }
                    else if (arg == "commodities")
                    {
                        var reporter = new Reporter <Post, PostHandler>(new FormatPosts(report, formatter.ToString()), report, "#select", report.CommoditiesReport);
                        reportFunctor = ExprOp.WrapFunctor(scope => reporter.Handle((CallScope)scope));
                    }
                }
                else if (keyword == "where")
                {
                    report.LimitHandler.On("#select", arg);
                }
                else if (keyword == "display")
                {
                    report.DisplayHandler.On("#select", arg);
                }
                else if (keyword == "collect")
                {
                    report.AmountHandler.On("#select", arg);
                }
                else if (keyword == "group by")
                {
                    report.GroupByHandler.On("#select", arg);
                }
                else if (keyword == "style")
                {
                    if (arg == "csv")
                    {
                    }
                    else if (arg == "xml")
                    {
                    }
                    else if (arg == "json")
                    {
                    }
                    else if (arg == "emacs")
                    {
                    }
                    else if (arg == "org")
                    {
                    }
                }
            }

            if (reportFunctor == null)
            {
                var reporter = new Reporter <Post, PostHandler>(new FormatPosts(report, formatter.ToString()), report, "#select", report.PostsReport);
                reportFunctor = ExprOp.WrapFunctor(scope => reporter.Handle((CallScope)scope));
            }

            CallScope callArgs = new CallScope(report);

            return(reportFunctor.AsFunction(callArgs));
        }
コード例 #30
0
 public void Dispose()
 {
     VirtualEnvironment.SetInstance(_prevEnvironment);
 }
コード例 #31
0
        public int Execute(string argString)
        {
            using (MainApplicationContext.AcquireCurrentThread())
            {
                var envp = VirtualEnvironment.GetEnvironmentVariables();
                var args = CommandLine.PreprocessSingleQuotes(argString);

                int status = 1;

                // The very first thing we do is handle some very special command-line
                // options, since they affect how the environment is setup:
                //
                //   --verify            ; turns on memory tracing
                //   --verbose           ; turns on logging
                //   --debug CATEGORY    ; turns on debug logging
                //   --trace LEVEL       ; turns on trace logging
                //   --memory            ; turns on memory usage tracing
                //   --init-file         ; directs ledger to use a different init file
                GlobalScope.HandleDebugOptions(args);
                // initialize_memory_tracing - [DM] #memory-tracing
                Logger.Current.Info(() => LedgerStarting);
                // ::textdomain("ledger"); - [DM] #localization
                GlobalScope globalScope = null;
                try
                {
                    // Create the session object, which maintains nearly all state relating to
                    // this invocation of Ledger; and register all known journal parsers.
                    globalScope = new GlobalScope(envp);
                    globalScope.Session.FlushOnNextDataFile = true;

                    // Look for options and a command verb in the command-line arguments
                    BindScope boundScope = new BindScope(globalScope, globalScope.Report);
                    args = globalScope.ReadCommandArguments(boundScope, args);

                    if (globalScope.ScriptHandler.Handled)
                    {
                        // Ledger is being invoked as a script command interpreter
                        globalScope.Session.ReadJournalFiles();

                        status = 0;

                        using (StreamReader sr = FileSystem.GetStreamReader(globalScope.ScriptHandler.Str()))
                        {
                            while (status == 0 && !sr.EndOfStream)
                            {
                                string line = sr.ReadLine().Trim();
                                if (!line.StartsWith("#"))
                                {
                                    status = globalScope.ExecuteCommandWrapper(StringExtensions.SplitArguments(line), true);
                                }
                            }
                        }
                    }
                    else if (args.Any())
                    {
                        // User has invoke a verb at the interactive command-line
                        status = globalScope.ExecuteCommandWrapper(args, false);
                    }
                    else
                    {
                        // Commence the REPL by displaying the current Ledger version
                        VirtualConsole.Output.WriteLine(globalScope.ShowVersionInfo());

                        globalScope.Session.ReadJournalFiles();

                        bool exitLoop = false;

                        VirtualConsole.ReadLineName = "Ledger";

                        string p;
                        while ((p = VirtualConsole.ReadLine(globalScope.PromptString())) != null)
                        {
                            string expansion = null;
                            int    result    = VirtualConsole.HistoryExpand(p.Trim(), ref expansion);

                            if (result < 0 || result == 2)
                            {
                                throw new LogicError(String.Format(LogicError.ErrorMessageFailedToExpandHistoryReference, p));
                            }
                            else if (expansion != null)
                            {
                                VirtualConsole.AddHistory(expansion);
                            }

                            CancellationManager.CheckForSignal();

                            if (!String.IsNullOrWhiteSpace(p) && p != "#")
                            {
                                if (String.Compare(p, "quit", true) == 0)
                                {
                                    exitLoop = true;
                                }
                                else
                                {
                                    globalScope.ExecuteCommandWrapper(StringExtensions.SplitArguments(p), true);
                                }
                            }

                            if (exitLoop)
                            {
                                break;
                            }
                        }
                        status = 0;    // report success
                    }
                }
                catch (CountError errors)
                {
                    // used for a "quick" exit, and is used only if help text (such as
                    // --help) was displayed
                    status = errors.Count;
                }
                catch (Exception err)
                {
                    if (globalScope != null)
                    {
                        globalScope.ReportError(err);
                    }
                    else
                    {
                        VirtualConsole.Error.WriteLine(String.Format(ExceptionDuringInitialization, err.Message));
                    }
                }

                if (globalScope != null)
                {
                    globalScope.QuickClose();
                    globalScope.Dispose();              // {DM] It is the most appropriate place to call Dispose for the global scope.
                }
                Logger.Current.Info(() => LedgerEnded); // let global_scope leak!

                // Return the final status to the operating system, either 1 for error or 0
                // for a successful completion.
                return(status);
            }
        }