protected bool Equals(ComplexType other)
 {
     return(Equals(BaseType, other.BaseType) && Date.Equals(other.Date) &&
            Equals(InterfaceHolder, other.InterfaceHolder) && NullableInt == other.NullableInt &&
            Equals(PolymorphicHolder, other.PolymorphicHolder) && Array.SequenceEqual(other.Array) &&
            GuidCollection.SequenceEqual(other.GuidCollection));
 }
예제 #2
0
        /// <summary>
        /// Test the Table Definition contain the table
        /// </summary>
        /// <param name="DefinitionId"></param>
        /// <param name="ResourceTableId"></param>
        public static bool Test_DefinitionContainsTable_ResourceExists(Guid DefinitionId, Guid ResourceTableId)
        {
            bool isExisting = false;

            try
            {
                IResource resourceDefinition = Resource.Get(DefinitionId);

                //Get the definition tables
                GuidCollection tables = ((IResourceDefinition)resourceDefinition).Tables;

                //check if the supplied table exists
                foreach (Guid table in tables)
                {
                    if (table == ResourceTableId)
                    {
                        isExisting = true;
                        break;
                    }
                }
            }
            catch
            {
                isExisting = false;
            }


            return(isExisting);
        }
예제 #3
0
        public static GuidCollection EnsureUpdatesStaged(IList <Guid> guids, bool sync, out ITaskExecutionInstance inst)
        {
            inst = null;
            GuidCollection nonstagedUpdates = GetNonstagedUpdates(guids);

            if (nonstagedUpdates.Count <= 0)
            {
                return(nonstagedUpdates);
            }
            EventLog.ReportVerbose(string.Format("Staging {0} updates...", nonstagedUpdates.Count), "Stage & Distribute");
            try {
                for (int i = 0; i < 5; i++)
                {
                    inst = Item.GetItem <DownloadSWUPackageTask>(Tasks.Singletons70.DownloadSWUPackage, ItemLoadFlags.WriteableIgnoreAll).CreateInstanceForReplication(nonstagedUpdates, DownloadFilter.Auto, DownloadSWUPackageTask.EReason.DOWNLOAD_STAGE);
                    if (sync)
                    {
                        TaskHelper.WaitForTaskToComplete(inst);
                    }
                    else
                    {
                        return(nonstagedUpdates);
                    }
                    if (inst.InstanceStatus == Altiris.TaskManagement.Common.TaskInstanceStatus.Completed)
                    {
                        return(nonstagedUpdates);
                    }
                }
            }
            catch (Exception exception) {
                TraceOps.TRACE(exception);
            }
            throw new Exception(string.Format("Unable to stage '{0}' updates.", nonstagedUpdates.Count));
        }
예제 #4
0
        /// <summary>
        /// Test all Relationship Constraints resource exists
        /// </summary>
        public static bool Test_RelationshipConstraints_ResourceExist(GuidCollection ResourceConstraintIds)
        {
            bool isExisting = false;

            try
            {
                int constraintCounter = ResourceConstraintIds.Count;
                foreach (Guid contraintId in ResourceConstraintIds)
                {
                    //get the constraint by Guid
                    IResource resourceConstraint = Resource.Get(contraintId);

                    //check if constraint is not null and the type is IResourceRelationshipConstraint
                    if (resourceConstraint != null && resourceConstraint is IResourceRelationshipConstraint)
                    {
                        constraintCounter--;
                    }
                }
                if (constraintCounter == 0)
                {
                    isExisting = true;
                }
            }
            catch
            {
                isExisting = false;
            }
            return(isExisting);
        }
예제 #5
0
 public GuidCollectionEnumerator(GuidCollection collection)
 {
     collectionRef = collection;
     currentIndex  = -1;
     currentObject = null;
     currentSize   = collectionRef.Count;
 }
예제 #6
0
        public string CreateUpdatePolicy(string name, string bulletinGuids, List <string> targetGuids, bool enabled)
        {
            IList <Guid> suGuids = ParseGuidList(ResolveToUpdates(bulletinGuids), true);

            if (suGuids == null)
            {
                return(string.Empty);
            }
            if (suGuids.Count == 0)
            {
                return("No software updates resolved for policy.");
            }
            Guid platformPolicy = PatchManagementVendorPolicy.GetPlatformPolicy(suGuids[0]);

            if (platformPolicy == Guid.Empty)
            {
                return(string.Format("Unable to resolve vendor from {0}", suGuids[0]));
            }
            PatchManagementVendorPolicy item = Item.GetItem(platformPolicy) as PatchManagementVendorPolicy;

            if (item == null)
            {
                return(string.Format("Unable to load vendor policy {0}", platformPolicy));
            }
            GuidCollection gc = new GuidCollection();

            foreach (Guid g in suGuids)
            {
                gc.Add(g);
            }
            SoftwareUpdateAdvertismentSet newAdvertismentSet = item.GetNewAdvertismentSet();

            newAdvertismentSet.Initialise(gc);
            SoftwareUpdateDistributionTask task = Item.GetItem(Tasks.Singletons70.SoftwareUpdateDistrbutionTask, ItemLoadFlags.WriteableIgnoreAll) as SoftwareUpdateDistributionTask;

            if (task == null)
            {
                return("Cannot initialise of SoftwareUpdateDistrbutionTask. Item is missing from the database");
            }
            newAdvertismentSet.Name    = name;
            newAdvertismentSet.Enabled = enabled;

            if (targetGuids.Count > 0)
            {
                GuidCollection targetGuidColl = new GuidCollection();
                foreach (string target in targetGuids)
                {
                    targetGuidColl.Add(new Guid(target));
                }

                newAdvertismentSet.BaseResourceTargetGuids = targetGuidColl;
            }
            ITaskExecutionInstance instance = task.CreateInstance(newAdvertismentSet, Guid.Empty, DistributionType.PolicyForWin);

            if (instance == null)
            {
                return(string.Empty);
            }
            return(instance.TaskInstanceGuid.Guid.ToString());
        }
예제 #7
0
        public string ResolveToUpdates(string bulletinGuids)
        {
            string         str;
            GuidCollection guids = ParseGuidList(bulletinGuids, true);

            if ((guids != null) && (guids.Count > 0))
            {
                GuidCollection guids2 = new GuidCollection();
                foreach (Guid guid in guids)
                {
                    IItem item = Item.GetItem(guid, 0);
                    if (item == null)
                    {
                        throw new Exception(string.Format("{0} is not a valid bulletin or update resource.", guid));
                    }
                    SoftwareBulletinResource    resource  = item as SoftwareBulletinResource;
                    PatchSoftwareUpdateResource resource2 = item as PatchSoftwareUpdateResource;
                    if (resource != null)
                    {
                        guids2.AddRange(resource.SoftwareUpdateGuids);
                    }
                    else if (resource2 != null)
                    {
                        guids2.Add(guid);
                    }
                }
                return(ArrayOps.Join((IEnumerable <Guid>)guids2.RemoveDuplicates(), ","));
            }
            str = string.Empty;
            return(str);
        }
예제 #8
0
 public GuidCollection(GuidCollection other) : this(CommonPINVOKE.new_GuidCollection__SWIG_1(GuidCollection.getCPtr(other)), true)
 {
     if (CommonPINVOKE.SWIGPendingException.Pending)
     {
         throw CommonPINVOKE.SWIGPendingException.Retrieve();
     }
 }
예제 #9
0
        /// <summary>
        /// Test the Table Definition contain the key
        /// </summary>
        public static bool Test_DefinitionContainsKey_ResourceExists(Guid DefinitionId, Guid ResourceKeyId)
        {
            bool isExisting = false;

            try
            {
                IResource resourceDefinition = Resource.Get(DefinitionId);

                //Get the definition keys
                GuidCollection keys = ((IResourceDefinition)resourceDefinition).Keys;

                //check if the supplied key exists
                foreach (Guid key in keys)
                {
                    if (key == ResourceKeyId)
                    {
                        isExisting = true;
                        break;
                    }
                }
            }
            catch
            {
                isExisting = false;
            }


            return(isExisting);
        }
예제 #10
0
        /// <summary>
        /// Test the Relationship Constraint in the relationship definition
        /// </summary>
        /// <param name="ResourceRelationShipDefinitonId"></param>
        /// <param name="RelationshipConstraintIds"></param>
        /// <returns></returns>
        public static bool Test_RelationshipDefinition_ContainConstraint(Guid ResourceRelationShipDefinitonId, Guid RelationshipConstraintId)
        {
            bool isExisting = false;

            try
            {
                //get the relationship from the database
                IResource resourceRelationship = Resource.Get(ResourceRelationShipDefinitonId);

                //get  the relationship constaints
                GuidCollection constraints = ((IResourceRelationshipDefinition)resourceRelationship).RelationshipConstraints;

                foreach (Guid constraint in constraints)
                {
                    if (constraint == RelationshipConstraintId)
                    {
                        isExisting = true;
                        break;
                    }
                }
            }
            catch
            {
                isExisting = false;
            }
            return(isExisting);
        }
예제 #11
0
 public System.Guid[] GetSignalIDs()
 {
     using (GuidCollection guids = new GuidCollection())
     {
         GetSignalIDs(guids);
         return(System.Linq.Enumerable.ToArray(guids));
     }
 }
예제 #12
0
 public void SetRange(int index, GuidCollection values)
 {
     CommonPINVOKE.GuidCollection_SetRange(swigCPtr, index, GuidCollection.getCPtr(values));
     if (CommonPINVOKE.SWIGPendingException.Pending)
     {
         throw CommonPINVOKE.SWIGPendingException.Retrieve();
     }
 }
예제 #13
0
        public int EnsureStaged(string bulletinGuids, bool sync)
        {
            int num;
            ITaskExecutionInstance inst  = null;
            GuidCollection         guids = EnsureUpdatesStaged((IList <Guid>)ParseGuidList(ResolveToUpdates(bulletinGuids), true), sync, out inst);

            return(num = (guids != null) ? guids.Count : -1);
        }
예제 #14
0
        public bool IsStaged(string bulletinGuids)
        {
            bool           flag;
            GuidCollection nonstagedUpdates = GetNonstagedUpdates(ParseGuidList(ResolveToUpdates(bulletinGuids), true));

            flag = (nonstagedUpdates == null) || (nonstagedUpdates.Count == 0);
            return(flag);
        }
예제 #15
0
        static int Main(string[] args)
        {
            if (SecurityAPI.is_user_admin())
            {
                ZeroDayPatch automate = new ZeroDayPatch();
                automate.config = new CliConfig(config_types.ZeroDayPatch);
                CliInit init;
                if (args.Length == 1 && args[0].StartsWith("/config="))
                {
                    init = new CliInit(CliInit.GetConfigFromFile(ref args), ref automate.config);
                }
                else
                {
                    init = new CliInit(args, ref automate.config);
                }

                #region If we can initialise run the automate
                if (init.ParseArgs())
                {
                    Console.WriteLine("ZeroDayPatch {0} starting.", Constant.VERSION);

                    GuidCollection bulletins = new GuidCollection();
                    bulletins = automate.GetSoftwareBulletins();

                    int i = automate.RunAutomation(bulletins);

                    if (i != -1)
                    {
                        Console.WriteLine("\n{0} software update policy creation tasks were started.", i.ToString());
                        Console.WriteLine("ZeroDayPatch execution completed now. See you soon...");
                        return(0);
                    }
                    return(i);
                }
                #endregion
                #region else display the help message
                else
                {
                    if (automate.config.Print_Version)
                    {
                        Console.WriteLine("{{CWoC}} ZeroDayPatch version {0}", Constant.VERSION);
                        return(0);
                    }
                    Console.WriteLine(Constant.ZERO_DAY_HELP);
                    if (!automate.config.Help_Needed)
                    {
                        return(0);
                    }
                    return(-1);
                }
                #endregion
            }
            else
            {
                Console.WriteLine("Access denied - Only Altiris administrators are allowed to use this tool");
            }
            return(-1);
        }
예제 #16
0
        static void Main()
        {
            GuidCollection guids = PMImportHelper.GetAllBulletinsDisabledByUser();

            foreach (Guid g in guids)
            {
                Console.WriteLine(g.ToString());
            }
        }
예제 #17
0
        public static GuidCollection GetNonstagedUpdates(IList <Guid> gcUpdates)
        {
            GuidCollection gc = new GuidCollection();

            foreach (Guid g in Altiris.NS.DataAccessLayer.DataAccessLayer <PatchManagementCoreResourcesDAL> .Instance.spPMCore_SoftwareUpdateListIsNotDownloaded(new GuidCollection(gcUpdates)))
            {
                gc.Add(g);
            }
            return(gc);
        }
예제 #18
0
        public bool IsStaged(string bulletinGuids)
        {
            GuidCollection nonstagedUpdates = SoftwareUpdateAdvertismentSetPolicy.GetNonstagedUpdates(ParseGuidList(ResolveToUpdates(bulletinGuids), true), true);

            if (nonstagedUpdates != null)
            {
                return(nonstagedUpdates.Count == 0);
            }
            return(true);
        }
예제 #19
0
        public bool GetSignalIDs(GuidCollection signalIDs)
        {
            bool ret = CommonPINVOKE.SignalIndexCache_GetSignalIDs(swigCPtr, GuidCollection.getCPtr(signalIDs));

            if (CommonPINVOKE.SWIGPendingException.Pending)
            {
                throw CommonPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
예제 #20
0
        public GuidCollection GetRange(int index, int count)
        {
            global::System.IntPtr cPtr = CommonPINVOKE.GuidCollection_GetRange(swigCPtr, index, count);
            GuidCollection        ret  = (cPtr == global::System.IntPtr.Zero) ? null : new GuidCollection(cPtr, true);

            if (CommonPINVOKE.SWIGPendingException.Pending)
            {
                throw CommonPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
예제 #21
0
 public static GuidCollection Repeat(System.Guid value, int count)
 {
     guid_t tempvalue = Common.ParseGuid(value.ToByteArray(), true);
     {
         global::System.IntPtr cPtr = CommonPINVOKE.GuidCollection_Repeat(guid_t.getCPtr(tempvalue), count);
         GuidCollection        ret  = (cPtr == global::System.IntPtr.Zero) ? null : new GuidCollection(cPtr, true);
         if (CommonPINVOKE.SWIGPendingException.Pending)
         {
             throw CommonPINVOKE.SWIGPendingException.Retrieve();
         }
         return(ret);
     }
 }
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = (BaseType != null ? BaseType.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Date.GetHashCode();
         hashCode = (hashCode * 397) ^ (InterfaceHolder != null ? InterfaceHolder.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ NullableInt.GetHashCode();
         hashCode = (hashCode * 397) ^ (PolymorphicHolder != null ? PolymorphicHolder.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Array != null ? Array.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (GuidCollection != null ? GuidCollection.GetHashCode() : 0);
         return(hashCode);
     }
 }
예제 #23
0
        public void SupportCustomizations()
        {
            var gc = new GuidCollection();

            var g = Guid.NewGuid();

            // add a guid
            gc.Add(g);
            Assert.Contains(g, gc);

            // reject addition of an empty guid
            Assert.Throws <ArgumentException>(() => gc.Add(Guid.Empty));

            // reject setting an empty guid
            Assert.Throws <ArgumentException>(() => gc[0] = Guid.Empty);
        }
예제 #24
0
        public GuidCollection ParseGuidList(string list, bool unique)
        {
            GuidCollection guids = new GuidCollection();

            foreach (string str in list.Split(new char[] { ',', ';', '|' }))
            {
                Guid guid = GuidOps.Str2Guid(str.Trim());
                if (guid != Guid.Empty)
                {
                    guids.Add(guid);
                }
            }
            if (!unique)
            {
                return(guids);
            }
            return(guids.RemoveDuplicates());
        }
예제 #25
0
        public string ResolveToPolicies(string bulletinGuids)
        {
            GuidCollection guids = ParseGuidList(ResolveToUpdates(bulletinGuids), true);

            if (guids == null)
            {
                return(string.Empty);
            }
            GuidCollection guids2 = new GuidCollection();

            foreach (Guid guid in guids)
            {
                foreach (ItemReferenceRow row in Altiris.NS.DataAccessLayer.DataAccessLayer <PatchManagementCorePoliciesDAL> .Instance.spPMCore_GetItemReference(Guid.Empty, guid, "policy_swu"))
                {
                    guids2.Add(row.ParentItemGuid);
                }
            }
            return(ArrayOps.Join(guids2.RemoveDuplicates(), ","));
        }
예제 #26
0
        /// <summary>
        /// Test the Table Definition contains All keys which belong it
        /// </summary>
        /// <param name="DefinitionId"></param>
        /// <param name="ResourceTableIds">List of key Guid</param>
        public static bool Test_DefinitionContainsKeys_ResourceExists(Guid DefinitionId, GuidCollection ResourceKeyIds)
        {
            bool isExisting = false;

            try
            {
                IResource resourceDefinition = Resource.Get(DefinitionId);

                int keyIdsCounter = ResourceKeyIds.Count;
                //Get the definition keys
                GuidCollection keys = ((IResourceDefinition)resourceDefinition).Keys;

                //check if the supplied keys exists

                foreach (Guid key in keys)
                {
                    foreach (Guid keyId in ResourceKeyIds)
                    {
                        if (key == keyId)
                        {
                            keyIdsCounter--;
                        }
                    }
                }
                if (keyIdsCounter == 0)
                {
                    isExisting = true;
                }
            }
            catch
            {
                isExisting = false;
            }


            return(isExisting);
        }
예제 #27
0
        /// <summary>
        /// Test the Table Definition contains All tables which belong it
        /// </summary>
        /// <param name="DefinitionId"></param>
        /// <param name="ResourceTableIds">List of Table Guid</param>
        public static bool Test_DefinitionContainsTables_ResourceExists(Guid DefinitionId, GuidCollection ResourceTableIds)
        {
            bool isExisting = false;

            try
            {
                IResource resourceDefinition = Resource.Get(DefinitionId);

                int tableIdsCounter = ResourceTableIds.Count;
                //Get the definition tables
                GuidCollection tables = ((IResourceDefinition)resourceDefinition).Tables;

                //check if the supplied tables exists

                foreach (Guid table in tables)
                {
                    foreach (Guid tableId in ResourceTableIds)
                    {
                        if (table == tableId)
                        {
                            tableIdsCounter--;
                        }
                    }
                }
                if (tableIdsCounter == 0)
                {
                    isExisting = true;
                }
            }
            catch
            {
                isExisting = false;
            }


            return(isExisting);
        }
예제 #28
0
        private GuidCollection GetSoftwareBulletins()
        {
            GuidCollection bulletin_collection = new GuidCollection();

            DataTable bulletins = GetExistingBulletins();

            Console.WriteLine("# {0} bulletins returned by the stored procedure execution.", bulletins.Rows.Count);
            DataTable excluded_bulletins = GetExcludedBulletins();

            Console.WriteLine("# {0} bulletin names found in the exclusion table.", excluded_bulletins.Rows.Count);

            if (bulletins.Rows.Count == 0)
            {
                return(bulletin_collection);
            }

            try {
                using (DataTableReader sqlRdr = bulletins.CreateDataReader()) {
                    #region Get position of the used field
                    int pos_released = -1;
                    int pos_res_guid = -1;
                    int pos_bulletin = -1;
                    int pos_severity = -1;
                    int pos_vendor   = -1;

                    for (int i = 0; i < sqlRdr.FieldCount; i++)
                    {
                        string field_name = sqlRdr.GetName(i).ToLower();
                        if (field_name == "released")
                        {
                            pos_released = i;
                        }
                        if (field_name == "_resourceguid")
                        {
                            pos_res_guid = i;
                        }
                        if (field_name == "bulletin")
                        {
                            pos_bulletin = i;
                        }
                        if (field_name == "severity")
                        {
                            pos_severity = i;
                        }
                        if (field_name == "vendor")
                        {
                            pos_vendor = i;
                        }
                    }

                    bool field_init = false;
                    if (pos_severity != -1 && pos_res_guid != -1 && pos_released != -1 && pos_bulletin != -1)
                    {
                        field_init = true;
                    }
                    #endregion

                    if (config.Debug)
                    {
                        Console.WriteLine("# Field positions are:\n\tBulletin={0}\n\tReleased={1}\n\tResourceGuid={2}\n\tSeverity={3}\n\tVendor={4}", pos_bulletin, pos_released, pos_res_guid, pos_severity, pos_vendor);
                    }

                    if (field_init)
                    {
                        while (sqlRdr.Read())
                        {
                            Guid     bguid       = sqlRdr.GetGuid(pos_res_guid);
                            String   bull_name   = sqlRdr.GetString(pos_bulletin);
                            String   sev         = sqlRdr.GetString(pos_severity);
                            DateTime dt          = sqlRdr.GetDateTime(pos_released);
                            String   bull_vendor = string.Empty;
                            if (pos_vendor != -1)
                            {
                                bull_vendor = sqlRdr.GetString(pos_vendor).ToLower();
                            }

                            bool row_excluded = false;

                            #region // Break if the current bulletin is excluded
                            foreach (DataRow r in excluded_bulletins.Rows)
                            {
                                if (r[0].ToString() == bull_name)
                                {
                                    row_excluded = true;
                                    break;
                                }
                            }

                            if (row_excluded)
                            {
                                continue;
                            }
                            #endregion

                            if ((sev.ToLower() == config.Severity.ToLower() || config.Severity == "*") && dt >= config.Released_After && dt <= config.Released_Before)
                            {
                                if (pos_vendor == -1 || config.Vendor_Name == bull_vendor || config.Vendor_Name == "*")
                                {
                                    if (config.Debug)
                                    {
                                        Console.WriteLine("\tWe have a match: {0} from {1}", bull_name, bull_vendor);
                                    }
                                    bulletin_collection.Add(bguid);
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Failed to find the required fields in the provided data table. Not doing anything.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Error: {0}\nException message = {1}\nStack trace = {2}.", e.Message, e.InnerException, e.StackTrace);
            }
            Console.WriteLine("{0} bulletins match the {1} severity and will be checked for policies.", bulletin_collection.Count, config.Severity);
            return(bulletin_collection);
        }
예제 #29
0
        private int RunAutomation(GuidCollection bulletins)
        {
            Console.Write("\n\n");
            string now = DateTime.Now.ToString("yyyyMMddHHmmss");

            operation_log = "journal_" + now.ToString() + ".log";

            int i = 0;

            try {
                SecurityContextManager.SetContextData();
                PatchAPI wrap = new PatchAPI();

                string name = "";

                if (config.Dry_Run)
                {
                    Console.WriteLine("\n######## THIS IS A DRY RUN ########");
                }
                foreach (Guid bulletin in bulletins)
                {
                    name = Item.GetItem(bulletin).Name;
                    Console.WriteLine("");
                    Console.WriteLine("Processing bulletin {0} ({1}) now.", name, bulletin);

                    if (wrap.IsStaged(bulletin.ToString()))
                    {
                        Console.WriteLine("\tThis bulletin is already staged.");
                    }
                    else
                    {
                        if (config.RecreateMissingPolicies || config.Retarget)
                        {
                            // Skip this bulletin as it is not yet downloaded
                            continue;
                        }
                        Console.WriteLine("\t... bulletin will be staged now.");
                        if (!config.Dry_Run)
                        {
                            try {
                                wrap.EnsureStaged(bulletin.ToString(), true);
                                LogOp(String.Format("{0}: Staged bulletin {1} (guid={2}).", DateTime.Now.ToString(), name, bulletin.ToString()));
                            } catch {
                                // Do not retry staging error. Any download error is retried at the task level. Other errors won't be solved by retry...
                                if (config.ExcludeOnFail)
                                {
                                    DatabaseAPI.ExecuteNonQuery("insert patchautomation_excluded (bulletin) values ('" + name + "')");
                                    Console.WriteLine("Failed to stage bulletin {0} - the bulletin is now excluded.", name);
                                }
                                else
                                {
                                    Console.WriteLine("Failed to stage bulletin {0} - skipping the bulletin now.", name);
                                }
                                continue; // Go to the next bulletin
                            }
                        }
                        Console.WriteLine("\tBulletin is now staged.");
                    }
                    Console.WriteLine("\tChecking if we need to create a new policy now.");

                    string   policies_str = wrap.ResolveToPolicies(bulletin.ToString());
                    string[] policies_arr = policies_str.Split(',');

                    if (!config.Retarget && (policies_str == "" || policies_str.Length == 0 || config.Create_Duplicates))
                    {
                        Console.WriteLine("\t... create a policy for the bulletin now.");
                        if (!config.Dry_Run)
                        {
                            int j = 0; // Used for retry count
retry_create_policy:
                            try {
                                if (config.Target_Guids.Count == 0)
                                {
                                    wrap.CreateUpdatePolicy(name, bulletin.ToString(), true);
                                    LogOp(String.Format("{0}: Created policy for bulletin {1} (guid={2})", DateTime.Now.ToString(), name, bulletin.ToString()));
                                }
                                else
                                {
                                    wrap.CreateUpdatePolicy(name, bulletin.ToString(), config.Target_Guids, true);
                                    LogOp(String.Format("{0}: Created policy for bulletin {1} (guid={2}, target={3})", DateTime.Now.ToString(), name, bulletin.ToString(), config.Get_TargetGuids()));
                                }
                                // Added the bulletin to the exclusion list here
                                if (config.Create_Duplicates)
                                {
                                    DatabaseAPI.ExecuteNonQuery("insert patchautomation_excluded (bulletin) values ('" + name + "')");
                                }
                                i++;
                            } catch (Exception e) {
                                if (j++ < 3)
                                {
                                    Console.WriteLine(e.Message);
                                    Console.WriteLine(e.StackTrace);
                                    Console.WriteLine("\tFailed to create policy for bulletin {0} {1} time(s)...", name, j.ToString());
                                    goto retry_create_policy; // Retry ceiling not reach - let's do it again.
                                }
                                else                          // Retried 3 times - we quit and document the problem
                                {
                                    if (config.ExcludeOnFail)
                                    {
                                        DatabaseAPI.ExecuteNonQuery("insert patchautomation_excluded (bulletin) values ('" + name + "')");
                                        Console.WriteLine("\tFailed to create policy for bulletin {0} 3 times - the bulletin is now excluded.", name);
                                    }
                                    else
                                    {
                                        Console.WriteLine("\tFailed to create policy for bulletin {0} 3 times - skipping the bulletin now.", name);
                                    }
                                    continue; // Go to the next bulletin
                                }
                            }
                        }
                        Console.WriteLine("\tSoftware update policy created!");
                    }
                    else if (config.Retarget)
                    {
                        if (policies_arr.Length > 0)
                        {
                            /* ENHANCEMENT: 2018-01-24; There is no need to update each policy - one of them will update the "parent" policy which is enough :D.
                             *                          This avoid doing the same task 153 times when an Office policy as 153 updates!
                             *
                             * */
                            //                            foreach (string p in policies_arr) {
                            string p = policies_arr[0];
                            if (p.Length != 36)
                            {
                                continue;
                            }

                            Console.WriteLine("\tA policy already exists for this bulletin...");

                            Guid policyGuid = new Guid(p);
                            SoftwareUpdateAdvertismentSetPolicy policyItem = Item.GetItem <SoftwareUpdateAdvertismentSetPolicy>(policyGuid, ItemLoadFlags.Writeable);

                            Console.WriteLine("\tPolicy {0} will be retargetted now.", policyItem.Name);

                            policyItem.ResourceTargets.Clear();
                            foreach (string target in config.Target_Guids)
                            {
                                policyItem.ResourceTargets.Add(new Guid(target));
                            }
                            if (!config.Dry_Run)
                            {
                                int retry = 0;
save_item:
                                try {
                                    policyItem.Save();
                                    LogOp(String.Format("{0}: Retargetted policy for bulletin {1} (guid={2}, new target={3})", DateTime.Now.ToString(), name, bulletin.ToString(), config.Get_TargetGuids()));
                                    i++;
                                } catch {
                                    Console.WriteLine("\tCaught an exception. Retry " + retry.ToString() + "will start now.");
                                    if (retry < 10)
                                    {
                                        goto save_item;
                                    }
                                    Console.WriteLine("\tSaving the policy failed 10 times. Moving on to the next item.");
                                }
                            }
//                            } // Commented out for each node removed to fix
                        }
                    }
                    else
                    {
                        Console.WriteLine("\tA policy already exists for this bulletin.");
                    }
                    if (i > 9 && config.Test_Run)
                    {
                        break;
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Error message={0}\nInner Exception={1}\nStacktrace={2}", e.Message, e.InnerException, e.StackTrace);
                return(-1);
            }
            return(i);
        }
예제 #30
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(GuidCollection obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }