public static async Task <APObject> CreateNewAsync(APObject apObject = null)
        {
            Console.WriteLine("Creating new apObject");
            var     now = DateTime.Now;
            dynamic obj = apObject ?? new APObject("object");

            if (apObject == null)
            {
                obj.intfield      = 1;
                obj.decimalfield  = 10.0m;
                obj.datefield     = "2012-12-20";
                obj.datetimefield = now.ToString("o");
                obj.stringfield   = "string value";
                obj.textfield     = "text value";
                obj.boolfield     = false;
                obj.geofield      = "11.5,12.5";
                obj.listfield     = "a";
                obj.SetAttribute("attr1", "value1");
                obj.SetAttribute("attr2", "value2");
            }

            CreateObjectResponse response = null;

            response = await(new CreateObjectRequest()
            {
                Object      = obj,
                Environment = Environment.Sandbox
            }).ExecuteAsync();
            ApiHelper.EnsureValidResponse(response);
            Assert.IsNotNull(response.Object);
            Console.WriteLine("Created apObject id {0}", response.Object.Id);
            return(response.Object);
        }
Esempio n. 2
0
        public async Task DeleteObjectAsyncTest()
        {
            // Create apObject
            var     now = DateTime.Now;
            dynamic obj = new APObject("object");

            obj.intfield      = 1;
            obj.decimalfield  = 10.0m;
            obj.datefield     = "2012-12-20";
            obj.datetimefield = now.ToString("o");
            obj.stringfield   = "string value";
            obj.textfield     = "text value";
            obj.boolfield     = false;
            obj.geofield      = "11.5,12.5";
            obj.listfield     = "a";
            obj.SetAttribute("attr1", "value1");
            obj.SetAttribute("attr2", "value2");

            CreateObjectResponse response = null;

            response = await(new CreateObjectRequest()
            {
                Object = obj
            }).ExecuteAsync();
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Status);
            Assert.IsTrue(response.Status.IsSuccessful);
            Assert.IsNotNull(response.Object);
            Console.WriteLine("Created apObject id {0}", response.Object.Id);
            Console.WriteLine("Time taken: {0} seconds", response.TimeTaken);

            // Delete the apObject
            var deleteObjectResponse = await(new DeleteObjectRequest()
            {
                Id   = response.Object.Id,
                Type = response.Object.Type
            }).ExecuteAsync();

            Assert.IsNotNull(deleteObjectResponse, "Delete apObjectr response is null.");
            Assert.IsTrue(deleteObjectResponse.Status.IsSuccessful == true,
                          deleteObjectResponse.Status.Message ?? "Delete apObject operation failed.");

            // Try get the deleted apObject
            var getObjectResponse = await(
                new GetObjectRequest()
            {
                Id   = response.Object.Id,
                Type = response.Object.Type
            }).ExecuteAsync();

            Assert.IsNotNull(getObjectResponse, "Get apObject response is null.");
            Assert.IsNull(getObjectResponse.Object, "Should not be able to get a deleted apObject.");
            Assert.IsTrue(getObjectResponse.Status.Code == "404", "Error code expected was not 404.");
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            CreateObjectResponse response = new CreateObjectResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("ObjectIdentifier", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    response.ObjectIdentifier = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
Esempio n. 4
0
        public async Task FindAllObjectAsyncFixture()
        {
            // Create atleast one apObject
            var     now = DateTime.Now;
            dynamic obj = new APObject("object");

            obj.intfield      = 66666;
            obj.decimalfield  = 98765.0m;
            obj.datefield     = "2012-12-20";
            obj.datetimefield = now.ToString("o");
            obj.stringfield   = "Frank";
            obj.textfield     = "Frand Sinatra was an amazing singer.";
            obj.boolfield     = false;
            obj.geofield      = "11.5,12.5";
            obj.listfield     = "a";


            CreateObjectResponse response = null;

            response = await(new CreateObjectRequest()
            {
                Object = obj
            }).ExecuteAsync();

            ApiHelper.EnsureValidResponse(response);

            // Find all objects
            var findRequest = new FindAllObjectsRequest()
            {
                Type = "object"
            };
            var findResponse = await findRequest.ExecuteAsync();

            ApiHelper.EnsureValidResponse(findResponse);
            findResponse.Objects.ForEach(x => Console.WriteLine("Found apObject id {0}.", x.Id));
            Assert.IsNotNull(findResponse.PagingInfo);
            Assert.IsTrue(findResponse.PagingInfo.PageNumber == 1);
            Assert.IsTrue(findResponse.PagingInfo.TotalRecords > 0);
            Console.WriteLine("Paging info => pageNumber: {0}, pageSize: {1}, totalRecords: {2}",
                              findResponse.PagingInfo.PageNumber,
                              findResponse.PagingInfo.PageSize,
                              findResponse.PagingInfo.TotalRecords);
        }
Esempio n. 5
0
        public async Task CreateObjectAsyncTest()
        {
            // Create obj
            var     now = DateTime.Now;
            dynamic obj = ObjectHelper.NewInstance();

            CreateObjectResponse response = null;


            response = await(new CreateObjectRequest()
            {
                Object      = obj,
                Environment = TestConfiguration.Environment
            }).ExecuteAsync();

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Status);
            Assert.IsTrue(response.Status.IsSuccessful);
            Assert.IsNotNull(response.Object);
            Console.WriteLine("Created obj id {0}", response.Object.Id);
            Console.WriteLine("Time taken {0} seconds", response.TimeTaken);
        }
Esempio n. 6
0
        private static void ScanLocal(string apiKey, string url, string username, string password)
        {
            //In i-doit einloggen, und Konstanten abfragen.
            Idoit idoit = null;

            try
            {
                idoit = Idoit.Login(apiKey, url, username, password);
            }
            catch (JsonRpcException rpcException)
            {
                Console.WriteLine("-> Unable to connect to i-doit:");
                Console.WriteLine(rpcException.Error.message);
                return;
            }
            catch (WebException we)
            {
                Console.WriteLine("-> Unable to connect to i-doit:");
                Console.WriteLine(string.Format("-> {1}", null, we.Message));
                return;
            }

            VersionResponse vr            = idoit.Version();
            Version         parsedVersion = new Version(vr.version);

            if (parsedVersion < new Version(1, 4, 8))
            {
                Console.WriteLine("-> This Program requires i-doit 1.4.8");
                idoit.Logout();
                return;
            }

            ConstantsResponse   constants = idoit.Constants();
            ObjectTypesResponse ot        = idoit.ObjectTypes();

            //Die i-doit API erlaubt es uns nicht Objekttypen programmatisch anzulegen oder zu modifizieren.
            //Von daher testen die drei nächsten Absätze, ob es möglich ist Notebooks einzutragen, falls nicht, wird der Anwender aufgefordert,
            //den Objekttyp anzulegen.
            if (!constants.objectTypes.ContainsValue("Notebook"))
            {
                Console.WriteLine("-> Could not find object type \"Notebook\" in your i-doit setup!");
                Console.WriteLine(
                    "-> Please create it by creating it in the Object type configuration in the i-doit web interface.");
                idoit.Logout();
                return;
            }
            ObjectTypeCategoriesResponse notebookCats = null;

            foreach (var m in constants.objectTypes)
            {
                if (m.Value.Equals("Notebook"))
                {
                    notebookCats = idoit.ObjectTypeCategories(m.Key);
                    break;
                }
            }
            foreach (Category c in new Category[] { new Drive(), new Model(), new SoundCard(), new Cpu(), new Memory(), new SoftwareAssignment(), })
            {
                if (!notebookCats.TestForConstant(c.Constant))
                {
                    Console.WriteLine("-> Could not find category \"{0}\" in object type \"Notebook\" in your i-doit setup!", c.DisplayName);
                    Console.WriteLine(
                        "-> Please add it by editing the Object type configuration in the i-doit web interface.");
                    idoit.Logout();
                    return;
                }
            }

            //Rauskriegen, auf was für einem OS wir laufen
            IOperatingSystemHandler osHandler;

            osHandler = DetectOperatingSystem();
            if (osHandler == null)
            {
                idoit.Logout();
                return;
            }

            //Herausfinden was wir für eine Art von PC sind...
            ObjectType targetObjectType = null;

            if (osHandler.IsLaptop())
            {
                //Ich gehe mal davon aus, das Notebooks nicht als Server-artige Geräte verwendet werden.
                targetObjectType = ot.GetObjectTypeFromTitle("Notebook");
            }
            else if (osHandler.IsVirtualMachine())
            {
                if (osHandler.IsServer())
                {
                    targetObjectType = ot.GetObjectTypeFromTitle("Virtual server");
                }
                else
                {
                    targetObjectType = ot.GetObjectTypeFromTitle("Virtual client");
                }
            }
            else
            {
                if (osHandler.IsVirtualMachineHost())
                {
                    targetObjectType = ot.GetObjectTypeFromTitle("Virtual host");
                }
                else if (osHandler.IsServer())
                {
                    targetObjectType = ot.GetObjectTypeFromTitle("Server");
                }
                else
                {
                    targetObjectType = ot.GetObjectTypeFromTitle("Desktop");
                }
            }

            ObjectTypeCategoriesResponse targetObjectTypeCategories = idoit.ObjectTypeCategories(targetObjectType);

            //Unseren Rechner aus der Datenbank rausfischen, oder ihn eintragen...
            CmdbObject        objectId;
            List <CmdbObject> o = idoit.FindObjects(Environment.MachineName, targetObjectType);

            if (o.Count > 1)
            {
                Console.WriteLine(
                    "Es gibt mehr als einen {0} der {1} heißt - bitte physikalisch beheben, dann in i-doit manuell löschen!");
                idoit.Logout();
                return;
            }
            else if (o.Count == 0)
            {
                CreateObjectResponse createObjectResponse = idoit.CreateCmdbObject(targetObjectType,
                                                                                   Environment.MachineName);
                if (!createObjectResponse.success)
                {
                    Console.WriteLine("-> {0}", createObjectResponse.message);
                    Console.WriteLine("-> Konnte das Objekt nicht anlegen, bitte in den Logs von i-doit nachsehen...");
                    idoit.Logout();
                    return;
                }
                objectId    = new CmdbObject();
                objectId.id = createObjectResponse.id;
            }
            else
            {
                objectId = o[0];
            }


            //CPU Hersteller
            IdoitEnumerator cpuManufactorEnumerator        = idoit.Dialog(new Cpu().Constant, "manufacturer");
            bool            cpuManufactorEnumeratorChanged = false;

            foreach (string manufac in Config.cpuManufactors)    //Liste der CPU Hersteller von: https://de.wikipedia.org/wiki/CPUID
            {
                if (!cpuManufactorEnumerator.TestTitle(manufac))
                {
                    idoit.DialogEdit(new Cpu(), "manufacturer", manufac);
                    cpuManufactorEnumeratorChanged = true;
                }
            }
            if (cpuManufactorEnumeratorChanged)
            {
                cpuManufactorEnumerator = idoit.Dialog(new Cpu().Constant, "manufacturer");
            }

            IdoitEnumerator cpuModelEnumator          = idoit.Dialog(new Cpu().Constant, "type");
            bool            cpuModelEnumeratorChanged = false;

            foreach (string model in Config.cpuModels)   //TODO: mehr Modell IDs rauskriegen...
            {
                if (!cpuModelEnumator.TestTitle(model))
                {
                    idoit.DialogEdit(new Cpu(), "type", model);
                    cpuModelEnumeratorChanged = true;
                }
            }
            if (cpuModelEnumeratorChanged)
            {
                cpuModelEnumator = idoit.Dialog(new Cpu().Constant, "type");
            }



            //CPU
            if (targetObjectTypeCategories.TestForConstant(new Cpu()))
            {
                List <Cpu> cpus = new List <Cpu>();
                cpus.AddRange(osHandler.GetCpu());
                foreach (Cpu c in cpus)
                {
                    string modelCmp = c.title.Replace("(TM)", "");
                    foreach (string manufac in Config.cpuManufactors)
                    {
                        if (c.cpuid.Contains(manufac))
                        {
                            c.manufacturer = cpuManufactorEnumerator.FindTitleLike(manufac);
                            break;
                        }
                    }
                    foreach (EnumInfo ei in cpuModelEnumator)
                    {
                        if (modelCmp.Contains(ei.title))
                        {
                            c.type = ei.id;
                            break;
                        }
                    }
                }
                List <Cpu> cpusInDb = idoit.CategoryRead <Cpu>(objectId.id, cpus[0]);
                idoit.SyncList(objectId, cpusInDb, cpus);
            }
            else
            {
                Console.WriteLine("-> According to i-doit {0}s do not have {1}s", targetObjectType.title, "CPU");
            }

            //Physikalische Laufwerke
            if (targetObjectTypeCategories.TestForConstant(new StorageDevice()))
            {
                List <StorageDevice> storageDevices     = osHandler.GetStorageDevices();
                List <StorageDevice> storageDevicesInDb = idoit.CategoryRead <StorageDevice>(objectId.id,
                                                                                             new StorageDevice());
                idoit.SyncList(objectId, storageDevicesInDb, storageDevices);
            }
            else
            {
                Console.WriteLine("-> According to i-doit {0}s do not have {1}s", targetObjectType.title, "Storage Device");
            }

            //Logische Laufwerke
            if (targetObjectTypeCategories.TestForConstant(new Drive()))
            {
                List <Drive> drives     = osHandler.GetDrives(idoit);
                List <Drive> drivesInDb = idoit.CategoryRead <Drive>(objectId.id, new Drive());
                idoit.SyncList(objectId, drivesInDb, drives);
            }
            else
            {
                Console.WriteLine("-> According to i-doit {0}s do not have {1}s", targetObjectType.title, "Drive");
            }

            //RAM Hersteller
            IdoitEnumerator ramManufactorEnumerator = idoit.Dialog(new Memory().Constant, "manufacturer");

            foreach (KeyValuePair <string, string> kv in Config.ramManufactors)
            {
                if (!ramManufactorEnumerator.TestTitle(kv.Value))
                {
                    idoit.DialogEdit(new Memory(), "manufacturer", kv.Value);
                    ramManufactorEnumerator = idoit.Dialog(new Memory().Constant, "manufacturer");
                }
            }

            //RAMs
            if (targetObjectTypeCategories.TestForConstant(new Memory()))
            {
                List <Memory> rams     = osHandler.GetMemoryBanks(idoit);
                List <Memory> ramsInDb = idoit.CategoryRead <Memory>(objectId.id, new Memory());
                idoit.SyncList(objectId, ramsInDb, rams);
            }
            else
            {
                Console.WriteLine("-> According to i-doit {0}s do not have {1}s", targetObjectType.title, "Memory");
            }

            //Als nächstes wollen wir Software Assignments eintragen, dazu stellen wir zunächst sicher, dass jede installierte Software auch in i-doit bekannt ist.
            if (targetObjectTypeCategories.TestForConstant(new SoftwareAssignment()))
            {
                ObjectType          softwareObjectType    = ot.GetObjectTypeFromTitle("Application");
                List <SoftwareInfo> softwares             = osHandler.GetSoftware();
                List <CmdbObject>   softwareKnown         = idoit.FindObjects(softwareObjectType);
                IdoitEnumerator     softwareManufacturers = idoit.Dialog(new Applications().Constant, "manufacturer");
                foreach (SoftwareInfo si in softwares)
                {
                    if (softwareKnown.Find(x => x.title.Equals(si.productName)) == null)
                    {
                        //Software in i-doit bekannt machen.
                        int          newSoftwareId           = idoit.CreateCmdbObject(softwareObjectType, si.productName).id;
                        CmdbObject   newSoftware             = idoit.GetCmdbObject(newSoftwareId);
                        Applications newSoftwareApplications = new Applications();
                        newSoftwareApplications.install_path = si.installPath;
                        newSoftwareApplications.release      = si.version;

                        //Software-Entwickler in i-doit bekannt machen.
                        if (!string.IsNullOrEmpty(si.manufacterer))
                        {
                            bool manufacturerKnown = softwareManufacturers.TestTitle(si.manufacterer);
                            if (!manufacturerKnown)
                            {
                                idoit.DialogEditSpecific(newSoftwareApplications, "manufacturer", si.manufacterer);
                                softwareManufacturers = idoit.Dialog(new Applications().Constant, "manufacturer");
                            }
                            newSoftwareApplications.manufacturer = softwareManufacturers.FindTitleLike(si.manufacterer);
                        }

                        //Software-Info schreiben.
                        idoit.CategoryCreate(newSoftware, newSoftwareApplications);

                        softwareKnown = idoit.FindObjects(softwareObjectType);
                        //direkt nochmal abfragen, um Doubletten auszuschließen.
                    }
                }

                //Liste von Software Assignments erzeugen:
                List <SoftwareAssignment> assignments =
                    softwares.ConvertAll(
                        x => new SoftwareAssignment(softwareKnown.Find(y => y.title.Equals(x.productName)).id));

                //Das Betriebssystem ist nach der Logik von i-doit auch ein Software Assignment. Von daher müssen wir uns nun um Betriebssystem-Infos kümmern:
                string            uname = osHandler.uname();
                ObjectType        operatingSystemObjectType = ot.GetObjectTypeFromTitle("Operating System");
                List <CmdbObject> knownOperatingSystems     = idoit.FindObjects(operatingSystemObjectType);
                CmdbObject        operatingSystemCmdbObject = null;
                operatingSystemCmdbObject = knownOperatingSystems.Find((x) => x.title.Equals(uname));
                if (operatingSystemCmdbObject == null)
                {
                    operatingSystemCmdbObject = new CmdbObject(idoit.CreateCmdbObject(operatingSystemObjectType, uname));
                }
                SoftwareAssignment osSoftwareAssignment = new SoftwareAssignment();
                osSoftwareAssignment.application = operatingSystemCmdbObject.id;

                //Dem Software Assignment für das Betriebssystem ggf. eine Lizenz nahe bringen.
                if (osHandler.OperatingSystemNeedsLicense())    //sowas braucht bekanntlich nur Windows... :D
                {
                    string cdKey = osHandler.OperatingSystemLicensingInfo();
                    if (!string.IsNullOrEmpty(cdKey))
                    {
                        string licenseName = string.Format("{0}-Lizenz für {1}", uname, Environment.MachineName);

                        ObjectType        licenseObjectType = ot.GetObjectTypeFromTitle("Licenses");
                        List <CmdbObject> knownLicenses     = idoit.FindObjects(licenseObjectType);
                        CmdbObject        licenseCmdbObject = null;
                        operatingSystemCmdbObject = knownLicenses.Find((x) => x.title.Equals(licenseName));
                        if (operatingSystemCmdbObject == null)
                        {
                            //Neues Objekt für die Lizenz anlegen:
                            licenseCmdbObject = new CmdbObject(idoit.CreateCmdbObject(licenseObjectType, licenseName));
                            //...und die Lizenz im Feld "Description" hinterlegen.
                            Global licenseGlobal = idoit.CategoryRead <Global>(licenseCmdbObject.id, new Global())[0];
                            licenseGlobal.description = cdKey;

                            try
                            {
                                idoit.CategoryCreate <Global>(licenseCmdbObject,
                                                              licenseGlobal); //Gut zu wissen: Wenn eine Kategorie nur einmal in einem Objekt vorhanden ist, wird

                                //sie durch Create überschrieben...
                            }
                            catch (JsonRpcException rpcException)
                            {
                                Console.WriteLine(rpcException.Error.ToString());
                            }

                            try
                            {
                                idoit.CategoryUpdate(licenseCmdbObject,
                                                     licenseGlobal); //Gut zu wissen: Wenn eine Kategorie nur einmal in einem Objekt vorhanden ist, wird

                                //sie durch Create überschrieben...
                            }
                            catch (JsonRpcException rpcException)
                            {
                                Console.WriteLine(rpcException.Error.data.ToString());
                            }
                        }
                    }
                    //osSoftwareAssignment.assigned_license = licenseCmdbObject.id;     //kann nicht direkt zugewiesen werden, gibt eine Exception dass irgendwelche SQL-Constraints nicht erfüllt sind...

                    //TODO: Das selbe hier für Office und Konsorten machen...
                }
                assignments.Add(osSoftwareAssignment);

                List <SoftwareAssignment> assignmentsInDb = idoit.CategoryRead <SoftwareAssignment>(objectId.id,
                                                                                                    new SoftwareAssignment());
                idoit.SyncList(objectId, assignmentsInDb, assignments);
            }
            else
            {
                Console.WriteLine("-> According to i-doit {0}s do not have {1}s", targetObjectType.title, "Software assignment");
            }

            //Samba Shares abgleichen
            if (targetObjectTypeCategories.TestForConstant(new Share()))
            {
                List <Share> shares     = osHandler.GetShares();
                List <Share> sharesInDb = idoit.CategoryRead <Share>(objectId.id, new Share());
                idoit.SyncList(objectId, sharesInDb, shares);
            }
            else
            {
                Console.WriteLine("-> According to i-doit {0}s do not have {1}s", targetObjectType.title, "Share");
            }

            //Soundkarten abgleichen
            if (targetObjectTypeCategories.TestForConstant(new SoundCard()))
            {
                List <SoundCard> soundCards     = osHandler.GetSoundCards(idoit);
                List <SoundCard> soundCardsInDb = osHandler.GetSoundCards(idoit);
                idoit.SyncList(objectId, soundCardsInDb, soundCards);
            }
            else
            {
                Console.WriteLine("-> According to i-doit {0}s do not have {1}s", targetObjectType.title, "Sound card");
            }

            idoit.Logout();
        }