Inheritance: MonoBehaviour
        private IEnumerable<Event> Car(string name, Environment env, Resource gasStation, Container fuelPump)
        {
            /*
               * A car arrives at the gas station for refueling.
               *
               * It requests one of the gas station's fuel pumps and tries to get the
               * desired amount of gas from it. If the stations reservoir is
               * depleted, the car has to wait for the tank truck to arrive.
               */
              var fuelTankLevel = env.RandUniform(MinFuelTankLevel, MaxFuelTankLevel + 1);
              env.Log("{0} arriving at gas station at {1}", name, env.Now);
              using (var req = gasStation.Request()) {
            var start = env.Now;
            // Request one of the gas pumps
            yield return req;

            // Get the required amount of fuel
            var litersRequired = FuelTankSize - fuelTankLevel;
            yield return fuelPump.Get(litersRequired);

            // The "actual" refueling process takes some time
            yield return env.Timeout(TimeSpan.FromSeconds(litersRequired / RefuelingSpeed));

            env.Log("{0} finished refueling in {1} seconds.", name, (env.Now - start).TotalSeconds);
              }
        }
Exemplo n.º 2
0
 internal MyBackbuffer(SharpDX.Direct3D11.Resource swapChainBB)
 {
     m_resource = swapChainBB;
     m_resource.DebugName = m_debugName;
     m_rtv = new RenderTargetView(MyRender11.Device, swapChainBB);
     m_rtv.DebugName = m_debugName;
 }
Exemplo n.º 3
0
		public void ShouldWork()
		{
			using (var session = store.OpenSession())
			{
				var person = new Person
				{
					Id = "people/1",
					Name = "Person 1",
					Roles = new List<string>(),
					Permissions = new List<OperationPermission>()
				};
				session.Store(person);
				person.Permissions.Add(new OperationPermission()
				{
					Operation = "resources",
					Allow = true,
					Tags = {person.Id}
				});
				person = new Person
				{
					Id = "people/2",
					Name = "Person 2",
					Roles = new List<string>(),
					Permissions = new List<OperationPermission>()
				};
				session.Store(person);
				person.Permissions.Add(new OperationPermission()
				{
					Operation = "resources",
					Allow = true,
					Tags = {person.Id}
				});

				var resource = new Resource
				{
					Name = "resources",
					Id = "resources/1"
				};
				session.Store(resource);
				session.SetAuthorizationFor(resource, new DocumentAuthorization()
				{
					Tags = {"people/1"}
				});
				session.SaveChanges();
			}
			using (var session = store.OpenSession())
			{
				session.SecureFor("people/1", "resources/view");
				session.Load<Resource>("resources/1");
				var collection = session.Query<Resource>().ToList();
				Assert.NotEmpty(collection);
			}
			using(var session = store.OpenSession())
			{
				session.SecureFor("people/2", "resources/view");
				Assert.Throws<ReadVetoException>(() => session.Load<Resource>("resources/1"));
				var collection = session.Query<Resource>().ToList();
				Assert.Empty(collection);
			}
		}
Exemplo n.º 4
0
Arquivo: IO.cs Projeto: jayvin/Courier
        public static string ResourceFilePath(Resource resource, string revisionAlias)
        {
            string root = ResourcesFolder(revisionAlias);
            var path = (root + Core.Helpers.IO.DirSepChar + resource.TemporaryStoragePath.Replace("//", "/").Replace('/', '\\').TrimStart('\\'));

            return path;
        }
Exemplo n.º 5
0
        public override bool NeedsExecutionFor(Resource resource)
        {
            var rpfName = GetRpfNameFor(resource);

            if (!File.Exists(rpfName))
            {
                return true;
            }

            // if not, test modification times
            var requiredFiles = GetRequiredFilesFor(resource).Select(a => Path.Combine(resource.Path, a));
            requiredFiles = requiredFiles.Concat(resource.ExternalFiles.Select(a => a.Value.FullName));

            var modDate = requiredFiles.Select(a => File.GetLastWriteTime(a)).OrderByDescending(a => a).First();
            var rpfModDate = File.GetLastWriteTime(rpfName);

            if (modDate > rpfModDate)
            {
                return true;
            }

            // and get the hash of the client package to store for ourselves (yes, we do this on every load; screw big RPF files, we're reading them anyway)
            var hash = Utils.GetFileSHA1String(rpfName);

            resource.ClientPackageHash = hash;

            return false;
        }
Exemplo n.º 6
0
 public Tile(Resource r, Vector3 gl, Vector2 p, int chitValue)
 {
     resource = r;
     geoLocation = gl;
     position = p;
     this.chitValue = chitValue;
 }
Exemplo n.º 7
0
        public void Clone_DeepCopy()
        {
            Resource resource = new Resource("TV");
            Course course = new Course(10, 10, new List<Resource>() { resource });
            unit1.AssignedCourse = course;

            TimeUnit clone = (TimeUnit)unit1.Clone();

            Course course2 = new Course(20, 20, new List<Resource>());
            DateTime start2 = DateTime.Now.AddDays(1);
            DateTime end2 = start2.AddHours(1);

            // mutate course
            clone.AssignedCourse = course2;
            // mutate end
            clone.End = end2;
            // mutate start
            clone.Start = start2;

            Assert.AreEqual(course, unit1.AssignedCourse);
            Assert.AreEqual(start, unit1.Start);
            Assert.AreEqual(end, unit1.End);

            Assert.AreEqual(course2, clone.AssignedCourse);
            Assert.AreEqual(start2, clone.Start);
            Assert.AreEqual(end2, clone.End);
        }
Exemplo n.º 8
0
    void Update()
    {
        Vector3 mouse_pos = Input.mousePosition;
        Vector3 player_pos = Camera.main.WorldToScreenPoint(this.transform.position);

        // Need to subtract player pos to get cannon rotation right
        mouse_pos.x = mouse_pos.x - player_pos.x;
        mouse_pos.y = mouse_pos.y - player_pos.y;

        float angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg;
        this.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
        if (Input.GetMouseButtonDown(0))
        {
            shoot(mouse_pos, player_pos);
        }

        if (Input.GetKeyDown("o"))
        {
            activePool = splitProjectilePool;
        }
        else if (Input.GetKeyDown("p"))
        {
            activePool = projectilePool;
        }
    }
Exemplo n.º 9
0
        public override void Read(BinaryReader reader, Resource resource)
        {
            reader.BaseStream.Position = this.Offset;

            CRC32 = reader.ReadUInt32();

            var size = reader.ReadUInt16();
            int headerSize = 4 + 2;

            for (var i = 0; i < size; i++)
            {
                var entry = new NameEntry
                {
                    Name = reader.ReadNullTermString(Encoding.UTF8),
                    CRC32 = reader.ReadUInt32(),
                };

                Names.Add(entry);

                headerSize += entry.Name.Length + 1 + 4; // string length + null byte + 4 bytes
            }

            Data = reader.ReadBytes((int)this.Size - headerSize);

            if (Crc32.Compute(Data) != CRC32)
            {
                throw new InvalidDataException("CRC32 mismatch for read data.");
            }
        }
        public void DynamicFetch()
        {
            using (ISession s = OpenSession())
            using (ITransaction tx = s.BeginTransaction())
            {
                DateTime now = DateTime.Now;
                User me = new User("me");
                User you = new User("you");
                Resource yourClock = new Resource("clock", you);
                Task task = new Task(me, "clean", yourClock, now); // :)
                s.Save(me);
                s.Save(you);
                s.Save(yourClock);
                s.Save(task);
                tx.Commit();
            }

            using (IStatelessSession ss = sessions.OpenStatelessSession())
            using (ITransaction tx = ss.BeginTransaction())
            {
                ss.BeginTransaction();
                Task taskRef =
                    (Task)ss.CreateQuery("from Task t join fetch t.Resource join fetch t.User").UniqueResult();
                Assert.True(taskRef != null);
                Assert.True(NHibernateUtil.IsInitialized(taskRef));
                Assert.True(NHibernateUtil.IsInitialized(taskRef.User));
                Assert.True(NHibernateUtil.IsInitialized(taskRef.Resource));
                Assert.False(NHibernateUtil.IsInitialized(taskRef.Resource.Owner));
                tx.Commit();
            }

            cleanup();
        }
        public void ShouldMatchResourceOnKey()
        {
            var filter = new ResourceFilter { KeyRegex = new Regex(@"Kiwi") };
            var resource = new Resource("This_is_my_Kiwi_resource");

            filter.IsMatch(resource).ShouldBeTrue();
        }
        public void ShouldMatchResourceOnKeyAndValue()
        {
            var filter = new ResourceFilter { KeyRegex = new Regex(@"Kiwi"), ValueRegex = new Regex(@"amazing kiwi") };
            var resource = new Resource("This_is_my_Kiwi_resource", "What an amazing kiwi");

            filter.IsMatch(resource).ShouldBeTrue();
        }
Exemplo n.º 13
0
    protected override void HandleObjectCommand(CommandType command, GameObject targetObject)
    {
        if (isSelected)
        {
            switch (command)
            {
                case CommandType.Attack:
                    {
                        currentTarget = targetObject.GetComponent<Commandable>();
                        currentCommand = command;
                        UpdatePath();
                    }
                    break;
                case CommandType.Follow:
                    {

                    }
                    break;
                case CommandType.Patrol:
                    {

                    }
                    break;
                case CommandType.Mine:
                    {
                        currentResourceTarget = targetObject.GetComponent<Resource>();
                        currentCommand = command;
                        UpdatePath();
                    }
                    break;
                default:
                    break;
            }
        }
    }
Exemplo n.º 14
0
        public override Statistics run()
        {
            Environment env = new Environment();

            //dist
            List<double> valueList = new List<double>() { 1, 2, 3, 4, 5 };
            List<double> distribution = new List<double>() { 0.5, 0.6, 0.7, 0.8, 1.0 };
            Discrete d = new Discrete(valueList, distribution);
            //dist1
            Uniform n = new Uniform(1, 3);
            Distribution dist = new Distribution(d);
            Distribution dist1 = new Distribution(n);

            Create c = new Create(env, 0, 20, dist);

            Dispose di = new Dispose(env, 1);

            Queue q = new Queue(env, 3);
            q.Capacity = 1;
            Resource r = new Resource(env, 2, 1, dist1, q);

            c.Next_AID.Add("First", 2);
            r.Next_AID.Add("First", 1);

            env.System_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Start_Time = new DateTime(1970, 1, 1, 0, 0, 0);
            env.Setup_Simulation();
            return env.Simulate();
        }
Exemplo n.º 15
0
        public ProcessingResult Process(Resource resource)
        {
            var eventRecorder = new EventRecorder();
            this.Target = new StubTarget();

            var concordionBuilder = new ConcordionBuilder()
                .withEvaluatorFactory(this.EvaluatorFactory)
                .withIOUtil(new IOUtil())
                .withSource(this.Source)
                .withTarget(this.Target)
                .withAssertEqualsListener(eventRecorder)
                .withThrowableListener(eventRecorder);

            if (this.Fixture != null)
            {
                new ExtensionLoader(this.Configuration).AddExtensions(this.Fixture, concordionBuilder);
            }

            if (this.Extension != null)
            {
                this.Extension.addTo(concordionBuilder);
            }

            var concordion = concordionBuilder.build();

            ResultSummary resultSummary = concordion.process(resource, this.Fixture);
            string xml = this.Target.GetWrittenString(resource);
            return new ProcessingResult(resultSummary, eventRecorder, xml);
        }
Exemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Textbox"/> class.
 /// </summary>
 public Label()
 {
     this.Text = "";
     this.font = AlmiranteEngine.Resources.LoadSync<BitmapFont>("Fonts\\Pixel16");
     this.Color = Color.White;
     this.Alignment = FontAlignment.Left;
 }
 public void Handle_ShouldReturnContentResultWithContent_WhenValidResourceSpecified()
 {
     var handler = new ResourceRouteHandler();
     var resource = new Resource(Resources.ResourceManager, Resources.StringResources.test);
     var result = handler.Handle(null, new RouteData { Data = resource });
     Assert.AreEqual(Resources.GetString(Resources.StringResources.test), (result as ContentResult).Content);
 }
 public void Handle_ShouldReturnContentResultWithLastModified_WhenDataIsResource()
 {
     var handler = new ResourceRouteHandler();
     var resource = new Resource(Resources.ResourceManager, Resources.StringResources.test);
     var result = handler.Handle(null, new RouteData { Data = resource });
     Assert.AreEqual(resource.LastModified, (result as ContentResult).LastModified);
 }
        public void ShouldTransformFiles()
        {
            var path = SampleData.GenerateRandomTempPath("TransformFilesTests");
            SampleData.CreateSampleFileHierarchy(this.FileSystem, path);

            var apples = XmlResourceParser.ParseAsResourceList(SampleData.SampleXmlFruitResourceString("Apple"));

            var appleResourceOne = apples.First(x => x.Key == "Resfit_Tests_Apple_Resource_One");
            var replacementOrangeOne = new Resource(
                "Resfit_Tests_Orange_Resource_One",
                "My orange is taking over the world");

            appleResourceOne.Transforms.Add(new ResourceReplacementTransform(replacementOrangeOne));
            new FileTransformer(this.FileSystem, apples).TransformDirectory(path, FileFilter.Typical);

            // -- Verify the files were changed as expected
            var changedAppleSourceFile = this.FileSystem.LoadFile(Path.Combine(path, "Apples.cs"));
            changedAppleSourceFile.ShouldNotContain("Resfit_Tests_Apple_Resource_One");
            changedAppleSourceFile.ShouldContain("Resfit_Tests_Orange_Resource_One");

            // -- Verify the resources where changd as expected
            var changedAppleResourcesFile = this.FileSystem.LoadFile(Path.Combine(path, "Apples.resx"));
            var changedAppleResources = XmlResourceParser.ParseAsResourceList(changedAppleResourcesFile);
            changedAppleResources.ShouldNotContain(x => x.Key == "Resfit_Tests_Apple_Resource_One");
            var oranges = changedAppleResources.Where(x => x.Key == "Resfit_Tests_Orange_Resource_One").ToArray();
            oranges.Count().ShouldBe(1);
            var orange = oranges.First();
            orange.Key.ShouldBe("Resfit_Tests_Orange_Resource_One");
            orange.Value.ShouldBe("My orange is taking over the world");
        }
 public void Handle_ShouldReturnContentResultWithContentType_WhenResourceSpecifiesType()
 {
     var handler = new ResourceRouteHandler();
     var resource = new Resource(Resources.ResourceManager, Resources.StringResources.test) { ContentType = "text/html" };
     var result = handler.Handle(null, new RouteData { Data = resource });
     Assert.AreEqual(resource.ContentType, (result as ContentResult).ContentType);
 }
Exemplo n.º 21
0
        public void Test_If_Paths_Are_Not_Identical_Can_Calculate_Relative_Path()
        {
            var from = new Resource(@"\spec\");
            var to = new Resource(@"\spec\blah");

            Assert.AreEqual(@"blah", from.getRelativePath(to));
        }
Exemplo n.º 22
0
        public void Test_If_Paths_Are_Weird_And_End_In_Slashes_Can_Calculate_Relative_Path()
        {
            var from = new Resource(@"\x\b\c\");
            var to = new Resource(@"\a\b\x\");

            Assert.AreEqual(@"../../../a/b/x/", from.getRelativePath(to));
        }
Exemplo n.º 23
0
 // Initialization
 public void SetResource(Resource newResource)
 {
     resource = newResource;
     // Update models
     resourceModel.sprite = resource.MapIcon;
     resourceModel.color = resource.MapIconColor;
 }
Exemplo n.º 24
0
 public void recieveResource(Resource resource)
 {
     for (int i = 0; i < spawnAmount; i++)
     {
         mobQueue.Enqueue(resource);
     }
 }
        /// <summary>
        /// Creates new instance from AddOn
        /// </summary>
        /// <param name="resource">The add on details</param>
        /// <param name="geoRegion">The add on region</param>
        public WindowsAzureAddOn(Resource resource, string geoRegion, string cloudService)
        {
            Type = resource.Namespace == DataSetType ? DataType : AppServiceType;

            AddOn = resource.Type;

            Name = resource.Name;

            Plan = resource.Plan;

            SchemaVersion = resource.SchemaVersion;

            ETag = resource.ETag;

            State = resource.State;

            UsageMeters = resource.UsageLimits.ToList();

            OutputItems = (Type == AppServiceType) ? new Dictionary<string, string>(resource.OutputItems) :
                new Dictionary<string, string>();

            LastOperationStatus = resource.Status;

            Location = geoRegion;

            CloudService = cloudService;
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     // Browser detection and redirecting to error page
     if (Request.Browser.Browser.ToLower() == "ie" && Convert.ToDouble(Request.Browser.Version) < 7)
     {
         SPUtility.TransferToErrorPage("To view this report use later versions of IE 6.0");
     }
     else
     {
         try
         {
             string siteurl = MyUtilities.ProjectServerInstanceURL(SPContext.Current);
             var Resource_Svc = new Resource()
                                    {
                                        AllowAutoRedirect = true,
                                        Url = siteurl + "/_vti_bin/psi/resource.asmx",
                                        UseDefaultCredentials = true
                                    };
             var result = MyUtilities.GetGovernanceReport(siteurl, Resource_Svc.GetCurrentUserUid());
             //Repeater1.DataSource = result;
             //Repeater1.DataBind();
             JSONData.Text = result.Rows.Count > 0 ? MyUtilities.Serialize(result) : "";
         }
         catch (Exception ex)
         {
             MyUtilities.ErrorLog(ex.Message, EventLogEntryType.Error);
         }
     }
 }
Exemplo n.º 27
0
 public void CloneFrom(ResourceCollection other)
 {
     int e = 0, o = 0;
     while (e < Resources.Count || o < other.Resources.Count) {
         int oid = o;
         if (e < Resources.Count) {
             for (; oid < other.Resources.Count; ++oid) if (other.Resources[oid].Name == Resources[e].Name) break;
         } else oid = other.Resources.Count;
         if (e == Resources.Count || oid < other.Resources.Count) {
             for (; o < oid; ++o) {
                 var otherEntity = other.Resources[o];
                 var myEntity = new Resource() { Name = otherEntity.Name };
                 myEntity.Amount = otherEntity.Amount;
                 Resources.Insert(e++, myEntity);
             }
         }
         if (e < Resources.Count) {
             if (oid < other.Resources.Count) {
                 if (oid != o) Debug.LogError("Id missmatch");
                 Resources[e++].Amount = other.Resources[o++].Amount;
             } else {
                 Resources.RemoveAt(e);
             }
         }
     }
 }
Exemplo n.º 28
0
        public void Test_If_Paths_Point_To_File_And_Are_Identical_Can_Calculate_Relative_Path()
        {
            var from = new Resource(@"\spec\x.html");
            var to = new Resource(@"\spec\x.html");

            Assert.AreEqual("x.html", from.getRelativePath(to));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Scene initialization
        /// </summary>
        protected override void OnInitialize()
        {
            var device = AlmiranteEngine.Device;
            this.background = new Texture2D(device, 1, 1);
            this.background.SetData(new Color[] { Color.FromNonPremultiplied(0, 0, 0, 255) });
            this.map = AlmiranteEngine.Resources.LoadSync<Texture2D>("Objects\\Back");

            this.text = new Textbox()
            {
                Size = new Vector2(620, 30),
                Position = new Vector2(10, 720 - 40),
                MaxLength = 60
            };
            this.text.KeyDown += OnKeyDown;
            this.text.Enter += OnFocus;
            this.text.Leave += OnUnfocus;

            this.Interface.Controls.Add(this.text);

            this.chat = new Chat()
            {
                Size = new Vector2(620, 620),
                Position = new Vector2(10, 720 - 40 - 10 - 620),
                MaxEntries = 50
            };
            this.Interface.Controls.Add(this.chat);

            Player.Instance.Protocol.Subscribe<PlayerMessage>(this.OnMessage);
        }
Exemplo n.º 30
0
        /// <summary>
        /// اطالعات مربوط به سطوح دسترسی را در ذخیره میکند
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="resourceIdList">منابعی که دسترسی به آنها مجاز است</param>
        /// <returns></returns>
        public bool UpdateAthorize(decimal roleId, IList <decimal> resourceIdList)
        {
            EntityRepository <Resource> resourceRep = new EntityRepository <Resource>();

            using (NHibernateSessionManager.Instance.BeginTransactionOn())
            {
                try
                {
                    Role role = base.GetByID(roleId);
                    if (role.AuthorizeList != null)
                    {
                        List <Authorize> OtherSystemAuthorizeList = role.AuthorizeList.Where(authorize => authorize.Resource.SubSystemId != SubSystemIdentifier.TimeAtendance).ToList();
                        List <decimal>   tmpResourceIds           = new List <decimal>();
                        tmpResourceIds.AddRange(resourceIdList);
                        tmpResourceIds.AddRange((from o in OtherSystemAuthorizeList
                                                 select o.Resource.ID).ToList());

                        resourceIdList = tmpResourceIds.ToList();
                        role.AuthorizeList.Clear();
                    }
                    else
                    {
                        role.AuthorizeList = new List <Authorize>();
                    }
                    foreach (decimal resourceId in resourceIdList)
                    {
                        Authorize athorize = new Authorize();
                        Resource  resource = resourceRep.GetById(resourceId, false);
                        athorize.Allow    = true;
                        athorize.Resource = resource;
                        athorize.Role     = role;
                        if (role.AuthorizeList.Where(auth => auth.Resource.ID == athorize.Resource.ID && auth.Role.ID == athorize.Role.ID).Count() == 0)
                        {
                            role.AuthorizeList.Add(athorize);
                        }
                        foreach (decimal parentId in resource.ParentPathList)
                        {//add parents
                            athorize          = new Authorize();
                            athorize.Allow    = true;
                            athorize.Resource = new Resource()
                            {
                                ID = parentId
                            };
                            athorize.Role = role;
                            if (role.AuthorizeList.Where(auth => auth.Resource.ID == athorize.Resource.ID && auth.Role.ID == athorize.Role.ID).Count() == 0)
                            {
                                role.AuthorizeList.Add(athorize);
                            }
                        }
                    }
                    this.SaveChanges(role, UIActionType.EDIT);

                    NHibernateSessionManager.Instance.CommitTransactionOn();
                    return(true);
                }
                catch (Exception ex)
                {
                    NHibernateSessionManager.Instance.RollbackTransactionOn();
                    LogException(ex, "BRole", "UpdateAthorize");
                    throw ex;
                }
            }
        }
Exemplo n.º 31
0
 public void AddResource(Resource resource)
 {
     Add(resource);
     SaveChanges();
 }
Exemplo n.º 32
0
 internal SubnetOperations(AzureResourceManagerClientOptions options, Resource resource)
     : base(options, resource)
 {
 }
        } // Value

        #endregion

        #region Constructor

        /// <summary>
        /// Shader Parameter for Matrix type.
        /// </summary>
        public ShaderParameterMatrix(string name, Shader shader) : base(name, shader)
        {
            Resource.SetValue(Value);
        } // ShaderParameterMatrix
Exemplo n.º 34
0
        private static ArrayList prove(Hashtable cases, SelectableSource world, Statement[] goal, int maxNumberOfSteps)
        {
            // This is the main routine from euler.js.

            // cases: Resource (predicate) => IList of Sequent

            if (world != null)             // cache our queries to the world, if a world is provided
            {
                world = new SemWeb.Stores.CachedSource(world);
            }

            StatementMap cached_subproofs = new StatementMap();

            // Create the queue and add the first item.
            ArrayList queue = new ArrayList();
            {
                QueueItem start = new QueueItem();
                start.env    = new Hashtable();
                start.rule   = new Sequent(Statement.All, goal, null);
                start.src    = null;
                start.ind    = 0;
                start.parent = null;
                start.ground = new ArrayList();
                queue.Add(start);
                if (Debug)
                {
                    Console.Error.WriteLine("Euler: Queue: " + start);
                }
            }

            // The evidence array holds the results of this proof.
            ArrayList evidence = new ArrayList();

            // Track how many steps we take to not go over the limit.
            int step = 0;

            // Process the queue until it's empty or we reach our step limit.
            while (queue.Count > 0)
            {
                // deal with the QueueItem at the top of the queue
                QueueItem c = (QueueItem)queue[queue.Count - 1];
                queue.RemoveAt(queue.Count - 1);
                ArrayList g = new ArrayList(c.ground);

                // have we done too much?
                step++;
                if (maxNumberOfSteps != -1 && step >= maxNumberOfSteps)
                {
                    if (Debug)
                    {
                        Console.Error.WriteLine("Euler: Maximum number of steps exceeded.  Giving up.");
                    }
                    return(null);
                }

                // if each statement in the body of the sequent has been proved
                if (c.ind == c.rule.body.Length)
                {
                    // if this is the top-level sequent being proved; we've found a complete evidence for the goal
                    if (c.parent == null)
                    {
                        EvidenceItem ev = new EvidenceItem();
                        ev.head = new Statement[c.rule.body.Length];
                        bool canRepresentHead = true;
                        for (int i = 0; i < c.rule.body.Length; i++)
                        {
                            ev.head[i] = evaluate(c.rule.body[i], c.env);
                            if (ev.head[i].AnyNull)                             // can't represent it: literal in subject position, for instance
                            {
                                canRepresentHead = false;
                            }
                        }

                        ev.body = c.ground;
                        ev.env  = c.env;

                        if (Debug)
                        {
                            Console.Error.WriteLine("Euler: Found Evidence: " + ev);
                        }

                        if (!canRepresentHead)
                        {
                            continue;
                        }

                        evidence.Add(ev);

                        // this is a subproof of something; whatever it is a subgroup for can
                        // be incremented
                    }
                    else
                    {
                        // if the rule had no body, it was just an axiom and we represent that with Ground
                        if (c.rule.body.Length != 0)
                        {
                            g.Add(new Ground(c.rule, c.env));
                        }

                        // advance the parent being proved and put the advanced
                        // parent into the queue; unify the parent variable assignments
                        // with this one's
                        QueueItem r = new QueueItem();
                        r.rule   = c.parent.rule;
                        r.src    = c.parent.src;
                        r.ind    = c.parent.ind;
                        r.parent = c.parent.parent;
                        r.env    = (Hashtable)c.parent.env.Clone();
                        r.ground = g;
                        unify(c.rule.head, c.env, r.rule.body[r.ind], r.env, true);
                        r.ind++;
                        queue.Add(r);
                        if (Debug)
                        {
                            Console.Error.WriteLine("Euler: Queue Advancement: " + r);
                        }

                        // The number of live children for this parent is decremented since we are
                        // done with this subproof, but we store the result for later.
                        if (c.parent.solutions == null)
                        {
                            c.parent.solutions = new StatementList();
                        }
                        c.parent.solutions.Add(evaluate(r.rule.body[r.ind - 1], r.env));
                        decrementLife(c.parent, cached_subproofs);
                    }

                    // this sequent still has parts of the body left to be proved; try to
                    // find evidence for the next statement in the body, and if we find
                    // evidence, queue up that evidence
                }
                else
                {
                    // this is the next part of the body that we need to try to prove
                    Statement t = c.rule.body[c.ind];

                    // Try to process this predicate with a user-provided custom
                    // function that resolves things like mathematical relations.
                    // euler.js provides similar functionality, but the system
                    // of user predicates is completely different here.
                    RdfRelation b = FindUserPredicate(t.Predicate);
                    if (b != null)
                    {
                        Resource[] args;
                        Variable[] unifyResult;
                        Resource   value = evaluate(t.Object, c.env);

                        if (!c.rule.callArgs.ContainsKey(t.Subject))
                        {
                            // The array of arguments to this relation is just the subject of the triple itself
                            args        = new Resource[] { evaluate(t.Subject, c.env) };
                            unifyResult = new Variable[1];
                            if (t.Subject is Variable)
                            {
                                unifyResult[0] = (Variable)t.Subject;
                            }
                        }
                        else
                        {
                            // The array of arguments to this relation comes from a pre-grouped arg list.
                            args        = (Resource[])((ICloneable)c.rule.callArgs[t.Subject]).Clone();
                            unifyResult = new Variable[args.Length];

                            for (int i = 0; i < args.Length; i++)
                            {
                                if (args[i] is Variable)
                                {
                                    unifyResult[i] = (Variable)args[i];
                                    args[i]        = evaluate(args[i], c.env);
                                }
                            }
                        }

                        // Run the user relation on the array of arguments (subject) and on the object.
                        if (b.Evaluate(args, ref value))
                        {
                            // If it succeeds, we press on.

                            // The user predicate may update the 'value' variable and the argument
                            // list array, and so we want to unify any variables in the subject
                            // or object of this user predicate with the values given to us
                            // by the user predicate.
                            Hashtable newenv = (Hashtable)c.env.Clone();
                            if (t.Object is Variable)
                            {
                                unify(value, null, t.Object, newenv, true);
                            }
                            for (int i = 0; i < args.Length; i++)
                            {
                                if (unifyResult[i] != null)
                                {
                                    unify(args[i], null, unifyResult[i], newenv, true);
                                }
                            }

                            Statement grnd = evaluate(t, newenv);
                            if (grnd != Statement.All)                             // sometimes not representable, like if literal as subject
                            {
                                g.Add(new Ground(new Sequent(grnd, new Statement[0], null), new Hashtable()));
                            }

                            QueueItem r = new QueueItem();
                            r.rule   = c.rule;
                            r.src    = c.src;
                            r.ind    = c.ind;
                            r.parent = c.parent;
                            r.env    = newenv;
                            r.ground = g;
                            r.ind++;
                            queue.Add(r);

                            // Note: Since we are putting something back in for c, we don't touch the life counter on the parent.
                        }
                        else
                        {
                            // If the predicate fails, decrement the life of the parent.
                            if (c.parent != null)
                            {
                                decrementLife(c.parent, cached_subproofs);
                            }
                        }
                        continue;
                    }

                    // t can be proved either by the use of a rule
                    // or if t literally exists in the world

                    Statement t_resolved = evaluate(t, c.env);

                    // If resolving this statement requires putting a literal in subject or predicate position, we
                    // can't prove it.
                    if (t_resolved == Statement.All)
                    {
                        if (c.parent != null)
                        {
                            decrementLife(c.parent, cached_subproofs);
                        }
                        continue;
                    }

                    ArrayList tcases = new ArrayList();

                    // See if we have already tried to prove this.
                    if (cached_subproofs.ContainsKey(t_resolved))
                    {
                        StatementList cached_solutions = (StatementList)cached_subproofs[t_resolved];
                        if (cached_solutions == null)
                        {
                            if (Debug)
                            {
                                Console.Error.WriteLine("Euler: Dropping queue item because we have already failed to prove it: " + t_resolved);
                            }
                        }
                        else
                        {
                            foreach (Statement s in cached_solutions)
                            {
                                if (Debug)
                                {
                                    Console.Error.WriteLine("Euler: Using Cached Axiom:  " + s);
                                }
                                Sequent seq = new Sequent(s);
                                tcases.Add(seq);
                            }
                        }
                    }
                    else
                    {
                        // get all of the rules that apply to the predicate in question
                        if (t_resolved.Predicate != null && cases.ContainsKey(t_resolved.Predicate))
                        {
                            tcases.AddRange((IList)cases[t_resolved.Predicate]);
                        }

                        if (cases.ContainsKey("WILDCARD"))
                        {
                            tcases.AddRange((IList)cases["WILDCARD"]);
                        }

                        // if t has no unbound variables and we've matched something from
                        // the axioms, don't bother looking at the world, and don't bother
                        // proving it any other way than by the axiom.
                        bool lookAtWorld = true;
                        foreach (Sequent seq in tcases)
                        {
                            if (seq.body.Length == 0 && seq.head == t_resolved)
                            {
                                lookAtWorld = false;
                                tcases.Clear();
                                tcases.Add(seq);
                                break;
                            }
                        }

                        // if there is a seprate world, get all of the world
                        // statements that witness t
                        if (world != null && lookAtWorld)
                        {
                            MemoryStore w = new MemoryStore();

                            if (Debug)
                            {
                                Console.Error.WriteLine("Running " + c);
                            }
                            if (Debug)
                            {
                                Console.Error.WriteLine("Euler: Ask World: " + t_resolved);
                            }
                            world.Select(t_resolved, w);
                            foreach (Statement s in w)
                            {
                                if (Debug)
                                {
                                    Console.Error.WriteLine("Euler: World Select Response:  " + s);
                                }
                                Sequent seq = new Sequent(s);
                                tcases.Add(seq);
                            }
                        }
                    }

                    // If there is no evidence or potential evidence (i.e. rules)
                    // for t, then we will dump this QueueItem by not queuing any
                    // subproofs.

                    // Otherwise we try each piece of evidence in turn.
                    foreach (Sequent rl in tcases)
                    {
                        ArrayList g2 = (ArrayList)c.ground.Clone();
                        if (rl.body.Length == 0)
                        {
                            g2.Add(new Ground(rl, new Hashtable()));
                        }

                        QueueItem r = new QueueItem();
                        r.rule   = rl;
                        r.src    = rl;
                        r.ind    = 0;
                        r.parent = c;
                        r.env    = new Hashtable();
                        r.ground = g2;

                        if (unify(t, c.env, rl.head, r.env, true))
                        {
                            QueueItem ep = c;                              // euler path
                            while ((ep = ep.parent) != null)
                            {
                                if (ep.src == c.src && unify(ep.rule.head, ep.env, c.rule.head, c.env, false))
                                {
                                    break;
                                }
                            }
                            if (ep == null)
                            {
                                // It is better for caching subproofs to work an entire proof out before
                                // going on, which means we want to put the new queue item at the
                                // top of the stack.
                                queue.Add(r);
                                c.liveChildren++;
                                if (Debug)
                                {
                                    Console.Error.WriteLine("Euler: Queue from Axiom: " + r);
                                }
                            }
                        }
                    }

                    // If we did not add anything back into the queue for this item, then
                    // we decrement the life of the parent.
                    if (c.liveChildren == 0 && c.parent != null)
                    {
                        decrementLife(c.parent, cached_subproofs);
                    }
                }
            }

            return(evidence);
        }
Exemplo n.º 35
0
        public override void Query(Statement[] graph, SemWeb.Query.QueryOptions options, SelectableSource targetModel, SemWeb.Query.QueryResultSink sink)
        {
            QueryCheckArg(graph);

            // Try to do the inferencing.
            ArrayList evidence = prove(rules, targetModel, graph, -1);

            if (evidence == null)
            {
                return;                 // not provable (in max number of steps, if that were given)
            }
            // Then send the possible bindings to the QueryResultSink.

            // Map variables to indexes.
            Hashtable vars = new Hashtable();

            foreach (Statement s in graph)
            {
                if (s.Subject is Variable && !vars.ContainsKey(s.Subject))
                {
                    vars[s.Subject] = vars.Count;
                }
                if (s.Predicate is Variable && !vars.ContainsKey(s.Predicate))
                {
                    vars[s.Predicate] = vars.Count;
                }
                if (s.Object is Variable && !vars.ContainsKey(s.Object))
                {
                    vars[s.Object] = vars.Count;
                }
            }

            // Prepare the bindings array.
            Variable[] varOrder = new Variable[vars.Count];
            foreach (Variable v in vars.Keys)
            {
                varOrder[(int)vars[v]] = v;
            }

            // Initialize the sink.
            sink.Init(varOrder);

            // Send a binding set for each piece of evidence.
            foreach (EvidenceItem ei in evidence)
            {
                // Write a comment to the results with the actual proof. (nifty actually)
                sink.AddComments(ei.ToProof().ToString());

                // Create the binding array and send it on
                Resource[] variableBindings = new Resource[varOrder.Length];
                foreach (Variable v in vars.Keys)
                {
                    if (ei.env.ContainsKey(v))
                    {
                        variableBindings[(int)vars[v]] = (Resource)ei.env[v];
                    }
                }
                sink.Add(new SemWeb.Query.VariableBindings(varOrder, variableBindings));
            }

            // Close the sink.
            sink.Finished();
        }
Exemplo n.º 36
0
        /// <summary>
        /// Alle mapninger sættes op i den statiske
        /// constructor af objektet.
        /// </summary>
        static ObjectMapper()
        {
            Mapper.CreateMap <AdresseBase, PersonView>()
            .ConvertUsing(s =>
            {
                if (s == null)
                {
                    return(null);
                }
                var mapper = new ObjectMapper();
                if (s is Adressereference)
                {
                    return(null);
                }
                if (s is Person)
                {
                    return(mapper.Map <Person, PersonView>(s as Person));
                }
                throw new DataAccessSystemException(
                    Resource.GetExceptionMessage(ExceptionMessage.CantAutoMapType, s.GetType()));
            });

            Mapper.CreateMap <AdresseBase, FirmaView>()
            .ConvertUsing(s =>
            {
                if (s == null)
                {
                    return(null);
                }
                var mapper = new ObjectMapper();
                if (s is Adressereference)
                {
                    return(null);
                }
                if (s is Firma)
                {
                    return(mapper.Map <Firma, FirmaView>(s as Firma));
                }
                throw new DataAccessSystemException(
                    Resource.GetExceptionMessage(ExceptionMessage.CantAutoMapType, s.GetType()));
            });

            Mapper.CreateMap <AdresseBase, AdresselisteView>()
            .ConvertUsing(s =>
            {
                if (s == null)
                {
                    return(null);
                }
                var mapper = new ObjectMapper();
                if (s is Adressereference)
                {
                    return(null);
                }
                if (s is Person)
                {
                    return(mapper.Map <Person, AdresselisteView>(s as Person));
                }
                if (s is Firma)
                {
                    return(mapper.Map <Firma, AdresselisteView>(s as Firma));
                }
                throw new DataAccessSystemException(
                    Resource.GetExceptionMessage(ExceptionMessage.CantAutoMapType, s.GetType()));
            });

            Mapper.CreateMap <AdresseBase, AdressereferenceView>()
            .ConvertUsing(s =>
            {
                if (s == null)
                {
                    return(null);
                }
                var mapper = new ObjectMapper();
                if (s is Adressereference)
                {
                    return(null);
                }
                if (s is Person)
                {
                    return(mapper.Map <Person, AdressereferenceView>(s as Person));
                }
                if (s is Firma)
                {
                    return(mapper.Map <Firma, AdressereferenceView>(s as Firma));
                }
                throw new DataAccessSystemException(
                    Resource.GetExceptionMessage(ExceptionMessage.CantAutoMapType, s.GetType()));
            });

            Mapper.CreateMap <Person, PersonView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.Adresse1, opt => opt.MapFrom(s => s.Adresse1))
            .ForMember(x => x.Adresse2, opt => opt.MapFrom(s => s.Adresse2))
            .ForMember(x => x.PostnummerBy, opt => opt.MapFrom(s => s.PostnrBy))
            .ForMember(x => x.Telefon, opt => opt.MapFrom(s => s.Telefon))
            .ForMember(x => x.Mobil, opt => opt.MapFrom(s => s.Mobil))
            .ForMember(x => x.Fødselsdato, opt => opt.MapFrom(s => s.Fødselsdato))
            .ForMember(x => x.Adressegruppe, opt => opt.MapFrom(s => s.Adressegruppe))
            .ForMember(x => x.Bekendtskab, opt => opt.MapFrom(s => s.Bekendtskab))
            .ForMember(x => x.Mailadresse, opt => opt.MapFrom(s => s.Mailadresse))
            .ForMember(x => x.Webadresse, opt => opt.MapFrom(s => s.Webadresse))
            .ForMember(x => x.Betalingsbetingelse, opt => opt.MapFrom(s => s.Betalingsbetingelse))
            .ForMember(x => x.Udlånsfrist, opt => opt.MapFrom(s => s.Udlånsfrist))
            .ForMember(x => x.FilofaxAdresselabel, opt => opt.MapFrom(s => s.FilofaxAdresselabel))
            .ForMember(x => x.Firma, opt => opt.MapFrom(s => s.Firma))
            .ForMember(x => x.Bogføringslinjer, opt => opt.MapFrom(s => s.Bogføringslinjer));

            Mapper.CreateMap <Person, AdresselisteView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.Adressegruppe, opt => opt.MapFrom(s => s.Adressegruppe))
            .ForMember(x => x.Adresse1, opt => opt.MapFrom(s => s.Adresse1))
            .ForMember(x => x.Adresse2, opt => opt.MapFrom(s => s.Adresse2))
            .ForMember(x => x.PostnummerBy, opt => opt.MapFrom(s => s.PostnrBy))
            .ForMember(x => x.Telefon, opt => opt.MapFrom(s => s.Telefon))
            .ForMember(x => x.Mobil, opt => opt.MapFrom(s => s.Mobil))
            .ForMember(x => x.Mailadresse, opt => opt.MapFrom(s => s.Mailadresse));

            Mapper.CreateMap <Person, AdressereferenceView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn));

            Mapper.CreateMap <Firma, FirmaView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.Adresse1, opt => opt.MapFrom(s => s.Adresse1))
            .ForMember(x => x.Adresse2, opt => opt.MapFrom(s => s.Adresse2))
            .ForMember(x => x.PostnummerBy, opt => opt.MapFrom(s => s.PostnrBy))
            .ForMember(x => x.Telefon1, opt => opt.MapFrom(s => s.Telefon1))
            .ForMember(x => x.Telefon2, opt => opt.MapFrom(s => s.Telefon2))
            .ForMember(x => x.Telefax, opt => opt.MapFrom(s => s.Telefax))
            .ForMember(x => x.Adressegruppe, opt => opt.MapFrom(s => s.Adressegruppe))
            .ForMember(x => x.Bekendtskab, opt => opt.MapFrom(s => s.Bekendtskab))
            .ForMember(x => x.Mailadresse, opt => opt.MapFrom(s => s.Mailadresse))
            .ForMember(x => x.Webadresse, opt => opt.MapFrom(s => s.Webadresse))
            .ForMember(x => x.Betalingsbetingelse, opt => opt.MapFrom(s => s.Betalingsbetingelse))
            .ForMember(x => x.Udlånsfrist, opt => opt.MapFrom(s => s.Udlånsfrist))
            .ForMember(x => x.FilofaxAdresselabel, opt => opt.MapFrom(s => s.FilofaxAdresselabel))
            .ForMember(x => x.Personer, opt => opt.MapFrom(s => s.Personer))
            .ForMember(x => x.Bogføringslinjer, opt => opt.MapFrom(s => s.Bogføringslinjer));

            Mapper.CreateMap <Firma, AdresselisteView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.Adressegruppe, opt => opt.MapFrom(s => s.Adressegruppe))
            .ForMember(x => x.Adresse1, opt => opt.MapFrom(s => s.Adresse1))
            .ForMember(x => x.Adresse2, opt => opt.MapFrom(s => s.Adresse2))
            .ForMember(x => x.PostnummerBy, opt => opt.MapFrom(s => s.PostnrBy))
            .ForMember(x => x.Telefon, opt => opt.MapFrom(s => s.Telefon1))
            .ForMember(x => x.Mobil, opt => opt.Ignore())
            .ForMember(x => x.Mailadresse, opt => opt.MapFrom(s => s.Mailadresse));

            Mapper.CreateMap <Firma, AdressereferenceView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn));

            Mapper.CreateMap <Postnummer, PostnummerView>()
            .ForMember(x => x.Landekode, opt => opt.MapFrom(s => s.Landekode))
            .ForMember(x => x.Postnummer, opt => opt.MapFrom(s => s.Postnr))
            .ForMember(x => x.Bynavn, opt => opt.MapFrom(s => s.By));

            Mapper.CreateMap <Adressegruppe, AdressegruppeView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.AdressegruppeOswebdb, opt => opt.MapFrom(s => s.AdressegruppeOswebdb));

            Mapper.CreateMap <Betalingsbetingelse, BetalingsbetingelseView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn));

            Mapper.CreateMap <Regnskab, RegnskabView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.Brevhoved, opt => opt.MapFrom(s => s.Brevhoved))
            .ForMember(x => x.Konti, opt => opt.MapFrom(s => s.Konti.OfType <Konto>().ToArray()))
            .ForMember(x => x.Budgetkonti, opt => opt.MapFrom(s => s.Konti.OfType <Budgetkonto>().ToArray()));

            Mapper.CreateMap <Regnskab, RegnskabListeView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.Brevhoved, opt => opt.MapFrom(s => s.Brevhoved));

            Mapper.CreateMap <Konto, KontoView>()
            .ForMember(x => x.Regnskab, opt => opt.MapFrom(s => s.Regnskab))
            .ForMember(x => x.Kontonummer, opt => opt.MapFrom(s => s.Kontonummer))
            .ForMember(x => x.Kontonavn, opt => opt.MapFrom(s => s.Kontonavn))
            .ForMember(x => x.Beskrivelse, opt => opt.MapFrom(s => s.Beskrivelse))
            .ForMember(x => x.Note, opt => opt.MapFrom(s => s.Note))
            .ForMember(x => x.Kontogruppe, opt => opt.MapFrom(s => s.Kontogruppe))
            .ForMember(x => x.Kreditoplysninger, opt => opt.MapFrom(s => s.Kreditoplysninger))
            .ForMember(x => x.Bogføringslinjer, opt => opt.MapFrom(s => s.Bogføringslinjer));

            Mapper.CreateMap <Konto, KontoListeView>()
            .ForMember(x => x.Regnskab, opt => opt.MapFrom(s => s.Regnskab))
            .ForMember(x => x.Kontonummer, opt => opt.MapFrom(s => s.Kontonummer))
            .ForMember(x => x.Kontonavn, opt => opt.MapFrom(s => s.Kontonavn))
            .ForMember(x => x.Beskrivelse, opt => opt.MapFrom(s => s.Beskrivelse))
            .ForMember(x => x.Note, opt => opt.MapFrom(s => s.Note))
            .ForMember(x => x.Kontogruppe, opt => opt.MapFrom(s => s.Kontogruppe));

            Mapper.CreateMap <Budgetkonto, BudgetkontoView>()
            .ForMember(x => x.Regnskab, opt => opt.MapFrom(s => s.Regnskab))
            .ForMember(x => x.Kontonummer, opt => opt.MapFrom(s => s.Kontonummer))
            .ForMember(x => x.Kontonavn, opt => opt.MapFrom(s => s.Kontonavn))
            .ForMember(x => x.Beskrivelse, opt => opt.MapFrom(s => s.Beskrivelse))
            .ForMember(x => x.Note, opt => opt.MapFrom(s => s.Note))
            .ForMember(x => x.Budgetkontogruppe, opt => opt.MapFrom(s => s.Budgetkontogruppe))
            .ForMember(x => x.Budgetoplysninger, opt => opt.MapFrom(s => s.Budgetoplysninger))
            .ForMember(x => x.Bogføringslinjer, opt => opt.MapFrom(s => s.Bogføringslinjer));

            Mapper.CreateMap <Budgetkonto, BudgetkontoListeView>()
            .ForMember(x => x.Regnskab, opt => opt.MapFrom(s => s.Regnskab))
            .ForMember(x => x.Kontonummer, opt => opt.MapFrom(s => s.Kontonummer))
            .ForMember(x => x.Kontonavn, opt => opt.MapFrom(s => s.Kontonavn))
            .ForMember(x => x.Beskrivelse, opt => opt.MapFrom(s => s.Beskrivelse))
            .ForMember(x => x.Note, opt => opt.MapFrom(s => s.Note))
            .ForMember(x => x.Budgetkontogruppe, opt => opt.MapFrom(s => s.Budgetkontogruppe));

            Mapper.CreateMap <Kreditoplysninger, KreditoplysningerView>()
            .ForMember(x => x.År, opt => opt.MapFrom(s => s.År))
            .ForMember(x => x.Måned, opt => opt.MapFrom(s => s.Måned))
            .ForMember(x => x.Kredit, opt => opt.MapFrom(s => s.Kredit));

            Mapper.CreateMap <Budgetoplysninger, BudgetoplysningerView>()
            .ForMember(x => x.År, opt => opt.MapFrom(s => s.År))
            .ForMember(x => x.Måned, opt => opt.MapFrom(s => s.Måned))
            .ForMember(x => x.Indtægter, opt => opt.MapFrom(s => s.Indtægter))
            .ForMember(x => x.Udgifter, opt => opt.MapFrom(s => s.Udgifter));

            Bogføringslinje.SætAutoCalculate(false);
            Mapper.CreateMap <Bogføringslinje, BogføringslinjeView>()
            .ForMember(x => x.Løbenummer, opt => opt.MapFrom(s => s.Løbenummer))
            .ForMember(x => x.Dato, opt => opt.MapFrom(s => s.Dato))
            .ForMember(x => x.Bilag, opt => opt.MapFrom(s => s.Bilag))
            .ForMember(x => x.Konto, opt => opt.MapFrom(s => s.Konto))
            .ForMember(x => x.Tekst, opt => opt.MapFrom(s => s.Tekst))
            .ForMember(x => x.Budgetkonto, opt => opt.MapFrom(s => s.Budgetkonto))
            .ForMember(x => x.Debit, opt => opt.MapFrom(s => s.Debit))
            .ForMember(x => x.Kredit, opt => opt.MapFrom(s => s.Kredit))
            .ForMember(x => x.Adresse, opt => opt.MapFrom(s => s.Adresse));

            Mapper.CreateMap <Kontogruppe, KontogruppeView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.KontogruppeType, opt => opt.MapFrom(s => s.KontogruppeType));

            Mapper.CreateMap <Budgetkontogruppe, BudgetkontogruppeView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn));

            Mapper.CreateMap <Brevhoved, BrevhovedreferenceView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn));

            Mapper.CreateMap <Brevhoved, BrevhovedView>()
            .ForMember(x => x.Nummer, opt => opt.MapFrom(s => s.Nummer))
            .ForMember(x => x.Navn, opt => opt.MapFrom(s => s.Navn))
            .ForMember(x => x.Linje1, opt => opt.MapFrom(s => s.Linje1))
            .ForMember(x => x.Linje2, opt => opt.MapFrom(s => s.Linje2))
            .ForMember(x => x.Linje3, opt => opt.MapFrom(s => s.Linje3))
            .ForMember(x => x.Linje4, opt => opt.MapFrom(s => s.Linje4))
            .ForMember(x => x.Linje5, opt => opt.MapFrom(s => s.Linje5))
            .ForMember(x => x.Linje6, opt => opt.MapFrom(s => s.Linje6))
            .ForMember(x => x.Linje7, opt => opt.MapFrom(s => s.Linje7))
            .ForMember(x => x.CvrNr, opt => opt.MapFrom(s => s.CvrNr));

            Mapper.AssertConfigurationIsValid();
        }
Exemplo n.º 37
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="resourceRoot"></param>
        /// <param name="adapter"></param>
        /// <param name="node"></param>
        /// <param name="newValue"></param>
        /// <param name="oldValue"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public OpenEhrToFhirAdapterBase SetFhirValue(Resource resourceRoot, OpenEhrToFhirAdapterBase adapter, Component node, object newValue, object oldValue = null, int index = int.MinValue)
        {
            var points = 1;

            // setting a not null property which is inside a list
            if (oldValue != null && index != int.MinValue)
            {
                var setListItemMethod = oldValue.GetType().GetMethod("set_Item");

                if (setListItemMethod != null)
                {
                    setListItemMethod.Invoke(oldValue, new[] { index, newValue });

                    adapter.SuccessfulMappingCount += points;

                    //Log.Info($"Mapped {GetType().Name} from {OpenEhrFieldPath} to {node.InnerNetPath(adapter.Mappings)} & yielded +{points} for total of {adapter.SuccessfulMappingCount} successes for this adapter.");
                }
            }
            // setting a null property which is not in a list
            else
            {
                var childPathFromParent = node.InnerNetPath(adapter.Mappings);

                object parentObject;

                if (childPathFromParent.LastIndexOf('.') < 0)
                {
                    parentObject = resourceRoot;
                }
                else
                {
                    var parentObjectPath = childPathFromParent.Remove(childPathFromParent.LastIndexOf('.'));
                    parentObject = resourceRoot.GetPropertyValue(parentObjectPath);
                }

                // get the property name that we want to set
                var childProperty = childPathFromParent.Split('.').Last();

                // set codeable concept in parent object which isn't at the root resource i.e. Resource.Property[0].AnotherProperty[1]
                if (ReflectionHelper.SetValue(parentObject, childProperty, newValue))
                {
                    adapter.SuccessfulMappingCount += points;
                }
                // set primitive data type in parent object which isn't at the root resource i.e. Resource.Property[0].AnotherProperty
                else if (ReflectionHelper.SetValue(parentObject, childProperty, ((Composite)node).Children[0].Name))
                {
                    adapter.SuccessfulMappingCount += points;
                }
                // set primitive data type in parent object which is at the root resource i.e. Resource.Property
                else
                {
                    if (ReflectionHelper.SetValue(resourceRoot, childProperty, ((Composite)node).Children[0].Name))
                    {
                        adapter.SuccessfulMappingCount += points;
                    }
                    else
                    {
                        //Log.Error($"Failed to map attribute with mapping {OpenEhrFieldPath} to {FhirFieldPath}.");
                    }
                }

                //Log.Info($"Mapped {GetType().Name} from {OpenEhrFieldPath} to {childPathFromParent} & yielded +{points} for total of {adapter.SuccessfulMappingCount} successes for this adapter.");
            }

            return(adapter);
        }
 private KeyValuePair <string, List <dynamic> > GetAuthorProperty(Resource resource)
 {
     return(resource.Properties.SingleOrDefault(p => p.Key == Graph.Metadata.Constants.Resource.Author));
 }
 public void AddResource(Resource newResource)
 {
     _resourceRepository.AddResource(newResource);
 }
Exemplo n.º 40
0
 protected override Texture ImportCore(Stream stream, string filename = null)
 {
     return(Resource.Load <Texture>(stream, true));
 }
Exemplo n.º 41
0
 public WorldNode(Resource resource)
 {
     Resource = resource;
 }
Exemplo n.º 42
0
 protected override void PopulateView()
 {
     foreach (int file in Resource.EnumerateFiles())
     {
         Nodes.Add(( TreeNode )ResourceWrapperFactory.GetResourceWrapper($"Sound{file:D2}.adx", Resource.OpenFile(file)));
     }
 }
Exemplo n.º 43
0
 public ResourcesFileTreeNode(Resource er)
     : base(er)
 {
     this.LazyLoading = true;
 }
Exemplo n.º 44
0
 private static extern string Internal_GetPath(Resource resource);
        public void TestVMOperations()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                EnsureClientsInitialized(context);

                ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);

                // Create resource group
                string         rg1Name            = ComputeManagementTestUtilities.GenerateName(TestPrefix) + 1;
                string         as1Name            = ComputeManagementTestUtilities.GenerateName("as");
                string         storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
                VirtualMachine inputVM1;

                try
                {
                    // Create Storage Account, so that both the VMs can share it
                    var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);

                    VirtualMachine vm1 = CreateVM(rg1Name, as1Name, storageAccountOutput, imageRef, out inputVM1);
                    m_CrpClient.VirtualMachines.Start(rg1Name, vm1.Name);
                    m_CrpClient.VirtualMachines.Redeploy(rg1Name, vm1.Name);
                    m_CrpClient.VirtualMachines.Restart(rg1Name, vm1.Name);

                    var runCommandImput = new RunCommandInput()
                    {
                        CommandId = "RunPowerShellScript",
                        Script    = new List <string>()
                        {
                            "param(",
                            "    [string]$arg1,",
                            "    [string]$arg2",
                            ")",
                            "echo This is a sample script with parameters $arg1 $arg2"
                        },
                        Parameters = new List <RunCommandInputParameter>()
                        {
                            new RunCommandInputParameter("arg1", "value1"),
                            new RunCommandInputParameter("arg2", "value2"),
                        }
                    };
                    RunCommandResult result = m_CrpClient.VirtualMachines.RunCommand(rg1Name, vm1.Name, runCommandImput);
                    Assert.NotNull(result);
                    Assert.NotNull(result.Value);
                    Assert.True(result.Value.Count > 0);

                    m_CrpClient.VirtualMachines.PowerOff(rg1Name, vm1.Name);
                    m_CrpClient.VirtualMachines.Deallocate(rg1Name, vm1.Name);
                    m_CrpClient.VirtualMachines.Generalize(rg1Name, vm1.Name);

                    VirtualMachine ephemeralVM;
                    string         as2Name = as1Name + "_ephemeral";
                    CreateVM(rg1Name, as2Name, storageAccountName, imageRef, out ephemeralVM, hasManagedDisks: true, hasDiffDisks: true, vmSize: VirtualMachineSizeTypes.StandardDS5V2,
                             osDiskStorageAccountType: StorageAccountTypes.StandardLRS, dataDiskStorageAccountType: StorageAccountTypes.StandardLRS);
                    m_CrpClient.VirtualMachines.Reimage(rg1Name, ephemeralVM.Name, tempDisk: true);
                    var captureParams = new VirtualMachineCaptureParameters
                    {
                        DestinationContainerName = ComputeManagementTestUtilities.GenerateName(TestPrefix),
                        VhdPrefix     = ComputeManagementTestUtilities.GenerateName(TestPrefix),
                        OverwriteVhds = true
                    };

                    var captureResponse = m_CrpClient.VirtualMachines.Capture(rg1Name, vm1.Name, captureParams);

                    Assert.NotNull(captureResponse);
                    Assert.True(captureResponse.Resources.Count > 0);
                    string resource = captureResponse.Resources[0].ToString();
                    Assert.Contains(captureParams.DestinationContainerName.ToLowerInvariant(), resource.ToLowerInvariant());
                    Assert.Contains(captureParams.VhdPrefix.ToLowerInvariant(), resource.ToLowerInvariant());

                    Resource template = JsonConvert.DeserializeObject <Resource>(resource);
                    string   imageUri = template.Properties.StorageProfile.OSDisk.Image.Uri;
                    Assert.False(string.IsNullOrEmpty(imageUri));

                    // Create 3rd VM from the captured image
                    // TODO : Provisioning Time-out Issues
                    VirtualMachine inputVM2;
                    string         as3Name = as1Name + "b";
                    VirtualMachine vm3     = CreateVM(rg1Name, as3Name, storageAccountOutput, imageRef, out inputVM2,
                                                      vm =>
                    {
                        vm.StorageProfile.ImageReference = null;
                        vm.StorageProfile.OsDisk.Image   = new VirtualHardDisk {
                            Uri = imageUri
                        };
                        vm.StorageProfile.OsDisk.Vhd.Uri = vm.StorageProfile.OsDisk.Vhd.Uri.Replace(".vhd", "copy.vhd");
                        vm.StorageProfile.OsDisk.OsType  = OperatingSystemTypes.Windows;
                    }, false, false);
                    Assert.True(vm3.StorageProfile.OsDisk.Image.Uri == imageUri);
                }
                finally
                {
                    // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
                    // of the test to cover deletion. CSM does persistent retrying over all RG resources.
                    m_ResourcesClient.ResourceGroups.Delete(rg1Name);
                }
            }
        }
Exemplo n.º 46
0
 private static extern void Internal_Create(Resource resource, string path);
        protected static void Initialize()
        {
            ExceptionHandlerMock = new Mock <IExceptionHandler>();
            Handler = new Handler(ExceptionHandlerMock.Object);
            RemarkRepositoryMock    = new Mock <IRemarkRepository>();
            RemarkServiceClientMock = new Mock <IRemarkServiceClient>();
            RemarkCacheMock         = new Mock <IRemarkCache>();
            RemarkResolvedHandler   = new RemarkResolvedHandler(Handler,
                                                                RemarkRepositoryMock.Object,
                                                                RemarkServiceClientMock.Object,
                                                                RemarkCacheMock.Object);

            User = new User
            {
                UserId = UserId,
                Name   = "TestUser"
            };
            Event  = new RemarkResolved(Guid.NewGuid(), Resource.Create("test", "test"), UserId, RemarkId);
            Author = new RemarkUser
            {
                UserId = UserId,
                Name   = "TestUser"
            };
            Category = new RemarkCategory
            {
                Id   = Guid.NewGuid(),
                Name = "Test"
            };
            Location = new Location
            {
                Address     = "address",
                Coordinates = new[] { 1.0, 1.0 },
                Type        = "point"
            };
            Remark = new Remark
            {
                Id          = RemarkId,
                Author      = Author,
                Category    = Category,
                CreatedAt   = CreatedAt,
                Description = "test",
                Location    = Location,
                Photos      = new List <File>()
            };
            var resolvedRemark = new Remark
            {
                Id          = RemarkId,
                Author      = Author,
                Category    = Category,
                CreatedAt   = CreatedAt,
                Description = "test",
                Location    = Location,
                State       = new RemarkState
                {
                    State = "resolved",
                    User  = new RemarkUser
                    {
                        UserId = UserId,
                    }
                },
                Photos = new List <File>()
            };

            RemarkServiceClientMock
            .Setup(x => x.GetAsync <Remark>(RemarkId))
            .ReturnsAsync(resolvedRemark);
            RemarkRepositoryMock.Setup(x => x.GetByIdAsync(Moq.It.IsAny <Guid>()))
            .ReturnsAsync(Remark);
        }
Exemplo n.º 48
0
 /// <summary>
 /// Updates a resource that is already in the library.
 /// </summary>
 /// <param name="resource">Resource to save.</param>
 public static void Save(Resource resource)
 {
     Internal_Save(resource);
 }
Exemplo n.º 49
0
 private static extern void Internal_Save(Resource resource);
Exemplo n.º 50
0
 public string Hash(Resource resource)
 {
     return(IO.CheckSum(ExecutionContext.MapPath(resource.ExtractToPath)));
 }
Exemplo n.º 51
0
 /// <summary>
 /// Returns a path to a resource stored in the project library.
 /// </summary>
 /// <param name="resource">Resource to find the path for.</param>
 /// <returns>Path to relative to the project library resources folder if resource was found, null otherwise.
 ///          </returns>
 public static string GetPath(Resource resource)
 {
     return(Internal_GetPath(resource));
 }
Exemplo n.º 52
0
 // TODO: optimisations and recursion
 /// <returns>A concise bounded description containing all properties the KnowledgeBase knows about the subject if the subject is known, otherwise an empty description.</returns>
 public ResourceDescription GetDescriptionOf(Resource theResource, TripleStore store)
 {
     return(GetDescriptionOf(theResource, store, new Hashtable()));
 }
Exemplo n.º 53
0
 /// <summary>
 /// Registers a new resource in the library.
 /// </summary>
 /// <param name="resource">Resource instance to add to the library. A copy of the resource will be saved at the
 ///                        provided path.</param>
 /// <param name="path">Path where where to store the resource. Absolute or relative to the resources folder.</param>
 public static void Create(Resource resource, string path)
 {
     Internal_Create(resource, path);
 }
 public override void AddResource(Resource resource)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 55
0
        public ResourceAdded(Resource newResource)
        {
            Palladia.Core.Ensure.ArgumentIsNotNull(newResource, nameof(newResource));

            NewResource = newResource;
        }
Exemplo n.º 56
0
        public bool Open(IFilter imageFilter)
        {
            Stream stream = imageFilter.GetDataForkStream();

            if (stream.Length < 512)
            {
                return(false);
            }

            stream.Seek(-Marshal.SizeOf <UdifFooter>(), SeekOrigin.End);
            byte[] footerB = new byte[Marshal.SizeOf <UdifFooter>()];

            stream.Read(footerB, 0, Marshal.SizeOf <UdifFooter>());
            footer = Marshal.ByteArrayToStructureBigEndian <UdifFooter>(footerB);

            if (footer.signature != UDIF_SIGNATURE)
            {
                stream.Seek(0, SeekOrigin.Begin);
                footerB = new byte[Marshal.SizeOf <UdifFooter>()];

                stream.Read(footerB, 0, Marshal.SizeOf <UdifFooter>());
                footer = Marshal.ByteArrayToStructureBigEndian <UdifFooter>(footerB);

                if (footer.signature != UDIF_SIGNATURE)
                {
                    throw new Exception("Unable to find UDIF signature.");
                }

                DicConsole.VerboseWriteLine("Found obsolete UDIF format.");
            }

            DicConsole.DebugWriteLine("UDIF plugin", "footer.signature = 0x{0:X8}", footer.signature);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.version = {0}", footer.version);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.headerSize = {0}", footer.headerSize);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.flags = {0}", footer.flags);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.runningDataForkOff = {0}", footer.runningDataForkOff);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.dataForkOff = {0}", footer.dataForkOff);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.dataForkLen = {0}", footer.dataForkLen);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.rsrcForkOff = {0}", footer.rsrcForkOff);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.rsrcForkLen = {0}", footer.rsrcForkLen);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.segmentNumber = {0}", footer.segmentNumber);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.segmentCount = {0}", footer.segmentCount);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.segmentId = {0}", footer.segmentId);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.dataForkChkType = {0}", footer.dataForkChkType);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.dataForkLen = {0}", footer.dataForkLen);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.dataForkChk = 0x{0:X8}", footer.dataForkChk);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.plistOff = {0}", footer.plistOff);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.plistLen = {0}", footer.plistLen);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.masterChkType = {0}", footer.masterChkType);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.masterChkLen = {0}", footer.masterChkLen);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.masterChk = 0x{0:X8}", footer.masterChk);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.imageVariant = {0}", footer.imageVariant);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.sectorCount = {0}", footer.sectorCount);
            DicConsole.DebugWriteLine("UDIF plugin", "footer.reserved1 is empty? = {0}",
                                      ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved1));
            DicConsole.DebugWriteLine("UDIF plugin", "footer.reserved2 is empty? = {0}",
                                      ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved2));
            DicConsole.DebugWriteLine("UDIF plugin", "footer.reserved3 is empty? = {0}",
                                      ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved3));
            DicConsole.DebugWriteLine("UDIF plugin", "footer.reserved4 is empty? = {0}",
                                      ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved4));

            // Block chunks and headers
            List <byte[]> blkxList = new List <byte[]>();

            chunks = new Dictionary <ulong, BlockChunk>();

            bool fakeBlockChunks = false;

            byte[] vers = null;

            if (footer.plistLen == 0 && footer.rsrcForkLen != 0)
            {
                DicConsole.DebugWriteLine("UDIF plugin", "Reading resource fork.");
                byte[] rsrcB = new byte[footer.rsrcForkLen];
                stream.Seek((long)footer.rsrcForkOff, SeekOrigin.Begin);
                stream.Read(rsrcB, 0, rsrcB.Length);

                ResourceFork rsrc = new ResourceFork(rsrcB);

                if (!rsrc.ContainsKey(BLOCK_OS_TYPE))
                {
                    throw new
                          ImageNotSupportedException("Image resource fork doesn't contain UDIF block chunks. Please fill an issue and send it to us.");
                }

                Resource blkxRez = rsrc.GetResource(BLOCK_OS_TYPE);

                if (blkxRez == null)
                {
                    throw new
                          ImageNotSupportedException("Image resource fork doesn't contain UDIF block chunks. Please fill an issue and send it to us.");
                }

                if (blkxRez.GetIds().Length == 0)
                {
                    throw new
                          ImageNotSupportedException("Image resource fork doesn't contain UDIF block chunks. Please fill an issue and send it to us.");
                }

                blkxList.AddRange(blkxRez.GetIds().Select(blkxId => blkxRez.GetResource(blkxId)));

                Resource versRez = rsrc.GetResource(0x76657273);

                if (versRez != null)
                {
                    vers = versRez.GetResource(versRez.GetIds()[0]);
                }
            }
            else if (footer.plistLen != 0)
            {
                DicConsole.DebugWriteLine("UDIF plugin", "Reading property list.");
                byte[] plistB = new byte[footer.plistLen];
                stream.Seek((long)footer.plistOff, SeekOrigin.Begin);
                stream.Read(plistB, 0, plistB.Length);

                DicConsole.DebugWriteLine("UDIF plugin", "Parsing property list.");
                NSDictionary plist = (NSDictionary)XmlPropertyListParser.Parse(plistB);
                if (plist == null)
                {
                    throw new Exception("Could not parse property list.");
                }

                if (!plist.TryGetValue(RESOURCE_FORK_KEY, out NSObject rsrcObj))
                {
                    throw new Exception("Could not retrieve resource fork.");
                }

                NSDictionary rsrc = (NSDictionary)rsrcObj;

                if (!rsrc.TryGetValue(BLOCK_KEY, out NSObject blkxObj))
                {
                    throw new Exception("Could not retrieve block chunks array.");
                }

                NSObject[] blkx = ((NSArray)blkxObj).GetArray();

                foreach (NSDictionary part in blkx.Cast <NSDictionary>())
                {
                    if (!part.TryGetValue("Name", out _))
                    {
                        throw new Exception("Could not retrieve Name");
                    }

                    if (!part.TryGetValue("Data", out NSObject dataObj))
                    {
                        throw new Exception("Could not retrieve Data");
                    }

                    blkxList.Add(((NSData)dataObj).Bytes);
                }

                if (rsrc.TryGetValue("vers", out NSObject versObj))
                {
                    NSObject[] versArray = ((NSArray)versObj).GetArray();
                    if (versArray.Length >= 1)
                    {
                        vers = ((NSData)versArray[0]).Bytes;
                    }
                }
            }
            else
            {
                // Obsolete read-only UDIF only prepended the header and then put the image without any kind of block references.
                // So let's falsify a block chunk
                BlockChunk bChnk = new BlockChunk
                {
                    length  = footer.dataForkLen,
                    offset  = footer.dataForkOff,
                    sector  = 0,
                    sectors = footer.sectorCount,
                    type    = CHUNK_TYPE_COPY
                };
                imageInfo.Sectors = footer.sectorCount;
                chunks.Add(bChnk.sector, bChnk);
                buffersize      = 2048 * SECTOR_SIZE;
                fakeBlockChunks = true;
            }

            if (vers != null)
            {
                Version version = new Version(vers);

                string release = null;
                string dev     = null;
                string pre     = null;

                string major = $"{version.MajorVersion}";
                string minor = $".{version.MinorVersion / 10}";
                if (version.MinorVersion % 10 > 0)
                {
                    release = $".{version.MinorVersion % 10}";
                }
                switch (version.DevStage)
                {
                case Version.DevelopmentStage.Alpha:
                    dev = "a";
                    break;

                case Version.DevelopmentStage.Beta:
                    dev = "b";
                    break;

                case Version.DevelopmentStage.PreAlpha:
                    dev = "d";
                    break;
                }

                if (dev == null && version.PreReleaseVersion > 0)
                {
                    dev = "f";
                }

                if (dev != null)
                {
                    pre = $"{version.PreReleaseVersion}";
                }

                imageInfo.ApplicationVersion = $"{major}{minor}{release}{dev}{pre}";
                imageInfo.Application        = version.VersionString;
                imageInfo.Comments           = version.VersionMessage;

                if (version.MajorVersion == 3)
                {
                    imageInfo.Application = "ShrinkWrap™";
                }
                else if (version.MajorVersion == 6)
                {
                    imageInfo.Application = "DiskCopy";
                }
            }
            else
            {
                imageInfo.Application = "DiskCopy";
            }

            DicConsole.DebugWriteLine("UDIF plugin", "Image application = {0} version {1}", imageInfo.Application,
                                      imageInfo.ApplicationVersion);

            imageInfo.Sectors = 0;
            if (!fakeBlockChunks)
            {
                if (blkxList.Count == 0)
                {
                    throw new
                          ImageNotSupportedException("Could not retrieve block chunks. Please fill an issue and send it to us.");
                }

                buffersize = 0;

                foreach (byte[] blkxBytes in blkxList)
                {
                    BlockHeader bHdr  = new BlockHeader();
                    byte[]      bHdrB = new byte[Marshal.SizeOf <BlockHeader>()];
                    Array.Copy(blkxBytes, 0, bHdrB, 0, Marshal.SizeOf <BlockHeader>());
                    bHdr = Marshal.ByteArrayToStructureBigEndian <BlockHeader>(bHdrB);

                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.signature = 0x{0:X8}", bHdr.signature);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.version = {0}", bHdr.version);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.sectorStart = {0}", bHdr.sectorStart);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.sectorCount = {0}", bHdr.sectorCount);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.dataOffset = {0}", bHdr.dataOffset);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.buffers = {0}", bHdr.buffers);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.descriptor = 0x{0:X8}", bHdr.descriptor);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved1 = {0}", bHdr.reserved1);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved2 = {0}", bHdr.reserved2);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved3 = {0}", bHdr.reserved3);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved4 = {0}", bHdr.reserved4);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved5 = {0}", bHdr.reserved5);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved6 = {0}", bHdr.reserved6);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.checksumType = {0}", bHdr.checksumType);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.checksumLen = {0}", bHdr.checksumLen);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.checksum = 0x{0:X8}", bHdr.checksum);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.chunks = {0}", bHdr.chunks);
                    DicConsole.DebugWriteLine("UDIF plugin", "bHdr.reservedChk is empty? = {0}",
                                              ArrayHelpers.ArrayIsNullOrEmpty(bHdr.reservedChk));

                    if (bHdr.buffers > buffersize)
                    {
                        buffersize = bHdr.buffers * SECTOR_SIZE;
                    }

                    for (int i = 0; i < bHdr.chunks; i++)
                    {
                        BlockChunk bChnk  = new BlockChunk();
                        byte[]     bChnkB = new byte[Marshal.SizeOf <BlockChunk>()];
                        Array.Copy(blkxBytes, Marshal.SizeOf <BlockHeader>() + Marshal.SizeOf <BlockChunk>() * i, bChnkB,
                                   0, Marshal.SizeOf <BlockChunk>());
                        bChnk = Marshal.ByteArrayToStructureBigEndian <BlockChunk>(bChnkB);

                        DicConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].type = 0x{1:X8}", i, bChnk.type);
                        DicConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].comment = {1}", i, bChnk.comment);
                        DicConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].sector = {1}", i, bChnk.sector);
                        DicConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].sectors = {1}", i, bChnk.sectors);
                        DicConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].offset = {1}", i, bChnk.offset);
                        DicConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].length = {1}", i, bChnk.length);

                        if (bChnk.type == CHUNK_TYPE_END)
                        {
                            break;
                        }

                        imageInfo.Sectors += bChnk.sectors;

                        // Chunk offset is relative
                        bChnk.sector += bHdr.sectorStart;
                        bChnk.offset += bHdr.dataOffset;

                        switch (bChnk.type)
                        {
                        // TODO: Handle comments
                        case CHUNK_TYPE_COMMNT: continue;

                        // TODO: Handle compressed chunks
                        case CHUNK_TYPE_KENCODE:
                            throw new
                                  ImageNotSupportedException("Chunks compressed with KenCode are not yet supported.");

                        case CHUNK_TYPE_LZH:
                            throw new
                                  ImageNotSupportedException("Chunks compressed with LZH are not yet supported.");

                        case CHUNK_TYPE_LZFSE:
                            throw new
                                  ImageNotSupportedException("Chunks compressed with lzfse are not yet supported.");
                        }

                        if (bChnk.type > CHUNK_TYPE_NOCOPY && bChnk.type < CHUNK_TYPE_COMMNT ||
                            bChnk.type > CHUNK_TYPE_LZFSE && bChnk.type < CHUNK_TYPE_END)
                        {
                            throw new ImageNotSupportedException($"Unsupported chunk type 0x{bChnk.type:X8} found");
                        }

                        if (bChnk.sectors > 0)
                        {
                            chunks.Add(bChnk.sector, bChnk);
                        }
                    }
                }
            }

            sectorCache           = new Dictionary <ulong, byte[]>();
            chunkCache            = new Dictionary <ulong, byte[]>();
            currentChunkCacheSize = 0;
            imageStream           = stream;

            imageInfo.CreationTime         = imageFilter.GetCreationTime();
            imageInfo.LastModificationTime = imageFilter.GetLastWriteTime();
            imageInfo.MediaTitle           = Path.GetFileNameWithoutExtension(imageFilter.GetFilename());
            imageInfo.SectorSize           = SECTOR_SIZE;
            imageInfo.XmlMediaType         = XmlMediaType.BlockMedia;
            imageInfo.MediaType            = MediaType.GENERIC_HDD;
            imageInfo.ImageSize            = imageInfo.Sectors * SECTOR_SIZE;
            imageInfo.Version = $"{footer.version}";

            imageInfo.Cylinders       = (uint)(imageInfo.Sectors / 16 / 63);
            imageInfo.Heads           = 16;
            imageInfo.SectorsPerTrack = 63;

            return(true);
        }
Exemplo n.º 57
0
        public void MergeFrom(LogEntry other)
        {
            if (other == null)
            {
                return;
            }
            if (other.LogName.Length != 0)
            {
                LogName = other.LogName;
            }
            if (other.resource_ != null)
            {
                if (resource_ == null)
                {
                    resource_ = new global::Google.Api.MonitoredResource();
                }
                Resource.MergeFrom(other.Resource);
            }
            if (other.timestamp_ != null)
            {
                if (timestamp_ == null)
                {
                    timestamp_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
                }
                Timestamp.MergeFrom(other.Timestamp);
            }
            if (other.Severity != 0)
            {
                Severity = other.Severity;
            }
            if (other.InsertId.Length != 0)
            {
                InsertId = other.InsertId;
            }
            if (other.httpRequest_ != null)
            {
                if (httpRequest_ == null)
                {
                    httpRequest_ = new global::Google.Cloud.Logging.Type.HttpRequest();
                }
                HttpRequest.MergeFrom(other.HttpRequest);
            }
            labels_.Add(other.labels_);
            if (other.operation_ != null)
            {
                if (operation_ == null)
                {
                    operation_ = new global::Google.Cloud.Logging.V2.LogEntryOperation();
                }
                Operation.MergeFrom(other.Operation);
            }
            if (other.Trace.Length != 0)
            {
                Trace = other.Trace;
            }
            if (other.sourceLocation_ != null)
            {
                if (sourceLocation_ == null)
                {
                    sourceLocation_ = new global::Google.Cloud.Logging.V2.LogEntrySourceLocation();
                }
                SourceLocation.MergeFrom(other.SourceLocation);
            }
            switch (other.PayloadCase)
            {
            case PayloadOneofCase.ProtoPayload:
                ProtoPayload = other.ProtoPayload;
                break;

            case PayloadOneofCase.TextPayload:
                TextPayload = other.TextPayload;
                break;

            case PayloadOneofCase.JsonPayload:
                JsonPayload = other.JsonPayload;
                break;
            }
        }
        public void Preprocess(List <XmlAttribute> expressionAttributes, List <Resource> resources, List <IdViewObject> viewElements)
        {
            // Create all properties for viewElements
            foreach (IdViewObject viewElement in viewElements)
            {
                Tuple <CodeMemberField, CodeMemberProperty> result = CodeGeneratorHelper.GenerateProxyProperty(viewElement.Id, viewElement.TypeName, new CodeMethodInvokeExpression(GetFindViewByIdReference(viewElement.TypeName), CodeGeneratorHelper.GetAndroidResourceReference(ResourcePart.Id, viewElement.Id)));
                Fields.Add(result.Item1);
                Properties.Add(result.Item2);
            }

            // Generate property for ILocalizationService LocalizationService
            CodePropertyReferenceExpression localizationServiceReference = CreateLocalizationServiceProperty();

            // Eval all expressions
            List <ExpressionContainer> expressions = (from attribute in expressionAttributes
                                                      let expressionResult = EvaluateExpression(attribute.Value)
                                                                             where expressionResult != null
                                                                             select new ExpressionContainer
            {
                Expression = expressionResult,
                TargetObject = attribute.AttachedId,
                TargetField = attribute.LocalName,
                IsTargetingResource = false,
            }).ToList();

            // Affect a property name to all resources and check if some has expression as attribute value
            foreach (Resource res in resources)
            {
                res.PropertyName = NameGeneratorHelper.GetResourceName();
                foreach (KeyValuePair <string, string> propertyItem in res.Properties.Where(propertyItem => ParsingHelper.IsExpressionValue(propertyItem.Value)).ToList())
                {
                    res.Properties.Remove(propertyItem.Key);

                    Expression expr = EvaluateExpression(propertyItem.Value);
                    if (expr != null)
                    {
                        if (CheckCorrectExpressionInResource(expr))
                        {
                            Log.LogError("Expression {0} is invalid in a resource context (you cannot use binding)", propertyItem.Value);
                        }
                        else
                        {
                            expressions.Add(new ExpressionContainer
                            {
                                Expression          = expr,
                                TargetObject        = res.PropertyName,
                                TargetField         = propertyItem.Key,
                                IsTargetingResource = true,
                            });
                        }
                    }
                }
            }

            // Check if all resources are declared and filter those we need
            Dictionary <string, Resource> neededResource = new Dictionary <string, Resource>();
            List <string> resourceKeys = expressions.SelectMany(x => GetUsedResources(x.Expression)).Distinct().ToList();

            foreach (string key in resourceKeys)
            {
                Resource res = resources.FirstOrDefault(x => key.Equals(x.Key, StringComparison.InvariantCultureIgnoreCase));
                if (res == null)
                {
                    Log.LogError("Resource with key {0} does not exists", key);
                }
                else
                {
                    neededResource.Add(key, res);
                }
            }


            // Go through all binding expression and find those where we need to declare implicit resources
            // Will also remove all Template & TemplateSelector fields in BindingExpression
            // to only have a fully prepared adapter
            foreach (Expression bindingExpression in expressions.SelectMany(expression => GetBindingExpressions(expression.Expression)).ToList())
            {
                if (bindingExpression.Has(BindingExpression.TEMPLATE))
                {
                    // create a template selector
                    string templateSelectorKey          = NameGeneratorHelper.GetResourceKey();
                    string templateSelectorPropertyName = NameGeneratorHelper.GetResourceName();
                    neededResource.Add(templateSelectorKey, new Resource(templateSelectorKey)
                    {
                        PropertyName    = templateSelectorPropertyName,
                        ResourceElement = null,
                        Type            = Configuration.DefaultTemplateSelector
                    });
                    expressions.Add(new ExpressionContainer
                    {
                        Expression          = bindingExpression[BindingExpression.TEMPLATE],
                        TargetField         = Configuration.DefaultTemplateSelectorField,
                        TargetObject        = templateSelectorPropertyName,
                        IsTargetingResource = true,
                    });
                    bindingExpression.Remove(BindingExpression.TEMPLATE);

                    ResourceExpression templateSelectorResourceExpression = new ResourceExpression();
                    templateSelectorResourceExpression.Add(ResourceExpression.KEY, new TextExpression
                    {
                        Value = templateSelectorKey
                    });
                    bindingExpression.Add(BindingExpression.TEMPLATE_SELECTOR, templateSelectorResourceExpression);
                }

                if (bindingExpression.Has(BindingExpression.TEMPLATE_SELECTOR))
                {
                    // create an adapter
                    string adapterKey  = NameGeneratorHelper.GetResourceKey();
                    string adapterName = NameGeneratorHelper.GetResourceName();
                    neededResource.Add(adapterKey, new Resource(adapterKey)
                    {
                        PropertyName    = adapterName,
                        ResourceElement = null,
                        Type            = Configuration.DefaultAdapter
                    });
                    expressions.Add(new ExpressionContainer
                    {
                        Expression          = bindingExpression[BindingExpression.TEMPLATE_SELECTOR],
                        TargetField         = Configuration.DefaultAdapterField,
                        TargetObject        = adapterName,
                        IsTargetingResource = true,
                    });
                    bindingExpression.Remove(BindingExpression.TEMPLATE_SELECTOR);
                    ResourceExpression adapterResourceExpression = new ResourceExpression();
                    adapterResourceExpression.Add(ResourceExpression.KEY, new TextExpression
                    {
                        Value = adapterKey
                    });
                    bindingExpression.Add(BindingExpression.ADAPTER, adapterResourceExpression);
                }
            }

            // In order to check if all adapter are not used more than once since we need them to be unique target
            Dictionary <string, bool> usedAdapter = new Dictionary <string, bool>();

            foreach (ExpressionContainer expression in expressions.Where(x => x.Expression.IsOfType(ExpressionType.Binding)).ToList())
            {
                Expression bindingExpression = expression.Expression;
                if (bindingExpression.Has(BindingExpression.ADAPTER))
                {
                    // expression in Adapter could only be Resource (since it's an android platform specific things, a binding expression would not have any sense)
                    Expression resourceExpression = bindingExpression[BindingExpression.ADAPTER];
                    string     adapterKey         = resourceExpression.GetValue(ResourceExpression.KEY);
                    Resource   adapterResource    = neededResource[adapterKey];

                    if (usedAdapter.ContainsKey(adapterKey))
                    {
                        Log.LogError("The adapter with key {0} is used more than once which could lead to issue, you need one adapter per use !", adapterKey);
                    }
                    else
                    {
                        usedAdapter.Add(adapterKey, true);
                    }

                    // remove the adapter property
                    bindingExpression.Remove(BindingExpression.ADAPTER);

                    // store old target info
                    string oldTargetField  = expression.TargetField;
                    string oldTargetObject = expression.TargetObject;
                    bool   oldTargetType   = expression.IsTargetingResource;

                    // retarget the binding expression to be targeted to Adapter.Collection
                    expression.TargetField         = "Collection";
                    expression.TargetObject        = adapterResource.PropertyName;
                    expression.IsTargetingResource = false;                     //TODO : false for debug mode only, need to see what we can do about that ?

                    // add a new expression to target the old object/field couple and affect the adapter with the resource expression
                    expressions.Add(new ExpressionContainer
                    {
                        IsTargetingResource = oldTargetType,
                        TargetField         = oldTargetField,
                        TargetObject        = oldTargetObject,
                        Expression          = resourceExpression,
                    });
                }
            }

            // Create all properties for resources
            Dictionary <string, CodePropertyReferenceExpression> resourceReferences = CreatePropertiesForResources(neededResource.Values);

            // Generate all properties to handle CommandParameter and retarget all expressions if needed
            GenerateCommandParameterProperties(expressions);

            // Create a setup resources method to initalize resources with all {Resource ...} and {Translation ...} expressions
            List <ExpressionContainer> translationExpressions        = expressions.Where(x => x.Expression.IsOfType(ExpressionType.Translation)).ToList();
            List <ExpressionContainer> expressionsTargetingResources = expressions.Where(x => x.IsTargetingResource && x.Expression.IsOfType(ExpressionType.Resource)).ToList();
            List <ExpressionContainer> resourceExpressions           = expressions.Where(x => !x.IsTargetingResource && x.Expression.IsOfType(ExpressionType.Resource)).ToList();
            List <ExpressionContainer> bindingExpressions            = expressions.Where(x => !x.IsTargetingResource && x.Expression.IsOfType(ExpressionType.Binding)).ToList();

            CodeMethodReferenceExpression assignTranslationMethodReference = CreateAssignTranslationMethod(translationExpressions, localizationServiceReference);
            CodeMethodReferenceExpression setupResourcesReference          = CreateSetupResourcesMethod(expressionsTargetingResources, resourceReferences);
            CodeMethodReferenceExpression setupResourceForViewElement      = CreateSetupResourceForViewElementMethod(resourceExpressions, resourceReferences);

            CreateBindingOverrideMethod(bindingExpressions, localizationServiceReference, resourceReferences, assignTranslationMethodReference, setupResourcesReference, setupResourceForViewElement);
        }
 public override Resource UpdateResource(Resource resource)
 {
     throw new NotImplementedException();
 }