Example #1
0
        public Manufacturer GetManufacturer(NameValueCollection appSettings, SnipeItApi snipe)
        {
            string       manufacturer       = GetOutputVariable("Win32_ComputerSystem.Manufacturer");
            Manufacturer systemManufacturer = new Manufacturer(manufacturer);

            return(systemManufacturer);
        }
Example #2
0
        /// <summary>
        /// Synchronizes the specified manufacturer details with an existing
        /// <c>Snipt.It</c> manufacturer or creates one if no manufacturer exists.
        /// </summary>
        /// <param name="snipe">
        ///     The <see cref="SnipeItApi"/> instance used to access the <c>Snipt.It</c>
        ///     web API.
        /// </param>
        /// <param name="manufacturer">
        ///     The manufacturer name.
        /// </param>
        /// <returns>
        ///      The resulting <c>Snipt.It</c> <see cref="Manufacturer"/>.
        /// </returns>
        public static Manufacturer SyncManufacturer(this SnipeItApi snipe, string manufacturer)
        {
            // Validate parameters.
            if (snipe == null)
            {
                throw new ArgumentNullException("snipe");
            }
            if (String.IsNullOrWhiteSpace(manufacturer))
            {
                throw new ArgumentNullException("manufacturer");
            }

            Manufacturer snipeManufacturer = snipe.ManufacturerManager.FindAll(new SearchFilter {
                Search = manufacturer
            })?.Rows.FirstOrDefault();

            if (snipeManufacturer == null)
            {
                snipeManufacturer = new Manufacturer()
                {
                    Name = manufacturer
                };
                var response = snipe.ManufacturerManager.Create(snipeManufacturer);
                snipeManufacturer = snipe.ManufacturerManager.FindAll(new SearchFilter {
                    Search = manufacturer
                })?.Rows.FirstOrDefault();
            }
            return(snipeManufacturer);
        }
Example #3
0
        public Asset GetAsset(NameValueCollection appSettings, SnipeItApi snipe)
        {
            string systemName   = GetOutputVariable("Win32_ComputerSystem.Name");
            string serialNumber = GetOutputVariable("Win32_ComputerSystemProduct.IdentifyingNumber");
            string macAddress   = GetOutputVariable("Win32_NetworkAdapter.MACAddress");
            Dictionary <string, string> customFields = new Dictionary <string, string>();

            customFields.Add("_snipeit_mac_address_1", macAddress);
            string warrantyMonths = appSettings["WarrantyMonths"];

            bool isInteractive           = false;
            bool interactiveParseSuccess = Boolean.TryParse(appSettings["Interactive"], out isInteractive);

            if (interactiveParseSuccess && isInteractive)
            {
                Console.WriteLine("Enter the computer name: ");
                systemName = Console.ReadLine();
            }

            Asset currentComputer = new SnipeSharp.Endpoints.Models.Asset
            {
                Company        = null,
                AssetTag       = appSettings["AssetTagPrefix"] + "-" + serialNumber, // <-- to be implemented.. somehow, somewhere
                Model          = null,
                StatusLabel    = null,
                RtdLocation    = null,
                Name           = systemName,
                Serial         = serialNumber,
                WarrantyMonths = warrantyMonths,
                CustomFields   = customFields,
            };

            return(currentComputer);
        }
Example #4
0
        /// <inheritdoc />
        protected override void EndProcessing()
        {
            WriteWarning("This software is considered pre-alpha and is not ready for production use. Proceed with caution, and use at your own risk.");
            var instance = new SnipeItApi {
                Token = this.Token,
                Uri   = this.Uri
            };

            if (!SkipConnectionCheck)
            {
                if (!instance.TestConnection())
                {
                    throw new ApiErrorException($"Could not validate a connection to Snipe-IT at Uri \"{Uri}\".");
                }
            }
            if (Force && ApiHelper.HasApiInstance)
            {
                ApiHelper.Reset();
            }
            ApiHelper.Instance = instance;
            ApiHelper.DisableLookupVerification = DisableLookupVerification;

            if (PassThru)
            {
                WriteObject(ApiHelper.Instance);
            }
        }
        public void CheckApiTokenAndUrl_NoUrlInApiSettings_ThrowException()
        {
            SnipeItApi snipe = new SnipeItApi();

            snipe.ApiSettings.ApiToken = "xxxxx";
            snipe.ReqManager.CheckApiTokenAndUrl();
        }
Example #6
0
        /// <summary>
        /// Synchronizes the specified model details with an existing
        /// <c>Snipt.It</c> category or creates a new one if no category exists.
        /// </summary>
        /// <param name="snipe">
        ///     The <see cref="SnipeItApi"/> instance used to access the <c>Snipt.It</c>
        ///     web API.
        /// </param>
        /// <param name="categoryName">
        ///     The category name.
        /// </param>
        /// <param name="categoryType">
        ///     The category type.
        /// </param>
        /// <returns>
        ///     The resulting <c>Snipt.It</c> <see cref="Category"/>.
        /// </returns>
        public static Category SyncCategory(
            this SnipeItApi snipe,
            string categoryName,
            string categoryType)
        {
            // Validate parameters.
            if (snipe == null)
            {
                throw new ArgumentNullException("snipe");
            }
            if (String.IsNullOrWhiteSpace(categoryName))
            {
                throw new ArgumentNullException("assetCategory");
            }

            Category snipeCategory = snipe.CategoryManager.FindAll(new SearchFilter {
                Search = categoryName
            })?.Rows.FirstOrDefault();

            if (snipeCategory == null)
            {
                snipeCategory = new Category()
                {
                    Name = categoryName, Type = categoryType
                };
                var response = snipe.CategoryManager.Create(snipeCategory);
                snipeCategory = snipe.CategoryManager.FindAll(new SearchFilter {
                    Search = categoryName
                })?.Rows.FirstOrDefault();
            }
            return(snipeCategory);
        }
Example #7
0
        public StatusLabel GetStatusLabel(NameValueCollection appSettings, SnipeItApi snipe)
        {
            string      defaultLabel       = appSettings["DefaultStatusLabel"];
            StatusLabel defaultStatusLabel = new StatusLabel(defaultLabel);

            return(defaultStatusLabel);
        }
        public void CheckApiTokenAndUrl_NoTokenInApiSettings_ThrowException()
        {
            SnipeItApi snipe = new SnipeItApi();

            snipe.ApiSettings.BaseUrl = new Uri("http://google.com");
            snipe.ReqManager.CheckApiTokenAndUrl();
        }
Example #9
0
        public Company GetCompany(NameValueCollection appSettings, SnipeItApi snipe)
        {
            string  companyName    = appSettings["Company"];
            Company currentCompany = new Company(companyName);

            return(currentCompany);
        }
Example #10
0
        /// <summary>
        /// Synchronizes the specified system's details with the configured <c>Snipe.It</c>
        /// system.
        /// </summary>
        private void SyncHostNameDetails(string hostName)
        {
            // Single Device.
            SnipeItApi snipe =
                SnipeApiExtensions.CreateClient(
                    snipeApiUrl,
                    snipeApiToken);

            if (!String.IsNullOrWhiteSpace(hostName))
            {
                Log.Information($"Retrieving asset details for {hostName}");
                try
                {
                    var asset      = AssetDescriptor.Create(hostName);
                    var components = ComponentDescriptor.Create(hostName);
                    try
                    {
                        Log.Information($"Synchronizing asset details for {hostName}");
                        // The current version of the SnipeSharp API has mapping issues causing the response not de serializing.
                        snipe.SyncAssetWithCompoments(asset, components);
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"Failed to sync asset details for {hostName}");
                        Log.Error(ex.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Log.Error($"Failed to retrieve asset details for {hostName}");
                    Log.Error(ex.ToString());
                }
            }
        }
Example #11
0
        public Location GetLocation(NameValueCollection appSettings, SnipeItApi snipe)
        {
            string   assetLocation   = this.Values["Location"];
            Location currentLocation = new Location(assetLocation);

            return(currentLocation);
        }
Example #12
0
        public static void SyncAssetWithCompoments(
            this SnipeItApi snipe,
            AssetDescriptor assetDetails,
            IEnumerable <ComponentDescriptor> components)
        {
            if (snipe == null)
            {
                throw new ArgumentNullException("snipe");
            }
            if (assetDetails == null)
            {
                throw new ArgumentNullException("assetDetails");
            }
            if (components == null)
            {
                throw new ArgumentNullException("components");
            }

            var snipeAsset = snipe.SyncAsset(assetDetails);

            //// The Snipe API does not have the capability to check-out components.
            //var snipeComponents = snipe.SyncComponents(components);
            //foreach (var item in snipeComponents)
            //{
            //    snipe.CheckOutComponent(snipeAsset.Serial, item.Serial);
            //}
        }
Example #13
0
        /// <summary>
        /// Synchronizes the specified collection of <see cref="ComponentDescriptor"/>
        /// details with a <c>Snipt.It</c> component or creates one if not asset matching
        /// the specified serial exists.
        /// </summary>
        /// <param name="snipe">
        ///      The <see cref="SnipeItApi"/> instance used to access the <c>Snipt.It</c>
        ///      web API.
        /// </param>
        /// <param name="components">
        ///      The collection of <see cref="ComponentDescriptor"/>s describing the
        ///      components details.
        /// </param>
        /// <returns>
        ///     The resulting <c>Snipt.It</c> collection of <see cref="Component"/>s.
        /// </returns>
        public static IEnumerable <Component> SyncComponents(
            this SnipeItApi snipe,
            IEnumerable <ComponentDescriptor> components)
        {
            // Validate parameters.
            if (snipe == null)
            {
                throw new ArgumentNullException("snipe");
            }
            if (components == null)
            {
                throw new ArgumentNullException("components");
            }


            List <Component> results = new List <Component>();

            if (components.Any())
            {
                foreach (var item in components)
                {
                    results.Add(snipe.SyncComponent(item));
                }
            }

            return(results);
        }
Example #14
0
        public static void syncAsset(SnipeItApi snipe, SnipeSharp.Endpoints.Models.Asset currentAsset)
        {
            try
            {
                SnipeSharp.Endpoints.SearchFilters.SearchFilter assetFilter = new SnipeSharp.Endpoints.SearchFilters.SearchFilter()
                {
                    Search = currentAsset.AssetTag
                };

                SnipeSharp.Endpoints.Models.Asset foundAsset = snipe.AssetManager.FindOne(assetFilter);
                if (foundAsset != null && foundAsset.AssetTag == currentAsset.AssetTag)
                {
                    Trace.WriteLine("Asset already exists in db. Not added.");
                }
                else
                {
                    var response = snipe.AssetManager.Create(currentAsset);
                    Trace.WriteLine("Response recieved from SnipeIT server after attempting to add asset: ");
                    Trace.WriteLine(response);
                }
            } catch (Exception e)
            {
                Trace.WriteLine("Exception encountered while adding asset: " + e.ToString());
            }
        }
Example #15
0
        /// <summary>
        /// Synchronizes the specified system's details with the configured <c>Snipe.It</c>
        /// system.
        /// </summary>
        private void SyncHostNameDetails(string hostName)
        {
            // Single Device.
            SnipeItApi snipe =
                SnipeApiExtensions.CreateClient(
                    ConfigurationManager.AppSettings["Snipe:ApiAddress"],
                    ConfigurationManager.AppSettings["Snipe:ApiToken"]);

            if (!String.IsNullOrWhiteSpace(hostName))
            {
                Console.WriteLine($"Retrieving asset details for {hostName}");
                try
                {
                    var asset      = AssetDescriptor.Create(hostName);
                    var components = ComponentDescriptor.Create(hostName);
                    try
                    {
                        Console.WriteLine($"Synchronizing asset details for {hostName}");
                        // The current version of the SnipeSharp API has mapping issues causing the response not de serializing.
                        snipe.SyncAssetWithCompoments(asset, components);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to sync asset details for {hostName}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to retrieve asset details for {hostName}");
                }
            }
        }
Example #16
0
 public void Init_MissingToken_ThrowsException()
 {
     Assert.Throws <NullApiTokenException>(() => {
         var snipe = new SnipeItApi();
         snipe.Uri = TEST_URI;
         snipe.RequestManager.SetTokenAndUri();
     });
 }
Example #17
0
 public void Init_MissingURI_ThrowsException()
 {
     Assert.Throws <NullApiUriException>(() => {
         var snipe   = new SnipeItApi();
         snipe.Token = TEST_TOKEN;
         snipe.RequestManager.SetTokenAndUri();
     });
 }
Example #18
0
 /// <param name="api">The Api to grab the RequestManager from.</param>
 /// <exception cref="SnipeSharp.Exceptions.MissingRequiredAttributeException">When the type parameter does not have the <see cref="PathSegmentAttribute">PathSegmentAttribute</see> attribute.</exception>
 internal EndPoint(SnipeItApi api)
 {
     Api          = api;
     EndPointInfo = typeof(T).GetCustomAttribute <PathSegmentAttribute>();
     if (null == EndPointInfo)
     {
         throw new MissingRequiredAttributeException(nameof(PathSegmentAttribute), typeof(T).Name);
     }
 }
Example #19
0
        public static SnipeItApi GetAPI()
        {
            ReadValues();

            SnipeItApi API = new SnipeItApi();

            API.ApiSettings.ApiToken = Token;
            API.ApiSettings.BaseUrl  = new Uri(URI);

            return(API);
        }
Example #20
0
        public static Asset Data(string Name)
        {
            SnipeItApi Snipe = Api.GetAPI();

            SearchFilter Search = new SearchFilter
            {
                Search = Name
            };

            return(Snipe.AssetManager.FindOne(Search));
        }
Example #21
0
        public void Init_NoneMissing_NotThrowsException()
        {
            var snipe = new SnipeItApi
            {
                Token = TEST_TOKEN,
                Uri   = TEST_URI
            };

            snipe.RequestManager.SetTokenAndUri();
            Assert.True(true);
        }
Example #22
0
        private static string Create(string companyname)
        {
            SnipeItApi Snipe = Api.GetAPI();
            Company    Comp  = new Company
            {
                Name = companyname,
            };

            Snipe.CompanyManager.Create(Comp);
            Name = Snipe.CompanyManager.Get(companyname).Name;
            return(Name);
        }
Example #23
0
        /// <summary>
        /// Synchronizes the specified <see cref="AssetDescriptor"/> details with a
        /// <c>Snipt.It</c> asset or creates one if not asset matching the specified
        /// serial exists.
        /// </summary>
        /// <param name="snipe">
        ///     The <see cref="SnipeItApi"/> instance used to access the <c>Snipt.It</c>
        ///     web API.
        /// </param>
        /// <param name="assetDetails">
        ///     The <see cref="AssetDescriptor"/> describing the asset's details.
        /// </param>
        /// <returns>
        ///     The resulting <c>Snipt.It</c> <see cref="Asset"/>.
        /// </returns>
        public static Asset SyncAsset(this SnipeItApi snipe, AssetDescriptor assetDetails)
        {
            // Validate parameters.
            if (snipe == null)
            {
                throw new ArgumentNullException("snipe");
            }
            if (assetDetails == null)
            {
                throw new ArgumentNullException("assetDetails");
            }

            Asset snipeAsset = snipe.AssetManager.FindOne(new SearchFilter {
                Search = assetDetails.Serial
            });
            var    manufacturer  = SnipeApiExtensions.SyncManufacturer(snipe, assetDetails.Manufacturer);
            string snipeCategory = SnipeApiExtensions.DefaultSnipeCategoriesMap[assetDetails.Category];
            var    category      = SnipeApiExtensions.SyncCategory(snipe, snipeCategory, "asset");
            var    model         = SnipeApiExtensions.SyncModel(snipe, manufacturer, category, assetDetails.Model, assetDetails.ModelNumber);

            if (snipeAsset == null)
            {
                snipeAsset =
                    new Asset()
                {
                    Name         = assetDetails.Name,
                    ModelNumber  = assetDetails.ModelNumber,
                    Manufacturer = manufacturer,
                    Category     = category,
                    Model        = model
                };

                var response = snipe.AssetManager.Create(snipeAsset);
                snipeAsset = snipe.AssetManager.FindOne(new SearchFilter {
                    Search = assetDetails.Serial
                });
            }
            else
            {
                snipeAsset.Name         = assetDetails.Name;
                snipeAsset.ModelNumber  = assetDetails.ModelNumber;
                snipeAsset.Manufacturer = manufacturer;
                snipeAsset.Category     = category;
                snipeAsset.Model        = model;

                var response = snipe.AssetManager.Update(snipeAsset);
            }

            return(snipeAsset);
        }
Example #24
0
        private static string Create(string DeviceCategory)
        {
            string category = DeviceCategory;

            SnipeItApi Snipe = Api.GetAPI();

            Category Cat = new Category
            {
                Name = category,
                Type = "asset"
            };

            Snipe.CategoryManager.Create(Cat);
            Name = Snipe.CategoryManager.Get(category).Name;
            return(Name);
        }
Example #25
0
        private static string Create(string DeviceMake, string DeviceModel, string ModelName)
        {
            SnipeItApi Snipe      = Api.GetAPI();
            Model      assetmodel = new Model
            {
                Name         = ModelName,
                Manufacturer = Snipe.ManufacturerManager.Get(DeviceMake),
                Category     = Snipe.CategoryManager.Get("Laptops"),
                ModelNumber  = DeviceModel
            };

            Snipe.ModelManager.Create(assetmodel);
            Name = Snipe.ModelManager.Get(ModelName).Name;

            return(Name);
        }
Example #26
0
        private static string Create(string DeviceMake)
        {
            string Make = DeviceMake;

            SnipeItApi   Snipe = Api.GetAPI();
            Manufacturer maker = new Manufacturer
            {
                Name = Make
            };

            Snipe.ManufacturerManager.Create(maker);

            Name = Snipe.ManufacturerManager.Get(Make).Name;

            return(Name);
        }
        public void CheckApiTokenAndUrl_SetHttpClientBaseAddress_SetCorrectly()
        {
            SnipeItApi snipe = new SnipeItApi();
            Uri        url   = new Uri("http://google.com");

            snipe.ApiSettings.ApiToken = "xxxxx";
            snipe.ApiSettings.BaseUrl  = url;
            snipe.ReqManager.CheckApiTokenAndUrl();

            // Get the Static property value
            Type       type  = typeof(RequestManager);
            FieldInfo  prop  = type.GetField("Client", BindingFlags.NonPublic | BindingFlags.Static);
            HttpClient value = prop.GetValue(snipe.ReqManager) as HttpClient;

            Assert.AreEqual(url, value.BaseAddress);
        }
Example #28
0
        /// <summary>
        ///  Synchronizes the specified model details with an existing
        /// <c>Snipt.It</c> model or creates a new one if no model exists.
        /// </summary>
        /// <param name="snipe">
        ///     The <see cref="SnipeItApi"/> instance used to access the <c>Snipt.It</c>
        ///     web API.
        /// </param>
        /// <param name="manufacturer">
        ///     The <c>Snipt.It</c> <see cref="Manufacturer"/> that should be associated
        ///     with the specified model.
        /// </param>
        /// <param name="category">
        ///      The <c>Snipt.It</c> <see cref="Category"/> that should be associated
        ///     with the specified model.
        /// </param>
        /// <param name="modelName">
        ///     The model name.
        /// </param>
        /// <param name="modelNumber">
        ///     The model number.
        /// </param>
        /// <returns>
        ///     The resulting <c>Snipt.It</c> <see cref="Model"/>.
        /// </returns>
        public static Model SyncModel(
            this SnipeItApi snipe,
            Manufacturer manufacturer,
            Category category,
            string modelName,
            string modelNumber)
        {
            // Validate parameters.
            if (snipe == null)
            {
                throw new ArgumentNullException("snipe");
            }
            if (manufacturer == null)
            {
                throw new ArgumentNullException("manufacturer");
            }
            if (category == null)
            {
                throw new ArgumentNullException("category");
            }
            if (String.IsNullOrWhiteSpace(modelName))
            {
                throw new ArgumentNullException("modelName");
            }
            if (String.IsNullOrWhiteSpace(modelNumber))
            {
                throw new ArgumentNullException("modelNumber");
            }


            Model snipeModel = snipe.ModelManager.FindAll(new SearchFilter {
                Search = modelName
            }).Rows.FirstOrDefault();

            if (snipeModel == null)
            {
                snipeModel = new Model()
                {
                    Name = modelName, ModelNumber = modelNumber, Manufacturer = manufacturer, Category = category
                };
                var response = snipe.ModelManager.Create(snipeModel);
                snipeModel = snipe.ModelManager.FindAll(new SearchFilter {
                    Search = modelName
                }).Rows.FirstOrDefault();
            }
            return(snipeModel);
        }
Example #29
0
 public Category GetCategory(NameValueCollection appSettings, SnipeItApi snipe)
 {
     string systemType = GetOutputVariable("Win32_ComputerSystem.PCSystemType");
     // TODO: Place in a separate enum class:
     WindowsSystemTypes winTypes = new WindowsSystemTypes();
     string systemTypeFull = "Undefined";
     try
     {
         systemTypeFull = winTypes.SystemTypes[systemType];
     }
     catch (Exception e)
     {
         Trace.WriteLine("Exception encountered while processing WinSystemType: " + e.ToString());
     }
     Category currentCategory = new Category(systemTypeFull);
     return currentCategory;
 }
        public void CheckApiTokenAndUrl_SetAuthorizationHeader_SetCorrectly()
        {
            SnipeItApi snipe = new SnipeItApi();
            Uri        url   = new Uri("http://google.com");

            snipe.ApiSettings.ApiToken = "xxxxx";
            snipe.ApiSettings.BaseUrl  = url;
            snipe.ReqManager.CheckApiTokenAndUrl();

            // Get the Static property value
            Type       type  = typeof(RequestManager);
            FieldInfo  prop  = type.GetField("Client", BindingFlags.NonPublic | BindingFlags.Static);
            HttpClient value = prop.GetValue(snipe.ReqManager) as HttpClient;

            Assert.IsTrue(value.DefaultRequestHeaders.Authorization.Scheme == "Bearer" &&
                          value.DefaultRequestHeaders.Authorization.Parameter == "xxxxx");
        }