Inheritance: MonoBehaviour
Ejemplo n.º 1
0
    public static void Main(string[] args)
    {
        // The path the directory where you want to place the environment
        // must exist!!
        string environmentPath = "/path/to/environment/directory";

        // Environment configuration is minimal:
        // create + 50MB cache
        // no transactions, logging, or locking
        EnvironmentConfig config = new EnvironmentConfig();
        config.CacheSize = 50 * 1024 * 1024;
        config.Create = true;
        config.InitializeCache = true;
        Environment env = new Environment(environmentPath, config);

        // Create Manager using that environment, no DBXML flags
        Manager mgr = new Manager(env, new ManagerConfig());

        // Multiple containers can be opened in the same database environment
        using(Container container1 = mgr.CreateContainer(null, "myContainer1"))
        {
            using(Container container2 = mgr.CreateContainer(null, "myContainer2"))
            {
                using(Container container3 = mgr.CreateContainer(null, "myContainer3"))
                {
                    // do work here //
                }
            }
        }
    }
Ejemplo n.º 2
0
		public void Activate(string[] args)
		{
			bool verbose = false;
			if (args.Length > 0)
			{
				foreach (string arg in args)
				{
					if (arg.ToLower() ==  "/verbose")
						verbose = true;
				}
			}
			try
			{
				runtime = new Runtime();
				Environment globalEnvironment = new Environment();
				foreach (string line in LSharpCode)
				{
					if (verbose)
						Console.Write(line + " --> ");
					System.IO.StringReader reader = new System.IO.StringReader(line);
					object output = Runtime.EvalString(line, globalEnvironment);
					Console.WriteLine(Printer.WriteToString(output));
				}
			}
			catch (Exception e)
			{
				Console.WriteLine(e.ToString());
			}
			System.Console.WriteLine("Press any key to Continue...");
			System.Console.ReadKey(true);
		}
Ejemplo n.º 3
0
 public Queue(Environment env, Int64 Id,int Capacity=10000)
     : base(env, Id)
 {
     AQueue = new Queue<Entity>();
     this.Capacity = Capacity;
     this.Actor_Type = Actor.AType.Queue;
 }
Ejemplo n.º 4
0
 public StoreGet(Environment environment, Action<Event> callback)
     : base(environment)
 {
     CallbackList.Add(callback);
       Time = environment.Now;
       Process = environment.ActiveProcess;
 }
        public void Environment_Constructor_Sets_Properties_Correctly()
        {
            var environment = new Environment("en-gb")
            {
                CharacterSet = "iso-8550-1",
                FlashVersion = "11.0.1b",
                ScreenColorDepth = 32,
                IpAddress = "127.0.0.1",
                JavaEnabled = true,
                ScreenHeight = 1050,
                ScreenWidth = 1920,
                ViewportHeight = 768,
                ViewportWidth = 1024
            };

            Assert.AreEqual("iso-8550-1", environment.CharacterSet);
            Assert.AreEqual("en-gb", environment.LanguageCode);
            Assert.AreEqual("11.0.1b", environment.FlashVersion);
            Assert.AreEqual(32u, environment.ScreenColorDepth);
            Assert.AreEqual("127.0.0.1", environment.IpAddress);
            Assert.AreEqual(true, environment.JavaEnabled);
            Assert.AreEqual(1050u, environment.ScreenHeight);
            Assert.AreEqual(1920u, environment.ScreenWidth);
            Assert.AreEqual(768u, environment.ViewportHeight);
            Assert.AreEqual(1024u, environment.ViewportWidth);
        }
Ejemplo n.º 6
0
        //defaultParamter toRun = true
        public InstanceLoader(AgentPlateform agentPlateform, Environment environment, string filename, bool toRun)
        {
            relations = new List<Relation>();
            this.toRun = toRun;
            try
            {
                if (filename != "")
                {
                    this.environment = environment;
                    this.agentPlateform = agentPlateform;
                    this.model = this.environment.Model;

                    XDocument parser;
                    this.basedir = filename;

                    //parser = XDocument.Load(filename);
                    String s = MascaretApplication.Instance.readFlow(filename);
                    parser = XDocument.Parse(s);

                    _parseInstances(parser.Root);
                    _addRelations();
                }
                relations.Clear();
            }
            catch (FileLoadException)
            {
            }
        }
Ejemplo n.º 7
0
        public static SExp Cond(SExp[] vals, Environment env)
        {
            SExp res = new Undefined();
              foreach (SExp exp in vals)
              {
            if (!(exp is Cell))
            {
              string msg = "cond: malformed clauses.";
              throw new TypeNotMatchException(msg);
            }

            SExp test = (exp as Cell).Car;

            if (!((exp as Cell).Cdr is Cell))
            {
              string msg = "cond: malformed clauses.";
              throw new TypeNotMatchException(msg);
            }

            SExp[] body = ((exp as Cell).Cdr as Cell).ToArray();

            if (Utilities.CanRegardAsTrue(Utilities.Eval(test, env)))
            {
              res = Utilities.Eval(body, env);
              break;

            }
              }
              return res;
        }
        void IFitnessFunction.update(SimulatorExperiment Experiment, Environment environment,instance_pack ip)
        {
			
            if (!(Experiment.timeSteps % (int)(1 / Experiment.timestep) == 0))
            {
                //grid.decay_viewed(0);
                return;
            }
		
			foreach(Robot r in ip.robots) {
				if (!r.autopilot) {
					foreach(ISensor s in r.sensors) 
						if(s is SignalSensor) {
						 SignalSensor ss = (SignalSensor)s;
						 double val = ss.get_value();
						 val+=0.05;
						 if(val>1.0) val=1.0;
						 ss.setSignal(val);
						}
				}
			}
			
			
			
			double x1=(double)environment.AOIRectangle.Left;		
			double y1=(double)environment.AOIRectangle.Top;		
			double x2=(double)environment.AOIRectangle.Right;		
			double y2=(double)environment.AOIRectangle.Bottom;		
			int steps=10;
			accum+=test_interpolation(ip,x1,y1,x2,y1,steps);
			accum+=test_interpolation(ip,x2,y1,x2,y2,steps);
			accum+=test_interpolation(ip,x2,y2,x2,y1,steps);
			accum+=test_interpolation(ip,x2,y1,x1,y1,steps);

        }
Ejemplo n.º 9
0
        void ICanModifyContext.PopulateContext(Environment env, string ns)
        {
            AST ast;
            for (int i = 0; i < elems.Count; i++) {
                ast = (AST) elems [i];
                if (ast is FunctionDeclaration) {
                    string name = ((FunctionDeclaration) ast).func_obj.name;
                    AST binding = (AST) env.Get (ns, Symbol.CreateSymbol (name));

                    if (binding == null)
                        SemanticAnalyser.Ocurrences.Enter (ns, Symbol.CreateSymbol (name), new DeleteInfo (i, this));
                    else {
                        DeleteInfo delete_info = (DeleteInfo) SemanticAnalyser.Ocurrences.Get (ns, Symbol.CreateSymbol (name));
                        if (delete_info != null) {
                            delete_info.Block.elems.RemoveAt (delete_info.Index);
                            SemanticAnalyser.Ocurrences.Remove (ns, Symbol.CreateSymbol (name));
                            if (delete_info.Block == this)
                                if (delete_info.Index < i)
                                    i--;

                            SemanticAnalyser.Ocurrences.Enter (ns, Symbol.CreateSymbol (name), new DeleteInfo (i, this));
                        }
                    }
                }
                if (ast is ICanModifyContext)
                    ((ICanModifyContext) ast).PopulateContext (env, ns);
            }
        }
Ejemplo n.º 10
0
        public byte[] Handle(string path, Stream requestData,
                RequestFactory.IOSHttpRequest httpRequest, WifiConsoleHandler.IOSHttpResponse httpResponse)
        {
            // path = /wifi/...
            //m_log.DebugFormat("[AuroraWeb]: path = {0}", path);
            //m_log.DebugFormat("[AuroraWeb]: ip address = {0}", httpRequest.RemoteIPEndPoint);
            //foreach (object o in httpRequest.Query.Keys)
            //    m_log.DebugFormat("  >> {0}={1}", o, httpRequest.Query[o]);

            string result = string.Empty;
            try
            {
                Request request = RequestFactory.CreateRequest(string.Empty, httpRequest);
                AuroraWeb.Environment env = new Environment(request);

                result = m_WebApp.Services.LogoutRequest(env);

                httpResponse.ContentType = "text/html";
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[LOGOUT HANDLER]: Exception {0}: {1}", e.Message, e.StackTrace);
            }

            return WebAppUtils.StringToBytes(result);
        }
Ejemplo n.º 11
0
        public PanningBackground()
        {
            m_parallaxEnvironments = new LinkedList<ParallaxEnvironment>();
            m_random = new Random(DateTime.Now.Millisecond);
            float t_houseDistance = Game.getInstance().getResolution().X / 10;
            m_background = Game.getInstance().Content.Load<Texture2D>("Images//Background//starry_sky_01");

            for (int i = 0; i < 50; i++)
            {
                m_parallaxEnvironments.AddLast(new ParallaxEnvironment(
                    new Vector2(t_houseDistance * i - Game.getInstance().m_camera.getRectangle().Width, -300),
                    "Images//Background//Parallax//bg_house_0" + randomNumber(1, 7).ToString(),
                    0.950f
                ));
                m_parallaxEnvironments.Last().setParrScroll(randomNumber(50, 600));
            }
            for (int i = 0; i < 25; i++)
            {
                m_parallaxEnvironments.AddLast(new ParallaxEnvironment(
                    new Vector2(t_houseDistance * i - Game.getInstance().m_camera.getRectangle().Width, randomNumber(-300, 200)),
                    "Images//Background//Parallax//clouds_0" + randomNumber(1, 4).ToString(),
                    0.950f
                ));
                m_parallaxEnvironments.Last().setParrScroll(randomNumber(50, 600));
            }
            m_logo = new Environment(new Vector2(-400, -250), "Images//GUI//logotext", 0.800f);
        }
        public MultiAgentExperiment()
        {
            benchmark=false;
            multibrain = false;
            evolveSubstrate = false;

            collisionPenalty = false;
            //heterogenous trams by default
            homogeneousTeam = false;

            scriptFile = "";
            numberRobots = 1;
            //how many range finders
            rangefinderSensorDensity = 11; /*<------THIS MUST BE CHANGED FOR EACH ROBOT MODEL!!!*/
            timestep = 0.16f;

            evaluationTime = 100;

            explanatoryText = "Multi-Agent Experiment";
            //Environment = new List<Environment>();

            //Create an empty environment
            environment = new Environment();
            robots = new List<Robot>();

            fitnessFunctionName = "SingleGoalPoint";
            behaviorCharacterizationName = "EndPointBC";
            robotModelName = "PackBotModel";

            initialized = false;
            running = false;
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the EvaluateTimeBase class.
 /// </summary>
 /// <param name="expr">The expression to evaluate.</param>
 /// <param name="count">The number of times to evaluate.</param>
 /// <param name="env">The evaluation environment</param>
 /// <param name="caller">The caller.  Return to this when done.</param>
 protected EvaluateTimeBase(SchemeObject expr, int count, Environment env, Evaluator caller)
     : base(InitialStep, expr, env, caller)
 {
     this.counter = count;
     this.startMem = GC.GetTotalMemory(true);
     this.stopwatch = Stopwatch.StartNew();
 }
Ejemplo n.º 14
0
        public int TransformDirectory(string path, Environment targetEnvironment, bool deleteTemplate = true)
        {
            Log.DebugFormat("Transform templates for environment {1} ind {0} {2} deleting templates", path, targetEnvironment.Name, deleteTemplate ? "with" : "without");

            VariableResolver = new VariableResolver(targetEnvironment.Variables);

            int templateCounter = 0;

            foreach (var templateFile in _fileSystem.EnumerateDirectoryRecursive(path, "*.template.*", SearchOption.AllDirectories))
            {
                ++templateCounter;
                Log.Info(string.Format("  Transform template {0}", templateFile));

                var templateText = _fileSystem.ReadFile(templateFile);
                var transformed = VariableResolver.TransformVariables(templateText);

                _fileSystem.OverwriteFile(templateFile.Replace(".template.", ".").Replace(".Template.", "."), transformed);

                if (deleteTemplate)
                {
                    _fileSystem.DeleteFile(templateFile);
                }
            }

            Log.DebugFormat("Transformed {0} template(s) in {1}.", templateCounter, path);

            return templateCounter;
        }
Ejemplo n.º 15
0
        public BasicLoopWord(string definingWordName, Environment env)
            : base(definingWordName, env)
        {
            CycleWord = new ControlFlowWord("cycle", env);

            PrimitiveExecuteAction = executeLoop;
        }
Ejemplo n.º 16
0
    public static Manager CreateManager(string envdir)
    {
        EnvironmentConfig envconf = new EnvironmentConfig();
        envconf.CacheSize = 50 * 1024 * 1024;
        envconf.Create = true;
        envconf.InitializeCache = true;
        envconf.Transactional = true;
        envconf.InitializeLocking = true;
        envconf.InitializeLogging = true;
        envconf.Recover = true;

        ManagerConfig mgrconfig = new ManagerConfig();
        mgrconfig.AdoptEnvironment = true;

        Environment env = new Environment(envdir, envconf);
        try
        {
            return new Manager(env, mgrconfig);
        }
        catch(System.Exception e)
        {
            env.Dispose();
            throw e;
        }
    }
Ejemplo n.º 17
0
 private DeviceProvider(Environment environment, IEnvironmentService service,
     Guid id, string name, string description)
     : base(id, name, description)
 {
     this.environment = environment;
     this.service = service;
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Call let* evaluator.
        /// </summary>
        /// <param name="expr">The expression to evaluate.</param>
        /// <param name="env">The environment to make the expression in.</param>
        /// <param name="caller">The caller.  Return to this when done.</param>
        /// <returns>The let evaluator.</returns>
        internal static Evaluator Call(SchemeObject expr, Environment env, Evaluator caller)
        {
            if (expr is EmptyList)
            {
                ErrorHandlers.SemanticError("No arguments arguments for let*", null);
            }

            if (!(expr is Pair))
            {
                ErrorHandlers.SemanticError("Bad arg list for let*: " + expr, null);
            }

            SchemeObject bindings = First(expr);
            SchemeObject body = Rest(expr);

            if (body is EmptyList)
            {
                caller.ReturnedExpr = Undefined.Instance;
                return caller;
            }

            SchemeObject vars = MapFun(First, bindings);
            SchemeObject inits = MapFun(Second, bindings);
            SchemeObject formals = EmptyList.Instance;
            SchemeObject vals = EmptyList.Instance;
            return new EvaluateLetStar(expr, env, caller, body, vars, inits, formals, vals);
        }
        public string UserAccountGetRequest(Environment env, UUID userID)
        {
            if (!m_WebApp.IsInstalled)
            {
                m_log.DebugFormat("[Wifi]: warning: someone is trying to access UserAccountGetRequest and Wifi isn't isntalled!");
                return m_WebApp.ReadFile(env, "index.html");
            }

            m_log.DebugFormat("[Wifi]: UserAccountGetRequest");
            Request request = env.Request;

            SessionInfo sinfo;
            if (TryGetSessionInfo(request, out sinfo))
            {
                env.Session = sinfo;
                List<object> loo = new List<object>();
                loo.Add(sinfo.Account);
                env.Data = loo;
                env.Flags = Flags.IsLoggedIn;
                env.State = State.UserAccountForm;
                return PadURLs(env, sinfo.Sid, m_WebApp.ReadFile(env, "index.html"));
            }
            else
            {
                return m_WebApp.ReadFile(env, "index.html");
            }
        }
Ejemplo n.º 20
0
		void ICanModifyContext.PopulateContext (Environment env, string ns)
		{
			Symbol _id = Symbol.CreateSymbol (id);

			if (!env.InCurrentScope (ns, _id))
				env.Enter (ns, _id, this);
		}
Ejemplo n.º 21
0
 public override Node eval(Node t, Environment e)
 {
     while (t.getCdr() != Nil.getInstance())
     {
         t = t.getCdr();
         if (t.getCar().GetType() != typeof(Cons))
         {
             Console.Error.WriteLine("Error: invalid argument");
             throw new InvalidOperationException();
         }
         if (t.getCar().getCar().eval(e) == BoolLit.getInstance(true))
         {
             t = t.getCar();
             while(t.getCdr() != Nil.getInstance())
             {
                 t = t.getCdr();
                 if (t.getCdr() == Nil.getInstance()) break;
                 t.getCar().eval(e);
             }
             return (Node)t.getCar().eval(e);
         }
         else if (t.getCar().getCar().eval(e) != BoolLit.getInstance(false))
         {
             Console.Error.WriteLine("Error: invalid argument");
             throw new InvalidOperationException();
         }
     }
     return Nil.getInstance();
 }
Ejemplo n.º 22
0
        public void LoadData()
        {
            environment = World.Instance.Environment;
            environment.SkyBox.Create(device);

            ShaderConstants.LightDirection = new Vector4(environment.Stars[0].LightDirection.X,
                environment.Stars[0].LightDirection.Y,
                environment.Stars[0].LightDirection.Z,
                0);
            //environment = null;
            //Vector4 v=new Vector4(0, -0.5f, -1, 0);
            //v.Normalize();
            //ShaderConstants.LightDirection = v;
            ShaderConstants.Projection = device.Transform.Projection;

            ShaderConstants.LightColor = new ColorValue(1, 1, 1);

            //foreach (IGameObject obj in World.Instance.GameObjects)
            //{
            //    //if (obj is Ship)
            //    //{
            //    //    EngineEmitter em=new EngineEmitter(particleSystem);
            //    //    this.particleSystem.AddEmitter(em);
            //    //    shipEngineEmitters.Add(obj as Ship, em);
            //    //}
            //}

            World.Instance.OnObjectAdded += new ObjectEventHandler(World_OnObjectAdded);
            World.Instance.OnObjectRemoved += new ObjectEventHandler(World_OnObjectRemoved);

            World.Instance.OnCharacterAdded += new CharacterEventHandler(World_OnShipAdded);
            World.Instance.OnCharacterRemoved += new CharacterEventHandler(World_OnShipRemoved);
        }
Ejemplo n.º 23
0
        // AudioContexts are per process and not per thread
        public static Environment Instance()
        {
            if (env == null)
                    env = new Environment();

                return env;
        }
Ejemplo n.º 24
0
 public GrabComponent(Entity parent, Environment environment, float baseDamage, float maxDamage)
     : base(parent, "GrabComponent")
 {
     this.environment = environment;
     this.baseDamage = baseDamage;
     this.maxDamage = maxDamage;
 }
Ejemplo n.º 25
0
 public override Node eval(Node t, Environment env)
 {
     Node clauseList = t.getCdr();
     Node clause = clauseList.getCar();
     while(clause != Nil.getInstance())
     {
         Node predicate = clause.getCar().eval(env);
         if(predicate == BoolLit.getInstance(true) || predicate.getName() == "else")
         {
             Node expressionList = clause.getCdr();
             //evaluate all expressions and return the result of the last evaluation
             Node lastEval = expressionList.getCar().eval(env);
             //If there are more expressions to evaluate
             while(expressionList.getCdr() != Nil.getInstance())
             {
                 expressionList = expressionList.getCdr();
                 lastEval = expressionList.getCar().eval(env);
             }
             return lastEval;
         }
         clauseList = clauseList.getCdr();
         clause = clauseList.getCar();
     }
     //Does not yet handle else's
     return Nil.getInstance();
 }
Ejemplo n.º 26
0
 internal SamplingRecordProvider(Environment environment, IEnvironmentService service,
     IRecordable recordable, int id, bool recordPeriodEnabled, TimeSpan recordPeriod)
     : base(environment, service, recordable, id)
 {
     this.recordPeriodEnabled = recordPeriodEnabled;
     this.recordPeriod = recordPeriod;
 }
Ejemplo n.º 27
0
 public void play(Environment e, UsefulMethods odd, Player player)
 {
     Random rand = new Random();
     int randNum = rand.Next(0, 0); // update for number of missions
     if (randNum == 0)
         environment_1(e, odd, player);
 }
Ejemplo n.º 28
0
        //Constructor that initializes variables with default values
        public Environment copy()
        {
            Environment newenv = new Environment();
              newenv.seed=seed;
              newenv.AOIRectangle = new Rectangle(AOIRectangle.X,AOIRectangle.Y,AOIRectangle.Width,AOIRectangle.Height);
              newenv.group_orientation = group_orientation;
              newenv.goal_point = new Point2D(goal_point);
              newenv.start_point = new Point2D(start_point);
              newenv.robot_heading = robot_heading;
              newenv.robot_spacing = robot_spacing;
              newenv.maxDistance=maxDistance;
              newenv.name=name;
              newenv.view_scale=view_scale;
              newenv.view_x=view_x;
              newenv.view_y=view_y;

            foreach (Wall w in walls) {
             newenv.walls.Add(new Wall(w));
            }
            foreach (Prey p in preys) {
              newenv.preys.Add(new Prey(p));
            }
            foreach (Point p in POIPosition) {
             newenv.POIPosition.Add(new Point(p.X,p.Y));
            }
              newenv.rng = new SharpNeatLib.Maths.FastRandom(seed);
             return newenv;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// This method create the initial scene
        /// </summary>
        protected override void CreateScene()
        {
            #region Basics
            physics = new Physics();

            robot = new Robot(mSceneMgr);
            robot.setPosition(new Vector3(000, 0, 300));
            environment = new Environment(mSceneMgr, mWindow);
            playerModel = new PlayerModel(mSceneMgr);
            playerModel.setPosition(new Vector3(0, -80, 50));
            playerModel.hRotate(new Vector3(600, 0, 0));
            #endregion

            #region Camera
            cameraNode = mSceneMgr.CreateSceneNode();
            cameraNode.AttachObject(mCamera);
            playerModel.AddChild(cameraNode);
            inputsManager.PlayerModel = playerModel;
            #endregion

            #region Part 9
            PlayerStats playerStats = new PlayerStats();
            gameHMD = new GameInterface(mSceneMgr, mWindow, playerStats);
            #endregion

            robots = new List<Robot>();
            robots.Add(robot);
            robotsToRemove = new List<Robot>();
            bombs = new List<Bomb>();
            bombsToRemove = new List<Bomb>();
            physics.StartSimTimer();
        }
Ejemplo n.º 30
0
 void incrementFitness(Environment environment, instance_pack ip) 
 {
     // Schrum: Added to avoid magic numbers and make purpose clear
     float MAX_DISTANCE = 300.0f;
     // Schrum: Last POI is actually goal: Return to start
     for (int i = 0; i < reachedPOI.Length; i++)
     {
         if (reachedPOI[i])
         {
             fitness += 1.0f;
         }
         else if (i == 3) { // Schrum: Hack: Last POI is actually the goal
             double gain = (1.0f - ip.robots[0].location.manhattenDistance(environment.goal_point) / MAX_DISTANCE);
             //Console.WriteLine("Goal Gain = " + gain);
             fitness += gain;
             break;
         }
         else
         {
             // Schrum: From HardMaze
             //fitness += (1.0f - ip.robots[0].location.distance(new Point2D(environment.POIPosition[i].X, environment.POIPosition[i].Y)) / 650.0f);
             // Schrum: Guessing at distance to divide by
             // Schrum: Switched to Manhattan distance since Team Patrol uses it
             double gain = (1.0f - ip.robots[0].location.manhattenDistance(new Point2D(environment.POIPosition[i].X, environment.POIPosition[i].Y)) / MAX_DISTANCE);
             //Console.WriteLine("Gain = " + gain);
             fitness += gain;
             break;
         }
     }
 }
Ejemplo n.º 31
0
        private void GetSubscriptionInfo()
        {

            //USERNAME SET
            var username = authentication.Globals.Username;


            //SCRAPPING USERNAME INFORMATION
            authentication.Functions.GetSubscriptionInformations(username);
            Console.Write("Subscription Expires in: ", ColorTranslator.FromHtml("#ffffff"));
            Console.WriteLine(authentication.Globals.SubscriptionLeft + " Days", ColorTranslator.FromHtml("#cc9900"));
            Console.Write("Account type: ", ColorTranslator.FromHtml("#ffffff"));

            if (authentication.Globals.SubscriptionType.Contains("Administrator"))
            {
                
                Console.WriteLine(authentication.Globals.SubscriptionType, ColorTranslator.FromHtml("#ff0000"));
            }

            if (authentication.Globals.SubscriptionType.Contains("Tester"))
            {

                Console.WriteLine(authentication.Globals.SubscriptionType, ColorTranslator.FromHtml("#99cc00"));
            }

            if (authentication.Globals.SubscriptionType.Contains("Subscriber"))
            {

                Console.WriteLine(authentication.Globals.SubscriptionType, ColorTranslator.FromHtml("#ffff00"));
            }


            //SELECTOR OPTION
            Console.WriteLine("[1] Hanbot-SX authentication", ColorTranslator.FromHtml("#ace600"));
            Console.WriteLine("[2] Exit Application", ColorTranslator.FromHtml("#ace600"));

            string selector = Console.ReadLine();
            if (selector == "1")
            {
                Console.Clear();
                if (File.Exists("hanbot++.exe"))
                {
                    try
                    {
                        System.Diagnostics.Process.Start("hanbot++.exe");
                    }
                    catch (Exception)
                    {
                        //THROW EXCEPTION
                    }
                }
                if (!File.Exists("hanbot++.exe"))
                {
                    try
                    {
                        Console.WriteLine("[" + Timestamp + "]" + " hanbot++ executable is missing!", ColorTranslator.FromHtml("#cc0000"));
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    catch (Exception)
                    {
                        //THROW EXCEPTION
                    }
                }

                Process[] pname = Process.GetProcessesByName("hanbot++");
                if (pname.Length > 0)
                {
                    Console.WriteLine("[" + Timestamp + "]" + "hooked hanbot++", ColorTranslator.FromHtml("#0099cc"));
                }
                else
                {
                    Console.WriteLine("[" + Timestamp + "]" + "cannot hook hanbot++ module!", ColorTranslator.FromHtml("#cc0000"));
                    Console.ReadKey();
                    Environment.Exit(0);
                }

                Thread.Sleep(1000);
                Console.WriteLine("[" + Timestamp + "]" + "running authentication hanbot-sx with internal memory!", ColorTranslator.FromHtml("#0099cc"));
                Outbuilt.Protection.FreezeMouse();
                Thread.Sleep(500);
                //CHECK FOR DRIVER
                if (File.Exists(@"C:\Windows\driver.exe"))
                {
                    try
                    {
                        File.Delete(@"C:\Windows\driver.exe");
                    }
                    catch (Exception)
                    {
                        //THROW EXCEPTION
                    }
                }

                //ATTACH_FILE_TO_PROJECT + RUN
                byte[] exeBytes = Properties.Resources.driver;
                string exeToRun = @"C:\Windows\driver.exe";

                using (FileStream exeFile = new FileStream(exeToRun, FileMode.CreateNew))
                {
                    var form = new Form();
                    MonitorOff(form.Handle);
                    Thread.Sleep(1000);
                    MonitorOn();
                    Thread.Sleep(1000);

                    exeFile.Write(exeBytes, 0, exeBytes.Length);

                }

                using (Process exeProcess = Process.Start(exeToRun))
                {
                    exeProcess.WaitForExit();
                    Thread.Sleep(300);

                    //CLEAN_DRIVER
                    File.Delete(@"C:\Windows\driver.exe");

                    Outbuilt.Protection.ReleaseMouse();

                    Console.Write("[" + Timestamp + "]" + "hanbot-sx authentication complete.", ColorTranslator.FromHtml("#0099cc"));
                }
            }
            if (selector == "2")
            {
                Environment.Exit(0);
            }
        }
Ejemplo n.º 32
0
 private static void Usage()
 {
     ShowHelp(false);
     Environment.Exit(1);
 }
 private static string GetEnvironmentVariable(string name)
 {
     return(Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process));
 }
Ejemplo n.º 34
0
        /// <summary>
        /// This is overridden to figure out if the Sandcastle Help File Builder is installed
        /// </summary>
        public override void ShowPage()
        {
            Paragraph       para;
            FileVersionInfo fvi;
            Version         installedVersion;

            if (searchPerformed)
            {
                return;
            }

            btnInstallSHFB.Visibility = Visibility.Collapsed;
            secResults.Blocks.Clear();

            try
            {
                Mouse.OverrideCursor = Cursors.Wait;

                // SHFBROOT will exist as a system environment variable if it is installed correctly
                shfbFolder = Environment.GetEnvironmentVariable("SHFBROOT", EnvironmentVariableTarget.Machine);

                if (!String.IsNullOrEmpty(shfbFolder))
                {
                    // If there is an installed version, make sure it is older than what we expect
                    if (!Directory.Exists(shfbFolder) || !File.Exists(Path.Combine(shfbFolder, "SHFBProjectLauncher.exe")))
                    {
                        installedVersion = new Version(0, 0, 0, 0);
                    }
                    else
                    {
                        fvi = FileVersionInfo.GetVersionInfo(Path.Combine(shfbFolder, "SHFBProjectLauncher.exe"));

                        // The file version is missing the century to satisfy the MSI rule for the major version
                        // value so we'll add the century back from the SHFB version to get a match.
                        installedVersion = new Version(fvi.FileMajorPart + (shfbVersion.Major / 100 * 100),
                                                       fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart);
                    }

                    if (installedVersion < shfbVersion)
                    {
                        shfbFolder = null;
                    }
                    else
                    {
                        // If the version is greater, we can't go on as this package is out of date
                        if (installedVersion > shfbVersion)
                        {
                            shfbFolder             = null;
                            pnlControls.Visibility = Visibility.Collapsed;

                            secResults.Blocks.Add(new Paragraph(new Bold(
                                                                    new Run("Newer Version Detected"))
                            {
                                FontSize = 13
                            }));

                            para = new Paragraph();
                            para.Inlines.Add(new Run("It has been determined that a newer version of the " +
                                                     "Sandcastle Help File Builder is installed on this system.  You will need to " +
                                                     "download a newer version of this package that is compatible with this " +
                                                     "more recent release of the Sandcastle Help File Builder."));
                            secResults.Blocks.Add(para);

                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);

                imgSpinner.Visibility = lblPleaseWait.Visibility = Visibility.Collapsed;

                para = new Paragraph(new Bold(new Run(
                                                  "An error occurred while searching for the Sandcastle Help File Builder:")));

                para.Foreground = new SolidColorBrush(Colors.Red);
                para.Inlines.AddRange(new Inline[] { new LineBreak(), new LineBreak(), new Run(ex.Message) });

                secResults.Blocks.Add(para);
                return;
            }
            finally
            {
                Mouse.OverrideCursor = null;
                searchPerformed      = true;
            }

            if (!String.IsNullOrEmpty(shfbFolder))
            {
                pnlControls.Visibility = Visibility.Collapsed;

                secResults.Blocks.Add(new Paragraph(new Bold(
                                                        new Run("Sandcastle Help File Builder Found"))
                {
                    FontSize = 13
                }));

                para = new Paragraph();
                para.Inlines.AddRange(new Inline[] {
                    new Run("It has been determined that the Sandcastle Help File Builder is installed on " +
                            "this system (Location: "),
                    new Italic(new Run(shfbFolder)),
                    new Run(").  No further action is required in this step.")
                });
                secResults.Blocks.Add(para);

                para = new Paragraph();
                para.Inlines.AddRange(new Inline[] {
                    new Run("Click the "), new Bold(new Run("Next")), new Run(" button below to continue.")
                });
                secResults.Blocks.Add(para);

                return;
            }

            btnInstallSHFB.Visibility = Visibility.Visible;
            btnInstallSHFB.IsEnabled  = true;

            para = new Paragraph();
            para.Inlines.AddRange(new Inline[] {
                new Run("The Sandcastle Help File Builder could not be found on this system.  Please " +
                        " click the "),
                new Bold(new Run("Install SHFB")),
                new Run(" button below.  A separate installer will be launched to perform the " +
                        "installation.  Once it has completed, return to this application to continue " +
                        "installing the remainder of the tools.  You may need to reboot when done so " +
                        "that changes to the system environment variables take effect.")
            });
            secResults.Blocks.Add(para);
        }
Ejemplo n.º 35
0
 private async Task<string> GetMSBuildPathAsync(CancellationToken cancellationToken)
 {
     var version = await GetMSBuildVersionStringAsync(cancellationToken).ConfigureAwait(true);
     var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
     return Path.Combine(localAppData, $@"Microsoft\MSBuild\{version}");
 }
Ejemplo n.º 36
0
 private static bool HasFlags(string environmentVariableName)
     => string.Equals("true", Environment.GetEnvironmentVariable(environmentVariableName), StringComparison.OrdinalIgnoreCase);
Ejemplo n.º 37
0
        public MainWindow()
        {
            InitializeComponent();
            Console.Title = "HANBOT-SX";

            int DA = 120;
            int V = 10;
            int ID = 40;
            for (int i = 0; i < 1; i++)
            {
                Console.WriteAscii("hanbot exclusive", Color.FromArgb(DA, V, ID));

                DA -= 0;
                V -= 0;
            }



            //SERVER CHECK
            if (!authentication.Functions.CheckForInternetConnection())
                {
                Environment.Exit(0);
                }

            //AUTHENTICATION_ALPHA
            string username, password = string.Empty;

            //UNIQUEKEY LOCK + AUTHENTICATION PLUGIN
            string whitelist = new WebClient() { Proxy = null }.DownloadString("<source>");
            //string blacklist = new WebClient() { Proxy = null }.DownloadString("<source>");

            if (whitelist.Contains(authentication.FingerPrint.ValueKey()))
            {
                Console.WriteLine(authentication.FingerPrint.ValueKey(), ColorTranslator.FromHtml("#cc0099"));
            }
            else
            {
                if (!whitelist.Contains(authentication.FingerPrint.ValueKey()))
                {
                    Console.WriteLine(authentication.FingerPrint.ValueKey());
                    Console.WriteLine("[" + Timestamp + "]" + " unauthorized machine!", ColorTranslator.FromHtml("#cc0000"));
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            Console.Write("Your username: "******"[" + Timestamp + "]" + " username cannot be empty", ColorTranslator.FromHtml("#cc0000"));
                return;
            }

            Console.Write("Your password: "******"[" + Timestamp + "]" + " password cannot be empty!", ColorTranslator.FromHtml("#cc0000"));
                return;
            }

            authentication.Globals.Username = username;
            authentication.Globals.Password = password;


            //START CHECK FUNCTION
            CheckUser();
        }
Ejemplo n.º 38
0
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveWindowState();

            Environment.Exit(-1);
        }
 public EasyAuthDemoDbContext CreateDbContext(string[] args)
 {
     return(Create(
                Directory.GetCurrentDirectory(),
                Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")));
 }
Ejemplo n.º 40
0
        private void StartAdventure()
        {
            bool keepRunning = true;

            Console.Clear();
            Console.WriteLine("Now let's name your spaceship! Be creative: ");
            string userSpaceShip = Console.ReadLine();

            Console.Clear();
            Console.WriteLine("Now tell me your name and the names of your 4 friends you are bringing along: ");
            string userNameOne   = Console.ReadLine();
            string userNameTwo   = Console.ReadLine();
            string userNameThree = Console.ReadLine();
            string userNameFour  = Console.ReadLine();
            string userNameFive  = Console.ReadLine();

            Console.Clear();
            Console.WriteLine($"Welcome aboard the {userSpaceShip}! {userNameOne}, {userNameTwo}, {userNameThree}, {userNameFour}, {userNameFive} your adventure to Mars begins now!");
            Console.WriteLine("Begin countdown 3...");
            Console.ReadLine();
            Console.WriteLine("2...");
            Console.ReadLine();
            Console.WriteLine("1...");
            Console.ReadLine();
            Console.WriteLine("And we have liftoff!");
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("On your journey to Mars, you'll make a few stops.\n Your first destination is the moon.");
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("Be wary of the dangers of traveling through space..");
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("Traveling at 240,000MPG your shuttle reaches the moon in 3 days. One of the crew sees a small unidentified flying object.");
            Console.WriteLine("Do you want to inspect the UFO? (y/n)");
            string inspectUFO = Console.ReadLine().ToLower();

            if (inspectUFO == "y")
            {
                Console.WriteLine("The UFO is filled with angry aliens, do you try to interact or flee? (i/f)");
                string alienResponse = Console.ReadLine().ToLower();
                if (alienResponse == "i")
                {
                    Console.WriteLine($"You're crew comes under a barrage of heavy fire! You're ship is just able to get away.");
                    Console.ReadLine();
                    Console.WriteLine($"{userNameThree} is mortally wounded.. they won't make it through the night.");
                }
                else if (alienResponse == "f")
                {
                    Console.WriteLine("You travel onward past the darkside of the moon.");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Please enter a valid number.");
                    Console.ReadLine();
                }
            }
            else if (inspectUFO == "n")
            {
                Console.WriteLine("You travel onward past the darkside of the moon.");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Please enter a valid number.");
                Console.ReadLine();
                return;
            }

            Console.Clear();
            Console.WriteLine("A month goes by on the shuttle. The passengers are in good health. The shuttle remains fully operational and Mars is slowly growing in your field of view.");
            RandomEvents();

            Console.Clear();
            Console.WriteLine("Over the communication system you hear reports of a solar flare that has a good chance of starting in 6 days. Luckily the shuttle has a radiation panic room just for this exact purpose.");
            Console.WriteLine("It is the captains choice on how long you and your crew will stay remain in the panic room.");
            Console.WriteLine("How many days will the crew remain in the panic room?? one/two/three");
            string panicRoomInput = Console.ReadLine().ToLower();


            while (keepRunning == true)
            {
                switch (panicRoomInput)
                {
                case "one":
                    Console.WriteLine($"{userNameFour} ventures out to check the radiation levels. When they return {userNameFour} is pale...soon they begin vomiting blood.");
                    Console.ReadLine();
                    Console.Clear();
                    Console.WriteLine($"Another month goes by on board the shuttle. {userNameFour} has succumb to extreme radiation poisoning. Morale on the {userSpaceShip} is low. The red planet continues to grow larger.");
                    Console.ReadLine();
                    break;

                case "two":
                    Console.WriteLine($"{userNameFour} ventures out to check the radiation levels. Whey they return {userNameFour} looks a little queasy, but says levels are close to normal. After 6 more hours you an the crew continue on.");
                    Console.ReadLine();
                    Console.Clear();
                    break;

                case "three":
                    Console.WriteLine($"{userNameFour} ventures out to check the radiation levels. When they return {userNameFour} says the levels are safe. You and your crew continue on.");
                    Console.ReadLine();
                    Console.Clear();
                    break;

                default:
                    Console.WriteLine("Please enter a valid number.");
                    break;
                }
            }

            Console.WriteLine($"After 3 months, the passengers aboard {userSpaceShip} are in good health. The shuttle continues to operate well.  All passengers look forward to a successful landing.");
            RandomEvents();
            Console.ReadLine();
            Console.Clear();

            Console.WriteLine("With 5 days remaining before touchdown on Mars, the crew realizes that a sensor is broken on a thruster.  The thruster needs to be fixed in order to land safely.");
            Console.WriteLine("Option one: ignore the issue and hope for the best.");
            Console.WriteLine("Option two: send two to fix the sensor.");
            Console.WriteLine("Option three: ask the AI system installed for assistance.");
            Console.WriteLine("Option four: risk a life to complete a space walk to fix the issue.");
            Console.WriteLine("Type one/two/three/four");
            string thrusterInput = Console.ReadLine().ToLower();

            Console.Clear();

            /*string thrusterOne = "one";
             * string thrusterTwo = "two";
             * string thrusterThree = "three";
             * string thrusterFour = "four";*/

            while (keepRunning == true)
            {
                switch (thrusterInput)
                {
                case "one":
                    Console.WriteLine($"By choosing to be negligent, {userNameFive} doesn't know it yet, but they won't make it.");
                    Console.ReadLine();
                    Console.Clear();
                    EndOfGame();
                    break;

                case "two":
                    Console.WriteLine($"{userNameOne} ventures out while {userNameFive} checks the lines.");
                    Console.WriteLine($"While working inside, {userNameTwo} sees debris heading toward {userSpaceShip}!");
                    Console.WriteLine($"{userNameOne} and {userNameFive} act in desperation but are hit by the debris and pushed into the depths of space.");
                    Console.ReadLine();
                    Console.Clear();
                    EndOfGame();
                    break;

                case "three":
                    Console.WriteLine($"The AI unit HAL/AL 9000-series relizes that the mission will ultimatly fail as long as there are people alive. The AI begins eliminating people one by one. You lose.");
                    Console.ReadLine();
                    Console.Clear();
                    Console.WriteLine("Goodbye!");
                    keepRunning = false;
                    Environment.Exit(1);
                    break;

                case "four":
                    Console.WriteLine($"{userNameFive} puts on their spacesuit to complete a spacewalk in the hopes of fixing the broken sensor.");
                    Console.WriteLine($"The task is nearly complete when {userNameOne} comes over the radio and reports that oxygen is running low.");
                    Console.WriteLine($"After a tense moment not knowing if {userNameOne} would make it, {userNameOne} returns safely to {userSpaceShip}.");
                    Console.WriteLine("There's a sigh of relief as you and your crew set your next goal on landing.");
                    Console.ReadLine();
                    Console.Clear();
                    EndOfGame();
                    break;

                default:
                    Console.WriteLine("Please enter a valid number.");
                    break;
                }
                Console.WriteLine("Please press any key to continue...");
                Console.ReadKey();
                Console.Clear();
            }

            void EndOfGame()
            {
                Console.WriteLine("As you begin your landing on Mars, you take care to double-check that all parts of your ship are functioning for landing safely.");
                Console.WriteLine("You and your crew deploy a parachute successfully to help slow your speed.  You give the instruction to turn boosters on to slow your momentum.");
                Console.WriteLine("Which speed do you want to choose to land on mars? type 10mph/6mph/2mph");
                string landingSpeed = Console.ReadLine();
                string landingOne   = "10mph";
                string landingTwo   = "6mph";
                string landingThree = "2mph";

                if (landingSpeed == landingOne)
                {
                    Console.WriteLine($"You descended too quickly. You broke the landing legs on the {userSpaceShip}. You will not be able to make it home safely. You lose.");
                    Environment.Exit(1);
                }
                else if (landingSpeed == landingTwo)
                {
                    Console.WriteLine("You successfully landed!  Enjoy your time on Mars!");
                }
                else if (landingSpeed == landingThree)
                {
                    Console.WriteLine("You successfully landed!  Enjoy your time on Mars!");
                }
            }

            void RandomEvents()
            {
                Random random       = new Random();
                int    randomNumber = random.Next(100);

                if (randomNumber < 50)
                {
                    Console.WriteLine("Routine maintenance. The space ship is still fully functional.");
                }
                else if (randomNumber > 50)
                {
                    Console.WriteLine("Your crew fell ill by having bad Tang.");
                }
                else
                {
                    Console.WriteLine("Your ship blew up. You lose.");
                    Environment.Exit(1);
                    Console.ReadLine();
                }
            }
        }
Ejemplo n.º 41
0
	    /// <summary>
		/// True if we consider our install to be shared by all users of the computer.
		/// We currently detect this based on being in the Program Files folder.
		/// </summary>
		/// <returns></returns>
		public static bool SharedByAllUsers()
		{
			// Being a 32-bit app, we expect to get installed in Program Files (x86) on a 64-bit system.
			// If we are in fact on a 32-bit system, we will be in plain Program Files...but on such a system that's what this code gets.
			return Application.ExecutablePath.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86));
		}
 string ISettingsProvider.GetSetting(string key) { return Environment.GetEnvironmentVariable(key); }
Ejemplo n.º 43
0
        private async Task RestoreData()
        {
            // TODO: Tests

            // Temporary folder to extract backup into for validation, copying, etc.
            string backupFolder = Path.Combine(FileSystem.CacheDirectory, "Restore");
            if (Directory.Exists(backupFolder))
                Directory.Delete(backupFolder, true);

            string[] allowedTypes;
            switch (Device.RuntimePlatform)
            {
                case Device.iOS:
                    allowedTypes = new[] { "com.pkware.zip-archive" };
                    break;

                case Device.Android:
                    allowedTypes = new[] { "application/zip" };
                    break;

                default:
                    throw new NotImplementedException();
            }

            // Select backup zip file
            using (FileData fileData = await CrossFilePicker.Current.PickFile(allowedTypes))
            {
                // User cancelled file picking
                if (fileData == null)
                    return;
                
                // Extract zip file to temp folder
                using (var stream = fileData.GetStream())
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
                {
                    archive.ExtractToDirectory(backupFolder);
                }
            }

            string databaseBackupPath = Path.Combine(backupFolder, "default.realm");

            // Validate backup contents (backup is not valid if it does not contain a database file)
            if (!File.Exists(databaseBackupPath))
            {
                await CoreMethods.DisplayAlert(
                    title: Res.Alert_Error_Title,
                    message: Res.Settings_Restore_Error_Invalid,
                    cancel: Res.Alert_Generic_Confirm);

                return;
            }

            // Must close database connection before editing database file
            var database = ComicDatabase.Instance;
            database.Close();

            // Replace database file with zip contents
            string databaseRestorePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "default.realm");
            File.Delete(databaseRestorePath);
            File.Copy(databaseBackupPath, databaseRestorePath);

            // Reopen database connection now that database file is back in place
            database.Open();

            string imageFolderBackupPath = Path.Combine(backupFolder, LocalImageService.SUBFOLDER);
            if (Directory.Exists(imageFolderBackupPath))
            {
                if (Directory.Exists(LocalImageService.FolderPath))
                    Directory.Delete(LocalImageService.FolderPath, true);

                FileHelper.DirectoryCopy(imageFolderBackupPath, LocalImageService.FolderPath, true);
            }
        }
Ejemplo n.º 44
0
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String path = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);

            System.Diagnostics.Process.Start("explorer.exe", path);
        }
Ejemplo n.º 45
0
        public static void StoreOSMEditorSettings(Dictionary <string, string> inputConfigurations)
        {
            try
            {
                string osmEditorFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + System.IO.Path.DirectorySeparatorChar + "ESRI" + System.IO.Path.DirectorySeparatorChar + "OSMEditor";

                if (Directory.Exists(osmEditorFolder) == false)
                {
                    try
                    {
                        Directory.CreateDirectory(osmEditorFolder);
                    }
                    catch
                    {
                        return;
                    }
                }

                string configurationfile = osmEditorFolder + System.IO.Path.DirectorySeparatorChar + "osmeditor.config";

                System.IO.FileStream configurationFileWriter = null;
                try
                {
                    if (File.Exists(configurationfile))
                    {
                        try
                        {
                            File.Delete(configurationfile);
                        }
                        catch { }
                    }

                    configurationFileWriter = File.Create(configurationfile);

                    MemoryStream      memoryStream      = new MemoryStream();
                    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                    xmlWriterSettings.Indent = true;

                    using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
                    {
                        xmlWriter.WriteStartDocument();
                        xmlWriter.WriteStartElement("OSMEditor");

                        foreach (KeyValuePair <string, string> configurationItem in inputConfigurations)
                        {
                            xmlWriter.WriteElementString(configurationItem.Key, configurationItem.Value);
                        }
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndDocument();
                        xmlWriter.Close();
                    }

                    configurationFileWriter.Write(memoryStream.GetBuffer(), 0, Convert.ToInt32(memoryStream.Length));
                    memoryStream.Close();
                }
                catch { }
                finally
                {
                    if (configurationFileWriter != null)
                    {
                        configurationFileWriter.Close();
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 46
0
 private static void updateGoDiagramKey()
 {
     // This line is patched during creation of setup. Do not modify.
     UIRegister.GoDiagramKey = $"{Environment.GetEnvironmentVariable("GO_DIAGRAM_KEY")}";
 }
Ejemplo n.º 47
0
 public override void Bad()
 {
     string data;
     if(IO.StaticReturnsTrueOrFalse())
     {
         /* get environment variable ADD */
         /* POTENTIAL FLAW: Read data from an environment variable */
         data = Environment.GetEnvironmentVariable("ADD");
     }
     else
     {
         /* FIX: Set data to an integer represented as a string */
         data = "10";
     }
     if(IO.StaticReturnsTrueOrFalse())
     {
         StringBuilder sourceCode = new StringBuilder("");
         sourceCode.Append("public class Calculator \n{\n");
         sourceCode.Append("\tpublic int Sum()\n\t{\n");
         sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n");
         sourceCode.Append("\t}\n");
         sourceCode.Append("}\n");
         /* POTENTIAL FLAW: Compile sourceCode containing unvalidated user input */
         CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
         CompilerParameters cp = new CompilerParameters();
         CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString());
         Assembly a = cr.CompiledAssembly;
         object calculator = a.CreateInstance("Calculator");
         Type calculatorType = calculator.GetType();
         MethodInfo mi = calculatorType.GetMethod("Sum");
         int s = (int)mi.Invoke(calculator, new object[] {});
         IO.WriteLine("Result: " + s.ToString());
     }
     else
     {
         int? parsedNum = null;
         /* FIX: Validate user input prior to compiling */
         try
         {
             parsedNum = int.Parse(data);
         }
         catch (FormatException exceptNumberFormat)
         {
             IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number.");
         }
         if (parsedNum != null)
         {
             StringBuilder sourceCode = new StringBuilder("");
             sourceCode.Append("public class Calculator \n{\n");
             sourceCode.Append("\tpublic int Sum()\n\t{\n");
             sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n");
             sourceCode.Append("\t}\n");
             sourceCode.Append("}\n");
             CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
             CompilerParameters cp = new CompilerParameters();
             CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString());
             Assembly a = cr.CompiledAssembly;
             object calculator = a.CreateInstance("Calculator");
             Type calculatorType = calculator.GetType();
             MethodInfo mi = calculatorType.GetMethod("Sum");
             int s = (int)mi.Invoke(calculator, new object[] {});
             IO.WriteLine("Result: " + s.ToString());
         }
     }
 }
Ejemplo n.º 48
0
 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
 {
     Environment.Exit(0);
 }
Ejemplo n.º 49
0
 private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
 {
     Console.WriteLine(e.ExceptionObject.ToString());
     logger.Error(e.ExceptionObject.ToString());
     Environment.Exit(1);
 }
Ejemplo n.º 50
0
        public static Dictionary <string, string> ReadOSMEditorSettings()
        {
            Dictionary <string, string> configurationSettings = new Dictionary <string, string>();

            try
            {
                string osmEditorFolder   = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + System.IO.Path.DirectorySeparatorChar + "ESRI" + System.IO.Path.DirectorySeparatorChar + "OSMEditor";
                string configurationfile = osmEditorFolder + System.IO.Path.DirectorySeparatorChar + "osmeditor.config";

                if (!File.Exists(configurationfile))
                {
                    configurationfile = "c:\\inetpub\\wwwroot\\osm\\" + "osmeditor.config";
                }
                // Setting the path for when the code runs inside VS2010 without being installed.
                if (!File.Exists(configurationfile))
                {
                    configurationfile = System.AppDomain.CurrentDomain.BaseDirectory + "osmeditor.config";
                    osmEditorFolder   = System.AppDomain.CurrentDomain.BaseDirectory;
                }

                if (File.Exists(configurationfile))
                {
                    using (XmlReader configurationFileReader = XmlReader.Create(configurationfile))
                    {
                        while (configurationFileReader.Read())
                        {
                            if (configurationFileReader.IsStartElement())
                            {
                                switch (configurationFileReader.Name)
                                {
                                case "osmbaseurl":
                                    configurationFileReader.Read();
                                    configurationSettings.Add("osmbaseurl", configurationFileReader.Value.Trim());
                                    break;

                                case "osmdomainsfilepath":
                                    configurationFileReader.Read();
                                    configurationSettings.Add("osmdomainsfilepath", configurationFileReader.Value.Trim());
                                    break;

                                case "osmfeaturepropertiesfilepath":
                                    configurationFileReader.Read();
                                    configurationSettings.Add("osmfeaturepropertiesfilepath", configurationFileReader.Value.Trim());
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                    }
                }
                //else
                //    throw new Exception("Config file missing osmeditor.config at osm directory");

                if (configurationSettings.ContainsKey("osmbaseurl") == false)
                {
                    // let's start with the very first default settings
                    configurationSettings.Add("osmbaseurl", "http://www.openstreetmap.org");
                }

                if (configurationSettings.ContainsKey("osmdiffsurl") == false)
                {
                    // let's start with the very first default settings
                    configurationSettings.Add("osmdiffsurl", "http://planet.openstreetmap.org/replication");
                }

                string   path = Assembly.GetExecutingAssembly().Location;
                FileInfo executingAssembly = new FileInfo(path);

                if (configurationSettings.ContainsKey("osmdomainsfilepath") == false)
                {
                    // initialize with the default configuration files
                    if (File.Exists(executingAssembly.Directory.FullName + System.IO.Path.DirectorySeparatorChar + "osm_domains.xml"))
                    {
                        configurationSettings.Add("osmdomainsfilepath", executingAssembly.Directory.FullName + System.IO.Path.DirectorySeparatorChar + "osm_domains.xml");
                    }
                }

                if (configurationSettings.ContainsKey("osmfeaturepropertiesfilepath") == false)
                {
                    if (File.Exists(executingAssembly.Directory.FullName + System.IO.Path.DirectorySeparatorChar + "OSMFeaturesProperties.xml"))
                    {
                        configurationSettings.Add("osmfeatureporpertiesfilepath", executingAssembly.Directory.FullName + System.IO.Path.DirectorySeparatorChar + "OSMFeaturesProperties.xml");
                    }
                }
            }
            catch { }

            return(configurationSettings);
        }
Ejemplo n.º 51
0
        protected override void OnStartup(StartupEventArgs e)
        {
            DispatcherUtil.UIDispatcher = Dispatcher;

            Environment.CurrentDirectory = Path.GetDirectoryName(GetType().Assembly.Location);

            if (!Debugger.IsAttached)
            {
                DispatcherUnhandledException += App_DispatcherUnhandledException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                TaskScheduler.UnobservedTaskException      += TaskScheduler_UnobservedTaskException;
            }

            base.OnStartup(e);

            if (e.Args.Length >= 3 && e.Args[0] == "browser")
            {
                var rLayoutEngine  = e.Args[1];
                var rHostProcessID = int.Parse(e.Args[2]);

                new BrowserWrapper(rLayoutEngine, rHostProcessID);

                Task.Factory.StartNew(() =>
                {
                    Process.GetProcessById(rHostProcessID).WaitForExit();
                    Process.GetCurrentProcess().Kill();
                }, TaskCreationOptions.LongRunning);

                return;
            }

            ThemeManager.Instance.Initialize(this, Accent.Blue);

            CoreDatabase.Initialize();
            DataStore.Initialize();

            DataService.Instance.EnsureDirectory();

            RecordService.Instance.Initialize();
            QuestProgressService.Instance.Initialize();
            MapService.Instance.Initialize();
            ExpeditionService.Instance.Initialize();
            EnemyEncounterService.Instance.Initialize();

            Preference.Instance.Initialize();
            Preference.Instance.Reload();
            StringResources.Instance.Initialize();
            StringResources.Instance.LoadMainResource(Preference.Instance.Language);
            StringResources.Instance.LoadExtraResource(Preference.Instance.ExtraResourceLanguage);

            StatusBarService.Instance.Initialize();
            CacheService.Instance.Initialize();
            NotificationService.Instance.Initialize();

            ServiceManager.Register <IBrowserService>(BrowserService.Instance);

            PluginService.Instance.Initialize();
            Preference.Instance.Reload();

            ShutdownMode = ShutdownMode.OnMainWindowClose;

            if (!Environment.GetCommandLineArgs().Any(r => r.OICEquals("--no-check-for-update")))
            {
                Observable.Timer(TimeSpan.Zero, TimeSpan.FromHours(4.0)).Subscribe(_ => UpdateService.Instance.CheckForUpdate());
            }

            if (e.Args.Any(r => r.OICEquals("--background")))
            {
                return;
            }

            var rMainWindow = new MainWindow();

            r_MainWindowHandle = rMainWindow.Handle;

            MainWindow             = rMainWindow;
            MainWindow.DataContext = Root = new MainWindowViewModel();
            MainWindow.Show();
        }
Ejemplo n.º 52
0
 public static void HandleUnhandledException(Exception ex)
 {
     Environment.FailFast("Unhandled Exception: " + ex.GetType() + ": " + ex.Message, ex);
 }
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     Environment.Exit(0);
 }
Ejemplo n.º 54
0
        static void Main(string[] args)
        {
            Dom one = new Dom();
            SzefBudowy four = new SzefBudowy();
            ProjektDomu two = new Biurowiec();
            ProjektDomu three = new DomJednorodzinny();
            while(true)
            {
                startLabel:
                char klawisz;
                Console.WriteLine("Co chcesz zrobić?");
                Console.WriteLine("A-Buduj biurowiec");
                Console.WriteLine("B-Buduj dom jednorodzinny");
                Console.WriteLine("C-Wyjdź");
                klawisz = Convert.ToChar(Console.ReadLine());
                switch(klawisz)
                {
                    case 'A':
                        string zlap = " ";
                        //two.NowyDom();
                        Console.WriteLine("Jak pomalować elewacje(biel,czerwony,zielony,czarny)??");
                        ustawKolorLabel:
                        zlap = Console.ReadLine();
                        if ((string.IsNullOrEmpty(zlap)==true)||(zlap.Length <=2))
                        {
                            Console.WriteLine("Niepodales poprawnie koloru! Podaj kolor ponownie(biel,czerwony,zielony,czarny): ");
                            goto ustawKolorLabel;
                        }
                        switch(zlap)
                        {
                            case "biel":
                                two.PomalujElewacje(Kolor.biel);
                                break;
                            case "czerowny":
                                two.PomalujElewacje(Kolor.czerwony);
                                break;
                            case "zielony":
                                two.PomalujElewacje(Kolor.zielony);
                                break;
                            case "czarny":
                                two.PomalujElewacje(Kolor.czarny);
                                break;
                            default:
                                Console.WriteLine("Niepoprawnie wybrales kolor.\nProsze wybierz jeden z kolorów(biel,czerwony,zielony,czarny)");
                                goto ustawKolorLabel;
                        }
                        Console.WriteLine("Teraz podaj rodzaj drzwi: ");
                        ustawRDrzwiLabel:

                        string rodzajDrzwi = Console.ReadLine();
                        if ((string.IsNullOrEmpty(rodzajDrzwi)==true) || (rodzajDrzwi.Length <= 2))
                        {
                            Console.WriteLine("Niepodales poprawnie rodzaju drzwi! Podaj rodzaj drzwi ponownie: ");
                            goto ustawRDrzwiLabel;
                        }
                        two.ZamontujDrzwi(rodzajDrzwi);

                        Console.WriteLine("Teraz podaj rodzaj okien: ");
                        ustawROkienLabel:
                        string rodzajOkien = Console.ReadLine();
                        if ((string.IsNullOrEmpty(rodzajOkien)==true) || (rodzajOkien.Length <= 2))
                        {
                            Console.WriteLine("Niepodales poprawnie rodzaju okien! Podaj rodzaj okien ponownie: ");
                            goto ustawROkienLabel;
                        }
                        two.WstawOkna(rodzajOkien);
                        Console.WriteLine("Gratulacje! Poprawnie przyjęto zamówienie!");
                        Console.WriteLine(two.ToString());
                        break;
                    case 'B':
                        zlap = " ";
                        three.NowyDom();

                        Console.WriteLine("Jak pomalować elewacje(biel,czerwony,zielony,czarny)??");
                        ustawKolorLabel2:
                        zlap = Console.ReadLine();
                        if ((string.IsNullOrEmpty(zlap) == true) || (zlap.Length <= 2))
                        {
                            Console.WriteLine("Niepodales poprawnie koloru! Podaj kolor ponownie(biel,czerwony,zielony,czarny): ");
                            goto ustawKolorLabel2;
                        }
                        switch (zlap)
                        {
                            case "biel":
                                three.PomalujElewacje(Kolor.biel);
                                break;
                            case "czerowny":
                                three.PomalujElewacje(Kolor.czerwony);
                                break;
                            case "zielony":
                                three.PomalujElewacje(Kolor.zielony);
                                break;
                            case "czarny":
                                three.PomalujElewacje(Kolor.czarny);
                                break;
                            default:
                                Console.WriteLine("Niepoprawnie wybrales kolor.\nProsze wybierz jeden z kolorów(biel,czerwony,zielony,czarny)");
                                goto ustawKolorLabel;
                        }
                        Console.WriteLine("Teraz podaj rodzaj drzwi: ");
                        ustawRDrzwiLabel2:

                        rodzajDrzwi = Console.ReadLine();
                        if ((string.IsNullOrEmpty(rodzajDrzwi) == true) || (rodzajDrzwi.Length <= 2))
                        {
                            Console.WriteLine("Niepodales poprawnie rodzaju drzwi! Podaj rodzaj drzwi ponownie: ");
                            goto ustawRDrzwiLabel2;
                        }
                        three.ZamontujDrzwi(rodzajDrzwi);

                        Console.WriteLine("Teraz podaj rodzaj okien: ");
                        ustawROkienLabel2:
                        rodzajOkien = Console.ReadLine();
                        if ((string.IsNullOrEmpty(rodzajOkien) == true) || (rodzajOkien.Length <= 2))
                        {
                            Console.WriteLine("Niepodales poprawnie rodzaju okien! Podaj rodzaj okien ponownie: ");
                            goto ustawROkienLabel2;
                        }
                        three.WstawOkna(rodzajOkien);
                        Console.WriteLine("Gratulacje! Poprawnie przyjęto zamówienie!");
                        Console.WriteLine(three.ToString());
                        break;
                    case 'C':
                        Environment.Exit(1);
                        break;
                    default:
                        Console.WriteLine("Błąd!");
                        goto startLabel;
                }
            }

        }
Ejemplo n.º 55
0
        private void X_click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(1);
            //this.Close();

        }
 public string Execute(string[] args)
 {
     Environment.Exit(0);
     return(null);
 }
Ejemplo n.º 57
0
 [System.Security.SecurityCritical]  // auto-generated
 internal void Save () {
     EncodeLevel(Environment.GetResourceString("Policy_PL_Enterprise"));
     EncodeLevel(Environment.GetResourceString("Policy_PL_Machine"));
     EncodeLevel(Environment.GetResourceString("Policy_PL_User"));
 }
 private void Exit(object s, EventArgs e)
 {
     Environment.Exit(0);
 }
 private void ExceptionForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     Environment.Exit(-666);
 }
        public async Task <object> FindByLogin(LoginDto user)
        {
            var baseUser = new UserEntity();

            if (user != null && !string.IsNullOrWhiteSpace(user.Email))
            {
                baseUser = await _repository.FindByLogin(user.Email);

                if (baseUser == null)
                {
                    return new
                           {
                               authenticated = false,
                               message       = "Falha ao autenticar"
                           }
                }
                ;
                else
                {
                    ClaimsIdentity identity = new ClaimsIdentity(
                        new GenericIdentity(user.Email),
                        new[]
                    {
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),     //jti Id do Token
                        new Claim(JwtRegisteredClaimNames.UniqueName, user.Email)
                    }
                        );

                    DateTime createDate = DateTime.Now;
                    //DateTime expirationDate = DateTime.Now + TimeSpan.FromSeconds(_tokenConfigurations.Seconds);
                    DateTime expirationDate = DateTime.Now + TimeSpan.FromSeconds(Convert.ToInt32(Environment.GetEnvironmentVariable("Seconds")));
                    var      handler        = new JwtSecurityTokenHandler();
                    string   token          = CreateToken(identity, createDate, expirationDate, handler);
                    return(SuccessObject(createDate, expirationDate, token, user));
                }
            }
            else
            {
                return new
                       {
                           authnticated = false,
                           message      = "Falha ao autenticar"
                       }
            };
        }