Ejemplo n.º 1
0
        /// <summary>
        /// Populate this container with AcStream objects as per constructor parameters.
        /// AcStream objects are instantiated during AcDepot and AcDepots construction.
        /// This function is called internally and not by user code.
        /// </summary>
        /// <param name="depot">The depot for which streams will be created.</param>
        /// <param name="listfile">List file <tt>\%APPDATA\%\\AcTools\\<prog_name\>\\<depot_name\>.streams</tt> for the
        /// <a href="https://www.microfocus.com/documentation/accurev/72/WebHelp/wwhelp/wwhimpl/js/html/wwhelp.htm#href=AccuRev_User_CLI/cli_ref_show.html">show -l <list-file> streams</a>
        /// command if found, otherwise \e null.<br>
        /// Example: <tt>"C:\Users\barnyrd\AppData\Roaming\AcTools\FooApp\NEPTUNE.streams"</tt>.</param>
        /// <returns>\e true if initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure
        /// to handle a range of exceptions.</exception>
        /*! \sa [AcStreams constructor](@ref AcUtils#AcStreams#AcStreams) */
        /*! \show_ <tt>show \<-fxig|-fxg\> -p \<depot\> [-l listfile] streams</tt> */

        /*! \accunote_ The following XML attributes from <tt>show -fx -p \<depot\> streams</tt> may exist depending on the version of AccuRev in use.
         * They are used internally by AccuRev and are not intended for customer usage. Micro Focus incident #3132463.
         * - \e eventStream: Efficient way to determine if the server process needs to fire the event trigger processing.
         * - \e eventStreamHWM: Used by GitCentric to track the high watermark for synchronization.
         * - \e hasProperties: Efficient way for the GUI to determine if the property icon is displayed in the StreamBrowser. */
        internal async Task <bool> initAsync(AcDepot depot, string listfile = null)
        {
            bool ret = false; // assume failure

            try
            {
                AcResult result = await AcCommand.runAsync($@"show {(_includeHidden ? "-fxig" : "-fxg")} -p ""{depot}""" +
                                                           $@"{((listfile == null) ? String.Empty : "-l " + "" + listfile + "")} streams")
                                  .ConfigureAwait(false);

                if (result != null && result.RetVal == 0)
                {
                    XElement xml = XElement.Parse(result.CmdResult);
                    IEnumerable <XElement> filter = null;
                    if (_dynamicOnly)
                    {
                        filter = from s in xml.Elements("stream")
                                 where (bool)s.Attribute("isDynamic") == true select s;
                    }
                    else
                    {
                        filter = from s in xml.Elements("stream") select s;
                    }

                    foreach (XElement e in filter)
                    {
                        AcStream stream = new AcStream();
                        stream.Name      = (string)e.Attribute("name");
                        stream.ID        = (int)e.Attribute("streamNumber");
                        stream.BasisName = (string)e.Attribute("basis") ?? String.Empty;
                        stream.BasisID   = (int?)e.Attribute("basisStreamNumber") ?? -1;
                        stream.Depot     = depot;
                        stream.IsDynamic = (bool)e.Attribute("isDynamic");
                        string type = (string)e.Attribute("type");
                        stream.Type = (StreamType)Enum.Parse(typeof(StreamType), type);
                        // attribute "time" only exists for snapshot streams (creation date) or when a dynamic stream has a time basis
                        stream.Time      = e.acxTime("time"); // time basis
                        stream.StartTime = (DateTime)e.acxTime("startTime");
                        // hidden attribute exists only if the stream is hidden
                        stream.Hidden          = (e.Attribute("hidden") != null);
                        stream.HasDefaultGroup = (bool)e.Attribute("hasDefaultGroup");
                        lock (_locker) { Add(stream); }
                    }

                    ret = true; // operation succeeded
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcStreams.initAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcStreams.initAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
        /// <summary>
        /// Use to retrieve the contents of a text file under version control.
        /// </summary>
        /// <remarks>
        /// Puts the content of the specified file in a temporary file. The caller is responsible for deleting the file.
        /// </remarks>
        /// <param name="eid">The file's element ID.</param>
        /// <param name="depot">The depot.</param>
        /// <param name="ver_spec">The version specification in the numeric or text format, e.g. \c 32/1 or \c PG_MAINT1_barnyrd\4.</param>
        /// <returns>A string initialized to the name of the temporary file with the contents from the
        /// AccuRev <tt>cat -v \<ver_spec\> -p \<depot\> -e \<eid\></tt> command on success, otherwise \e null on error.
        /// </returns>
        /*! \cat_ <tt>cat -v \<ver_spec\> -p \<depot\> -e \<eid\></tt> */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c cat command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \accunote_ The CLI \c cat command fails on Windows for ptext files larger than 62,733 bytes. Fixed in 6.0. AccuRev defect 28177. */

        /*! \accunote_ For the \c name, \c anc and \c cat commands, the validity of the results is guaranteed only if the commands are issued outside a workspace, or in a workspace whose
         *   backing stream is in the same depot for both workspace and the <tt>-v \<ver_spec\></tt> option used. If issued from a workspace that has a different backing stream than
         *   the <tt>-v \<ver_spec\></tt>, provided both workspace and ver_spec share the same depot, the command results can be deemed valid. However, if issued from a workspace whose
         *   backing stream is in a different depot than the <tt>-v \<ver_spec\></tt>, the command results are invalid. Applications should set the default directory to a non-workspace
         *   location prior to issuing these commands. AccuRev defects 18080, 21469, 1097778. */
        public static async Task <string> getCatFileAsync(int eid, AcDepot depot, string ver_spec)
        {
            string tmpFile = null;

            try
            {
                AcResult r = await AcCommand.runAsync($@"cat -v ""{ver_spec}"" -p ""{depot}"" -e {eid}")
                             .ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    tmpFile = Path.GetTempFileName();
                    using (StreamWriter streamWriter = new StreamWriter(tmpFile))
                    {
                        streamWriter.Write(r.CmdResult);
                    }
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcQuery.getCatFileAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx) // IOException, DirectoryNotFoundException, PathTooLongException, SecurityException... others
            {
                AcDebug.Log($"Exception caught and logged in AcQuery.getCatFileAsync{Environment.NewLine}{ecx.Message}");
            }

            return(tmpFile);
        }
        /// <summary>
        /// Get the number of active depots in the repository.
        /// </summary>
        /// <returns>Number of depots or <em>minus one (-1)</em> on error.</returns>
        /*! \show_ <tt>show -fx depots</tt> */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        public static async Task <int> getDepotsCountAsync()
        {
            int count = -1; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync("show -fx depots").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement t = XElement.Parse(r.CmdResult);
                    count = t.Elements("Element").Count();
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcQuery.getDepotsCountAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcQuery.getDepotsCountAsync{Environment.NewLine}{ecx.Message}");
            }

            return(count);
        }
        /// <summary>
        /// Get the number of dynamic streams in the repository that have a default group.
        /// </summary>
        /// <returns>Number of dynamic streams with a default group or <em>minus one (-1)</em> on error.</returns>
        /*! \show_ <tt>show -fx -d streams</tt> */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        public static async Task <int> getDynStreamsCountAsync()
        {
            int count = -1; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync("show -fx -d streams").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement s = XElement.Parse(r.CmdResult);
                    count = (from d in s.Elements("stream") where d.Attribute("isDynamic").Value == "true" select d).Count();
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcQuery.getDynStreamsCountAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcQuery.getDynStreamsCountAsync{Environment.NewLine}{ecx.Message}");
            }

            return(count);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// When this file exists (created manually), it is used as the \e list-file to populate the depot with select streams.
        /// This function is called internally and not by user code.
        /// </summary>
        /// <remarks>Implemented with <a href="https://www.microfocus.com/documentation/accurev/72/WebHelp/wwhelp/wwhimpl/js/html/wwhelp.htm#href=AccuRev_User_CLI/cli_ref_show.html">show -l <list-file> streams</a>
        /// </remarks>
/*! > -l <list-file> Process the streams listed in the specified file. The file must be text only, containing one stream name or number per line. Extra whitespace is not allowed; make sure there are no empty lines and no leading or trailing whitespace around the filenames. There is no provision for comment lines in a list-file. This option can also be used with one of -1 ("dash-one"), -r, or -R. You cannot also specify streams using the -s option. */
        /// <returns>Full path of the list file <tt>\%APPDATA\%\\AcTools\\<prog_name\>\\<depot_name\>.streams</tt> if found, otherwise \e null.<br>
        /// Example: <tt>"C:\Users\barnyrd\AppData\Roaming\AcTools\FooApp\NEPTUNE.streams"</tt>
        /// </returns>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>

        /*! \code
         *  list-file content:
         *  NEPTUNE_DEV3
         *  NEPTUNE_MAINT2
         *  ...
         *  AcDepot depot = new AcDepot("NEPTUNE"); // two-part object construction
         *  if (!(await depot.initAsync())) return false; // operation failed, check log file
         *  foreach (AcStream stream in depot.Streams.OrderBy(n => n))
         *      Console.WriteLine(stream.ToString("lv") + Environment.NewLine);
         *  ...
         *  NEPTUNE_DEV3 (10) {normal}
         *  Basis: NEPTUNE_UAT (8)
         *  Depot: NEPTUNE, Hidden: False, HasDefaultGroup: True
         *
         *  NEPTUNE_MAINT2 (6) {normal}
         *  Basis: NEPTUNE_MAINT (4)
         *  Depot: NEPTUNE, Hidden: False, HasDefaultGroup: False
         *  \endcode */
        internal string listFile()
        {
            string listfile = null;

            try
            {
                string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string actools = Path.Combine(appdata, "AcTools");
                string exeroot = String.Empty;
                using (Process currentProcess = Process.GetCurrentProcess())
                {
                    ProcessModule pm = currentProcess.MainModule;
                    exeroot = Path.GetFileNameWithoutExtension(pm.ModuleName);
                }

                string progfolder = Path.Combine(actools, exeroot);
                string temp       = Path.Combine(progfolder, Name);
                string file       = Path.ChangeExtension(temp, "streams");
                if (File.Exists(file))
                {
                    listfile = file;
                }
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcDepot.listFile{Environment.NewLine}{ecx.Message}");
            }

            return(listfile);
        }
        /// <summary>
        /// Get the depot-relative path for the element in \e stream with \e EID.
        /// Also returns the element's parent folder EID (folder where the element resides).
        /// </summary>
        /// <param name="stream">Name of the stream where the element resides.</param>
        /// <param name="EID">The element ID of the element on which to query.</param>
        /// <returns>An tuple initialized as <em>{depot-relative path, parent EID}</em> on success, otherwise \e null.</returns>
        /*! \name_ <tt>name -v \<stream\> -fx -e \<EID\></tt> */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c name command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>

        /*! \code
         * accurev name -v MARS_MAINT2 -fx -e 13763
         * <?xml version="1.0" encoding="utf-8"?>
         * <AcResponse
         *  Command="name"
         *  TaskId="51498">
         * <element
         *    location="\.\scripts\build.xml"
         *    parent_id="12269"/>
         * </AcResponse>
         * \endcode */
        /*! \accunote_ For the \c name, \c anc and \c cat commands, the validity of the results is guaranteed only if the commands are issued outside a workspace, or in a workspace whose
         *   backing stream is in the same depot for both workspace and the <tt>-v \<ver_spec\></tt> option used. If issued from a workspace that has a different backing stream than
         *   the <tt>-v \<ver_spec\></tt>, provided both workspace and ver_spec share the same depot, the command results can be deemed valid. However, if issued from a workspace whose
         *   backing stream is in a different depot than the <tt>-v \<ver_spec\></tt>, the command results are invalid. Applications should set the default directory to a non-workspace
         *   location prior to issuing these commands. AccuRev defects 18080, 21469, 1097778. */
        public static async Task <Tuple <string, int> > getElementNameAsync(string stream, int EID)
        {
            Tuple <string, int> ret = null; // depot-relative path, parent folder EID

            try
            {
                AcResult r = await AcCommand.runAsync($@"name -v ""{stream}"" -fx -e {EID}").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement xml       = XElement.Parse(r.CmdResult);
                    string   location  = (string)xml.Element("element").Attribute("location");
                    int      parent_id = (int)xml.Element("element").Attribute("parent_id");
                    ret = Tuple.Create(location, parent_id);
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcQuery.getElementNameAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcQuery.getElementNameAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
        /// <summary>
        /// Convert AcResult.CmdResult XML from \e result into AcWorkspace objects and add them to our container.
        /// Filters out workspace/ref trees that are not in the user's default list of depots they can view based on ACL permissions.
        /// </summary>
        /// <param name="result">Previously initialized AcResult object from AcWorkspaces.getWorkspacesXMLAsync and AcWorkspaces.getReferenceTreesXMLAsync.</param>
        /// <param name="depot">Specify a depot to limit the query to workspaces and ref trees in \e depot only, not the users default list of depots.</param>
        /// <returns>\e true if object initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
        private bool storeWSpaces(AcResult result, AcDepot depot = null)
        {
            bool ret = false; // assume failure

            try
            {
                // filter out workspace/ref trees not in the user's default list
                XElement xml = XElement.Parse(result.CmdResult);
                IEnumerable <XElement> filter;
                if (depot != null)
                {
                    filter = from w in xml.Elements("Element")
                             join AcDepot d in _depots on
                                 (string) w.Attribute("depot") equals d.Name
                                 where (string)w.Attribute("depot") == depot.Name
                             select w;
                }
                else
                {
                    filter = from w in xml.Elements("Element")
                             join AcDepot d in _depots on
                                 (string) w.Attribute("depot") equals d.Name
                             select w;
                }

                foreach (XElement e in filter)
                {
                    AcWorkspace ws = new AcWorkspace();
                    ws.Name     = (string)e.Attribute("Name");
                    ws.Hidden   = (e.Attribute("hidden") != null); // attribute hidden exists only when true
                    ws.Location = (string)e.Attribute("Loc");
                    ws.Storage  = (string)e.Attribute("Storage");
                    ws.Host     = (string)e.Attribute("Host");
                    ws.ID       = (int)e.Attribute("Stream");
                    string temp = (string)e.Attribute("depot");
                    ws.Depot       = _depots.getDepot(temp);
                    ws.TargetLevel = (int)e.Attribute("Target_trans");
                    ws.UpdateLevel = (int)e.Attribute("Trans");
                    ws.FileModTime = e.acxTime("fileModTime");
                    int type = (int)e.Attribute("Type");
                    ws.Type = (WsType)type;
                    int eol = (int)e.Attribute("EOL");
                    ws.EOL            = (WsEOL)eol;
                    ws.Principal.ID   = (int)e.Attribute("user_id");
                    ws.Principal.Name = (string)e.Attribute("user_name");
                    lock (_locker) { Add(ws); }
                }

                ret = true; // operation succeeded
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcWorkspaces.storeWSpaces{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
        /// <summary>
        /// Populate this list with elements from the XML emitted by the 
        /// [stat](https://www.microfocus.com/documentation/accurev/72/WebHelp/wwhelp/wwhimpl/js/html/wwhelp.htm#href=AccuRev_User_CLI/cli_ref_stat.html) command.
        /// </summary>
        /// <param name="xml">XML from the AccuRev \c stat command.</param>
        /// <returns>\e true if parsing was successful, \e false otherwise.</returns>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) 
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
        public static bool init(string xml)
        {
            bool ret = false; // assume failure
            try
            {
                XElement elements = XElement.Parse(xml);
                IEnumerable<XElement> query = from e in elements.Elements("element")
                                              where !e.Attribute("status").Value.Contains("no such elem")
                                              select e;
                foreach (XElement e in query)
                {
                    Element element = new Element();
                    element.Status = (string)e.Attribute("status") ?? String.Empty;
                    element.Location = (string)e.Attribute("location") ?? String.Empty;
                    string dir = (string)e.Attribute("dir") ?? String.Empty;
                    element.Folder = String.Equals(dir, "yes");
                    string exe = (string)e.Attribute("executable") ?? String.Empty;
                    element.Executable = String.Equals(exe, "yes");
                    element.EID = (int?)e.Attribute("id") ?? 0;
                    element.ElementType = e.acxType("elemType");
                    element.Size = (long?)e.Attribute("size");
                    element.ModTime = e.acxTime("modTime");
                    element.HierType = (string)e.Attribute("hierType") ?? String.Empty;
                    int ival;
                    string vir = (string)e.Attribute("Virtual") ?? String.Empty;
                    if (!String.IsNullOrEmpty(vir))
                    {
                        string[] arrVir = vir.Split('\\');
                        if (Int32.TryParse(arrVir[0], NumberStyles.Integer, null, out ival))
                            element.VirStreamNumber = ival;
                        if (Int32.TryParse(arrVir[1], NumberStyles.Integer, null, out ival))
                            element.VirVersionNumber = ival;
                    }
                    element.NamedVersion = (string)e.Attribute("namedVersion") ?? String.Empty;
                    string real = (string)e.Attribute("Real") ?? String.Empty;
                    if (!String.IsNullOrEmpty(real))
                    {
                        string[] arrReal = real.Split('\\');
                        if (Int32.TryParse(arrReal[0], NumberStyles.Integer, null, out ival))
                            element.RealStreamNumber = ival;
                        if (Int32.TryParse(arrReal[1], NumberStyles.Integer, null, out ival))
                            element.RealVersionNumber = ival;
                    }
                    element.LapStream = (string)e.Attribute("overlapStream") ?? String.Empty;
                    element.TimeBasedStream = (string)e.Attribute("timeBasisStream") ?? String.Empty;
                    lock (_locker) { _elements.Add(element); }
                }

                ret = true; // operation succeeded
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in Stat.init{Environment.NewLine}{ecx.Message}");
            }

            return ret;
        }
        /// <summary>
        /// Populate this container with AcProperty objects for all streams in \e depot or just \e stream in \e depot.
        /// Optionally include hidden (removed) streams.
        /// </summary>
        /// <param name="depot">The depot to query for properties.</param>
        /// <param name="stream">The stream for a specific stream only, otherwise \e null for all streams in \e depot.</param>
        /// <param name="includeHidden">\e true to include properties for hidden (removed) streams, \e false otherwise.</param>
        /// <returns>\e true if initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
        /// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c getproperty command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa [AcProperties constructor](@ref AcUtils#AcProperties#AcProperties), initAsync(string, bool) */
        /*! \getproperty_ <tt>getproperty \<-fx | -fix\> \<-s \<stream\> | -ks -p \<depot\>\></tt> */
        public async Task <bool> initAsync(AcDepot depot, AcStream stream = null, bool includeHidden = false)
        {
            bool ret = false; // assume failure

            try
            {
                string cmd = null;
                if (stream != null && includeHidden)
                {
                    cmd = $@"getproperty -fix -s ""{stream}""";
                }
                else if (stream != null && !includeHidden)
                {
                    cmd = $@"getproperty -fx -s ""{stream}""";
                }
                else if (includeHidden) // request is for all streams in depot including those that are hidden
                {
                    cmd = $@"getproperty -fix -ks -p ""{depot}""";
                }
                else  // request is for all streams except those that are hidden
                {
                    cmd = $@"getproperty -fx -ks -p ""{depot}""";
                }

                AcResult r = await AcCommand.runAsync(cmd).ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    foreach (XElement e in xml.Elements("property"))
                    {
                        AcProperty property = new AcProperty();
                        string     kind     = (string)e.Attribute("kind");
                        property.Kind      = (PropKind)Enum.Parse(typeof(PropKind), kind);
                        property.Depot     = depot;
                        property.ID        = (int)e.Attribute("streamNumber");
                        property.Name      = (string)e.Attribute("streamName");
                        property.PropName  = (string)e.Attribute("propertyName");
                        property.PropValue = (string)e;
                        lock (_locker) { Add(property); }
                    }

                    ret = true; // operation succeeded
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcProperties.initAsync(AcDepot, AcStream, bool){Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcProperties.initAsync(AcDepot, AcStream, bool){Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Populate this container with AcUser objects as per [constructor parameters](@ref AcUtils#AcUsers#AcUsers).
        /// </summary>
        /// <param name="progress">Optionally report progress back to the caller.</param>
        /// <returns>\e true if list initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
        /// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \show_ <tt>show \<-fx | -fix\> users</tt> */
        public async Task <bool> initAsync(IProgress <int> progress = null)
        {
            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync($"show {(_includeDeactivated ? "-fix" : "-fx")} users")
                             .ConfigureAwait(false);

                if (r != null && r.RetVal == 0) // if command succeeded
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    IEnumerable <XElement>   query = from element in xml.Elements("Element") select element;
                    List <Task <bool> >      tasks = new List <Task <bool> >(query.Count());
                    Func <Task <bool>, bool> cf    = t =>
                    {
                        bool res = t.Result;
                        if (res && progress != null)
                        {
                            progress.Report(Interlocked.Increment(ref _counter));
                        }
                        return(res);
                    };

                    foreach (XElement e in query)
                    {
                        string name = (string)e.Attribute("Name");
                        int    id   = (int)e.Attribute("Number");
                        // XML attribute isActive exists only if the user is inactive, otherwise it isn't there
                        PrinStatus status = (e.Attribute("isActive") == null) ? PrinStatus.Active : PrinStatus.Inactive;
                        AcUser     user   = new AcUser(id, name, status);
                        lock (_locker) { Add(user); }
                        Task <bool> t = initUserPropsAsync(user).ContinueWith(cf);
                        tasks.Add(t);
                    }

                    bool[] arr = await Task.WhenAll(tasks).ConfigureAwait(false);

                    ret = (arr != null && arr.All(n => n == true));
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcUsers.initAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcUsers.initAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
        /// <summary>
        /// Determines if \e user is a member of \e group by way of direct or indirect (implicit) membership,
        /// e.g. Mary is implicitly a member of groupA because she's a member of groupB which is a member of groupA.
        /// </summary>
        /// <param name="user">AccuRev principal name of \e user.</param>
        /// <param name="group">AccuRev principal name of \e group.</param>
        /// <returns>\e true if \e user is a member of \e group or \e false if not a member.</returns>
        /// <exception cref="AcUtilsException">thrown on AccuRev program invocation failure for the \c ismember command.</exception>
        /// <exception cref="Win32Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on error spawning the AccuRev process that runs the command.</exception>
        /// <exception cref="InvalidOperationException">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa [AcGroups.getMembers](@ref AcUtils#AcGroups#getMembers), [AcUser.getGroups](@ref AcUtils#AcUser#getGroups) */
        /*! \ismember_ <tt>ismember \<user\> \<group\></tt> */

        /*! \note The AccuRev program return value for \c ismember is <em>zero (0)</em> whether the user is a member of the group or not.
         *   It is the command's output (STDOUT) that is \"<b>1</b>\" (\e one) if the user is a member of the group or \"<b>0</b>\" (\e zero) if not a member. */
        /*! \warning The server admin trigger must return <em>zero (0)</em> for \c ismember to prevent an endless recursive loop. */
        public static bool isMember(string user, string group)
        {
            bool   ret     = false; // assume not a member
            string command = String.Format(@"ismember ""{0}"" ""{1}""", user, group);

            try
            {
                using (Process process = new Process())
                {
                    process.StartInfo.FileName               = "accurev";
                    process.StartInfo.Arguments              = command;
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.CreateNoWindow         = true;
                    process.StartInfo.RedirectStandardInput  = true; // fix for AccuRev defect 29059
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                    process.StartInfo.StandardErrorEncoding  = Encoding.UTF8;
                    process.ErrorDataReceived += new DataReceivedEventHandler(AcDebug.errorDataHandler);
                    process.Start();
                    process.BeginErrorReadLine();
                    string result = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    if (process.ExitCode == 0)
                    {
                        if (result.Length > 0 && result[0] == '1')
                        {
                            ret = true;
                        }
                    }
                    else
                    {
                        string err = String.Format("AccuRev program return: {0}{1}{2}", process.ExitCode, Environment.NewLine, "accurev " + command);
                        throw new AcUtilsException(err); // let calling method handle
                    }
                }
            }

            catch (Win32Exception ecx)
            {
                string msg = String.Format("Win32Exception caught and logged in AcGroups.isMember{0}{1}{0}accurev {2}{0}errorcode: {3}{0}native errorcode: {4}{0}{5}{0}{6}{0}{7}",
                                           Environment.NewLine, ecx.Message, command, ecx.ErrorCode.ToString(), ecx.NativeErrorCode.ToString(), ecx.StackTrace, ecx.Source, ecx.GetBaseException().Message);
                AcDebug.Log(msg);
            }

            catch (InvalidOperationException ecx)
            {
                string msg = String.Format("InvalidOperationException caught and logged in AcGroups.isMember{0}{1}{0}accurev {2}",
                                           Environment.NewLine, ecx.Message, command);
                AcDebug.Log(msg);
            }

            return(ret);
        }
        /// <summary>
        /// Populate this container with AcRule objects for all streams in \e streamsCol
        /// as per [constructor parameter](@ref AcUtils#AcRules#AcRules) \e explicitOnly.
        /// </summary>
        /// <param name="streamsCol">The list of streams to query for rules.</param>
        /// <param name="progress">Optionally report progress back to the caller.</param>
        /// <returns>\e true if no failure occurred and list was initialized successfully, \e false otherwise.</returns>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
        /// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
        public async Task <bool> initAsync(StreamsCollection streamsCol, IProgress <int> progress = null)
        {
            bool ret = false; // assume failure

            try
            {
                AcDepots depots = new AcDepots();
                if (!(await depots.initAsync(null, progress).ConfigureAwait(false)))
                {
                    return(false);
                }
                int num = 0; // get number of streams for tasks list
                foreach (AcDepot depot in depots)
                {
                    IEnumerable <AcStream> filter = depot.Streams.Where(s =>
                                                                        streamsCol.OfType <StreamElement>().Any(se => s.Name == se.Stream));
                    num += filter.Count();
                }

                List <Task <bool> >      tasks = new List <Task <bool> >(num);
                Func <Task <bool>, bool> cf    = t =>
                {
                    bool res = t.Result;
                    if (res && progress != null)
                    {
                        progress.Report(Interlocked.Increment(ref _counter));
                    }
                    return(res);
                };

                foreach (AcDepot depot in depots)
                {
                    IEnumerable <AcStream> filter = depot.Streams.Where(s =>
                                                                        streamsCol.OfType <StreamElement>().Any(se => s.Name == se.Stream));
                    foreach (AcStream stream in filter)
                    {
                        Task <bool> t = initAsync(stream).ContinueWith(cf);
                        tasks.Add(t);
                    }
                }

                bool[] arr = await Task.WhenAll(tasks).ConfigureAwait(false);

                ret = (arr != null && arr.All(n => n == true)); // true if all succeeded
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcRules.initAsync(StreamsCollection){Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initialize this AcDepot object with data from AccuRev as per constructor parameter's depot \e name or \e ID number.
        /// </summary>
        /// <returns>\e true if initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa AcDepot(string, bool, bool), AcDepot(int, bool, bool), [AcDepots constructor](@ref AcUtils#AcDepots#AcDepots) */
        /*! \show_ <tt>show -fx depots</tt> */
        public async Task <bool> initAsync()
        {
            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync("show -fx depots").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    IEnumerable <XElement> filter = null;
                    if (_id > 0)
                    {
                        filter = from element in xml.Elements("Element")
                                 where (int)element.Attribute("Number") == _id
                                 select element;
                    }
                    else
                    {
                        filter = from element in xml.Elements("Element")
                                 where (string)element.Attribute("Name") == _name
                                 select element;
                    }

                    XElement e = filter.SingleOrDefault();
                    if (e != null)
                    {
                        ID               = (int)e.Attribute("Number");
                        Name             = (string)e.Attribute("Name");
                        Slice            = (int)e.Attribute("Slice");
                        ExclusiveLocking = (bool)e.Attribute("exclusiveLocking");
                        string temp = (string)e.Attribute("case");
                        Case     = (CaseSensitivity)Enum.Parse(typeof(CaseSensitivity), temp);
                        _streams = new AcStreams(_dynamicOnly, _includeHidden);
                        ret      = await _streams.initAsync(this, listFile()).ConfigureAwait(false);
                    }
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcDepot.initAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcDepot.initAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Centralized error handler.
 /// </summary>
 /// <param name="sendingProcess">The spawned process.</param>
 /// <param name="errLine">The error message sent to this method by the spawned process.</param>
 public static void errorDataHandler(object sendingProcess, DataReceivedEventArgs errLine)
 {
     if (!String.IsNullOrEmpty(errLine.Data))
     {
         string errline = errLine.Data.Trim();
         // Report error if something other than "not in a directory associated with a workspace"
         if (errline.Length > 0 &&
             !String.Equals("You are not in a directory associated with a workspace", errline))
         {
             AcDebug.Log(errline);
         }
     }
 }
        /// <summary>
        /// Determines if the current user is logged into AccuRev and, if so, retrieves their principal name.
        /// </summary>
        /// <remarks>Implemented by extracting the user's principal name or string <b>\"(not logged in)\"</b> from the \c info command results.</remarks>
        /// <returns>A string initialized to the name of the principal logged into AccuRev or \e null if not logged in.</returns>
        /*! \info_ \c info */

        /*! \accunote_ To support GUIs logging into replicas, get host and port from \c info command
         *  (instead of from XML \<serverInfo\> results, which are not correct for replica)
         *  to use in titlebar, preferences.xml, and MQTT messages. 35934/17776122 (35921/17776020) */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c info command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>

        /*! \note The user must have <tt>AccuRev\\bin</tt> in their \e Path environment variable to run
         *   AccuRev commands issued by the AcUtils library. Since this method is often the first function called
         *   by a client application (in this case \c info), a failure here usually means this entry is missing.*/
        public static async Task <string> getPrincipalAsync()
        {
            string prncpl = null;

            try
            {
                AcResult r = await AcCommand.runAsync("info").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    using (StringReader reader = new StringReader(r.CmdResult))
                    {
                        bool?  login = null; // don't know yet
                        string line;
                        char[] sep = new char[] { ':' };
                        while ((line = reader.ReadLine()) != null && login == null)
                        {
                            string[] arr = line.Split(sep); // "Principal:      barnyrd"
                            if (arr.Length == 2)
                            {
                                if (String.Equals(arr[0], "Principal"))
                                {
                                    string temp = arr[1].Replace("\t", "");
                                    if (String.Equals(temp, "(not logged in)"))
                                    {
                                        login = false;
                                    }
                                    else
                                    {
                                        prncpl = temp; // AccuRev principal name
                                        login  = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcQuery.getPrincipalAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcQuery.getPrincipalAsync{Environment.NewLine}{ecx.Message}");
            }

            return(prncpl); // principal name or null if not logged in
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Get the depot's stream and workspace (optional) hierarchy relationship data from AccuRev.
        /// This method is called internally and not by user code.
        /// </summary>
        /// <param name="includeWSpaces">\e true to include workspaces in the list.</param>
        /// <returns>Fully initialized [MultiValueDictionary](https://www.nuget.org/packages/Microsoft.Experimental.Collections)
        /// object for the depot with [parent(key),children(values)] basis/stream ID's if no exception was thrown
        /// and the operation succeeded, otherwise \e null on error.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>

        /*! \pre Using \e includeWSpaces to include workspaces in the list requires that all stream types be specified at AcDepot
         *   object creation as per the \e dynamicOnly=false (default) constructor parameter. */
        /*! \show_ <tt>show -p \<depot\> [-fix | -fx] -s 1 -r streams</tt> */

        /*! \attention This method requires that you deploy
         *  <a href="https://www.nuget.org/packages/Microsoft.Experimental.Collections">Microsoft.Experimental.Collections.dll</a> with your application. */
        private async Task <MultiValueDictionary <int, int> > getHierarchyAsync(bool includeWSpaces = false)
        {
            MultiValueDictionary <int, int> hierarchy = null;

            try
            {
                AcResult r = await AcCommand.runAsync($@"show -p ""{this}"" {(_includeHidden ? " -fix" : " -fx")} -s 1 -r streams")
                             .ConfigureAwait(false);

                if (r != null && r.RetVal == 0) // if command succeeded
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    IEnumerable <XElement> filter;
                    if (includeWSpaces)
                    {
                        filter = from s in xml.Elements("stream")
                                 select s;
                    }
                    else
                    {
                        filter = from s in xml.Elements("stream")
                                 where (string)s.Attribute("type") != "workspace" // all except workspaces
                                 select s;
                    }

                    int capacity = filter.Count();
                    hierarchy = new MultiValueDictionary <int, int>(capacity);
                    foreach (XElement e in filter)
                    {
                        // XML attribute basisStreamNumber does not exist in the case of root streams
                        int parent = (int?)e.Attribute("basisStreamNumber") ?? -1;
                        int child  = (int)e.Attribute("streamNumber");
                        hierarchy.Add(parent, child);
                    }
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcDepot.getHierarchyAsync{Environment.NewLine}{ecx.Message}");
                hierarchy = null;
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcDepot.getHierarchyAsync{Environment.NewLine}{ecx.Message}");
                hierarchy = null;
            }

            return(hierarchy);
        }
        /// <summary>
        /// Retrieves the AccuRev program major, minor and patch version numbers.
        /// </summary>
        /// <returns>An array initialized as <em>int[]={major, minor, patch}</em> on success, otherwise \e null on error.</returns>
        /*! \xml_ <tt>xml -l \<xmlfile\></tt> */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c xml command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>

        /*! \code
         * <?xml version="1.0" encoding="utf-8"?>
         * <serverInfo>
         * <serverVersion
         *    major="5"
         *    minor="6"
         *    patch="0"/>
         * <serverHostPort>machine_name_omitted:5050</serverHostPort>
         * </serverInfo>
         * \endcode */
        public static async Task <int[]> getAccuRevVersionAsync()
        {
            int[]  arr      = null; // major, minor, patch
            string tempFile = null;

            try
            {
                tempFile = Path.GetTempFileName(); // the AccuRev xml command requires a file as its argument
                using (StreamWriter streamWriter = new StreamWriter(tempFile))
                {
                    streamWriter.Write(@"<serverInfo/>"); // set up the query
                }

                AcResult r = await AcCommand.runAsync($@"xml -l ""{tempFile}""").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    using (StringReader reader = new StringReader(r.CmdResult))
                    {
                        XElement doc   = XElement.Load(reader);
                        XElement sv    = doc.Element("serverVersion");
                        int      major = (int)sv.Attribute("major");
                        int      minor = (int)sv.Attribute("minor");
                        int      patch = (int)sv.Attribute("patch");
                        arr = new int[] { major, minor, patch };
                    }
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcQuery.getAccuRevVersionAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcQuery.getAccuRevVersionAsync{Environment.NewLine}{ecx.Message}");
            }

            finally
            {
                if (tempFile != null)
                {
                    File.Delete(tempFile);
                }
            }

            return(arr);
        }
        /// <summary>
        /// Initialize our task scheduler that allows no more than n tasks to execute simultaneously.
        /// </summary>

        /*! \sa [LimitedConcurrencyLevelTaskScheduler](@ref System#Threading#Tasks#Schedulers#LimitedConcurrencyLevelTaskScheduler),
         * <a href="https://blogs.msdn.microsoft.com/pfxteam/2010/04/09/parallelextensionsextras-tour-7-additional-taskschedulers/">ParallelExtensionsExtras Tour - #7 - Additional TaskSchedulers</a> */
        static AcCommand()
        {
            try
            {
                string maxconcurrent = Environment.GetEnvironmentVariable("ACUTILS_MAXCONCURRENT");
                int    max           = (maxconcurrent != null) ? Int32.Parse(maxconcurrent) : MaxConcurrencyDefault;
                LimitedConcurrencyLevelTaskScheduler ts = new LimitedConcurrencyLevelTaskScheduler(max);
                _taskFactory = new TaskFactory(ts);
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcCommand constructor{Environment.NewLine}{ecx.Message}");
            }
        }
        /// <summary>
        /// Populate this container with AcRule objects for all streams in \e depotsCol
        /// as per [constructor parameter](@ref AcUtils#AcRules#AcRules) \e explicitOnly.
        /// </summary>
        /// <param name="depotsCol">The list of depots to query for rules.</param>
        /// <param name="progress">Optionally report progress back to the caller.</param>
        /// <returns>\e true if no failure occurred and list was initialized successfully, \e false otherwise.</returns>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
        /// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
        public async Task <bool> initAsync(DepotsCollection depotsCol, IProgress <int> progress = null)
        {
            bool ret = false; // assume failure

            try
            {
                AcDepots depots = new AcDepots();
                if (!(await depots.initAsync(depotsCol, progress).ConfigureAwait(false)))
                {
                    return(false);
                }
                int num = 0; // get number of streams for tasks list
                foreach (AcDepot depot in depots)
                {
                    num += depot.Streams.Count();
                }
                List <Task <bool> >      tasks = new List <Task <bool> >(num);
                Func <Task <bool>, bool> cf    = t =>
                {
                    bool res = t.Result;
                    if (res && progress != null)
                    {
                        progress.Report(Interlocked.Increment(ref _counter));
                    }
                    return(res);
                };

                foreach (AcStream stream in depots.SelectMany(d => d.Streams))
                {
                    Task <bool> t = initAsync(stream).ContinueWith(cf);
                    tasks.Add(t);
                }

                bool[] arr = await Task.WhenAll(tasks).ConfigureAwait(false);

                ret = (arr != null && arr.All(n => n == true));
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcRules.initAsync(DepotsCollection){Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Populate this container with AcLock objects on streams in \e depots.
        /// </summary>
        /// <param name="depots">Limit the list of locks to those on streams in \e depots only. Depot names in \e depots
        /// must match their respective AccuRev depot name exactly.</param>
        /// <returns>\e true if initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa [AcLocks constructor](@ref AcUtils#AcLocks#AcLocks), initAsync(AcDepot), initAsync(StreamsCollection) */
        /*! \show_ <tt>show -fx locks</tt> */
        public async Task <bool> initAsync(DepotsCollection depots)
        {
            AcDepots dlist = new AcDepots();

            if (!(await dlist.initAsync(depots).ConfigureAwait(false)))
            {
                return(false);
            }

            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync("show -fx locks").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    bool     result = true;
                    XElement xml    = XElement.Parse(r.CmdResult);
                    for (int ii = 0; ii < dlist.Count && result; ii++)
                    {
                        AcDepot depot = dlist[ii];
                        IEnumerable <XElement> query = from e in xml.Elements("Element")
                                                       join AcStream s in depot.Streams on(string) e.Attribute("Name") equals s.Name
                                                       select e;

                        result = initList(query);
                    }

                    ret = result;
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcLocks.initAsync(DepotsCollection){Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcLocks.initAsync(DepotsCollection){Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Put a \c lock on \e stream as per lock \e kind.
        /// </summary>
        /// <param name="stream">Name of stream or workspace to lock.</param>
        /// <param name="comment">Comment to be used for the lock.</param>
        /// <param name="kind">Type of lock to apply: \e to, \e from, or \e all.</param>
        /// <param name="prncpl">AccuRev principal name of user or group in the case of \e to or \e from lock.</param>
        /// <param name="onlyexcept">Apply \c lock to \e prncpl only or to all except \e prncpl.</param>
        /// <returns>\e true if operation succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c lock command failure.</exception>
        /*! \lock_ <tt>lock -c \<comment\> [-kf [-e|-o prncpl] | -kt [-e|-o prncpl]] \<stream\></tt> */
        /*! \accunote_ The CLI \c lock command can be used on a workspace stream but the same cannot be done using the AccuRev GUI client. AccuRev defect 23850. */
        public async Task <bool> lockAsync(string stream, string comment, LockKind kind = LockKind.all, AcPrincipal prncpl = null, OnlyExcept onlyexcept = OnlyExcept.Except)
        {
            bool ret = false; // assume failure

            try
            {
                string cmd = null;
                if (kind == LockKind.from)
                {
                    if (prncpl != null)
                    {
                        cmd = $@"lock -c ""{comment}"" -kf {((onlyexcept == OnlyExcept.Except) ? "-e" : "-o")} ""{prncpl}"" ""{stream}""";
                    }
                    else
                    {
                        cmd = $@"lock -c ""{comment}"" -kf ""{stream}""";  // lock 'from' for all
                    }
                }
                else if (kind == LockKind.to)
                {
                    if (prncpl != null)
                    {
                        cmd = $@"lock -c ""{comment}"" -kt {((onlyexcept == OnlyExcept.Except) ? "-e" : "-o")} ""{prncpl}"" ""{stream}""";
                    }
                    else
                    {
                        cmd = $@"lock -c ""{comment}"" -kt ""{stream}"""; // lock 'to' for all
                    }
                }
                else if (kind == LockKind.all)
                {
                    cmd = $@"lock -c ""{comment}"" ""{stream}"""; // lock 'to and from' for all
                }
                AcResult r = await AcCommand.runAsync(cmd).ConfigureAwait(false);

                ret = (r != null && r.RetVal == 0);
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException in AcLocks.lockAsync caught and logged.{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
        //@}
        #endregion

        /// <summary>
        /// Get the list of workspaces in XML for all or the current user and optionally include
        /// inactive workspaces as per [AcWorkspaces constructor](@ref AcUtils#AcWorkspaces#AcWorkspaces) \e includeHidden parameter.
        /// </summary>
        /// <returns>AcResult initialized with the \c show command results, otherwise \e null on error.</returns>
        /*! \show_ <tt>show \<-fvx | -fvix\> \<-a | \> wspaces</tt> */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on <tt>show wspaces</tt> command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa AcWorkspaces.getReferenceTreesXMLAsync */
        private async Task <AcResult> getWorkspacesXMLAsync()
        {
            AcResult result = null;

            try
            {
                string cmd = null;
                // for all below, -v option adds the Loc (location) to output
                if (_allWSpaces && _includeHidden)
                {
                    // All workspaces, not just those that belong to the principal. Include deactivated workspaces.
                    cmd = "show -fvix -a wspaces"; // -a is the only option available for show wspaces
                }
                else if (_allWSpaces && !_includeHidden)
                {
                    // All workspaces, not just those that belong to the principal. Do not include deactivated workspaces.
                    cmd = "show -fvx -a wspaces";
                }
                else if (!_allWSpaces && _includeHidden)
                {
                    // Only those workspaces that belong to the principal. Include deactivated workspaces.
                    cmd = "show -fvix wspaces";
                }
                else if (!_allWSpaces && !_includeHidden)
                {
                    // Only those workspaces that belong to the principal. Do not include deactivated workspaces.
                    cmd = "show -fvx wspaces";
                }
                result = await AcCommand.runAsync(cmd).ConfigureAwait(false);
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcWorkspaces.getWorkspacesXMLAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcWorkspaces.getWorkspacesXMLAsync{Environment.NewLine}{ecx.Message}");
            }

            return(result);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Populate this container with AcSession objects, the currently active login sessions.
        /// </summary>
        /// <returns>\e true if no failure occurred and list was initialized successfully, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
        /// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \show_ <tt>show -fx sessions</tt> */
        public async Task <bool> initAsync()
        {
            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync("show -fx sessions").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    foreach (XElement e in xml.Elements("Element"))
                    {
                        AcSession session = new AcSession();
                        session.Name = (string)e.Attribute("Username");
                        session.Host = (string)e.Attribute("Host");
                        string temp = (string)e.Attribute("Duration");
                        if (!String.Equals(temp, "(timed out)"))
                        {
                            double duration = double.Parse(temp);
                            session.Duration = TimeSpan.FromMinutes(duration);
                        }

                        lock (_locker) { Add(session); }
                    }

                    ret = true; // operation succeeded
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcSessions.initAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcSessions.initAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Convert an AccuRev date given in Unix time (\e seconds param) to a .NET DateTime in local time.
        /// </summary>
        /// <param name="seconds">Unix time expressed as the number of seconds since January 1, 1970 UTC.</param>
        /// <returns>DateTime object with the converted value or \e null on error or \e seconds equal <em>zero (0)</em>.</returns>
        /// <exception cref="ArgumentOutOfRangeException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to convert \e seconds
        /// to a date and time value that represents the same moment in time as the Unix time.</exception>
        /*! \sa <a href="_latest_promotions_8cs-example.html">LatestPromotions.cs</a> */
        public static DateTime?AcDate2DateTime(long seconds)
        {
            DateTime?dt = null;

            try
            {
                if (seconds > 0)
                {
                    DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(seconds);
                    dt = dto.DateTime.ToLocalTime();
                }
            }

            catch (ArgumentOutOfRangeException ecx)
            {
                AcDebug.Log($"ArgumentOutOfRangeException caught and logged in AcDateTime.AcDate2DateTime{Environment.NewLine}{ecx.Message}");
            }

            return(dt);
        }
        /// <summary>
        /// Populate this container with AcRule objects for \e stream as per
        /// [constructor parameter](@ref AcUtils#AcRules#AcRules) \e explicitOnly.
        /// </summary>
        /// <param name="stream">The stream to query for rules.</param>
        /// <returns>\e true if no failure occurred and list was initialized successfully, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
        /// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c lsrules command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \lsrules_ <tt>lsrules -s \<stream\> [-d] -fx</tt>  */

        /*! \code
         *  <!-- accurev lsrules -s "PG_DEV1" -fx -->
         *  <AcResponse
         *    Command="lscomp"
         *    TaskId="54394">
         *    <element
         *      kind="incl"
         *      elemType="dir"
         *      dir="yes" // Not used as its redundant. We use ElementType.Dir instead.
         *      location="\.\Iconic"
         *      setInStream="PG_DEV1"
         *      xlinkToStream="IC_DEV1"
         *      options="1"/> // Obsolete. Was used for compatibility of rules in version 4.5.3 and earlier. Will always be a value of 1.
         *    <element
         *      kind="incl"
         *      elemType="dir"
         *      dir="yes"
         *      location="\.\"
         *      setInStream="PlayGround"
         *      options="1"/>
         *  </AcResponse>
         *  \endcode */
        public async Task <bool> initAsync(AcStream stream)
        {
            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync($@"lsrules -s ""{stream}"" {(_explicitOnly ? "-d" : String.Empty)} -fx")
                             .ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    foreach (XElement e in xml.Elements("element"))
                    {
                        AcRule rule = new AcRule();
                        string kind = (string)e.Attribute("kind");
                        rule.Kind = (RuleKind)Enum.Parse(typeof(RuleKind), kind);
                        string type = (string)e.Attribute("elemType");
                        rule.Type          = (ElementType)Enum.Parse(typeof(ElementType), type);
                        rule.Location      = (string)e.Attribute("location");
                        rule.SetInStream   = (string)e.Attribute("setInStream");
                        rule.XlinkToStream = (string)e.Attribute("xlinkToStream") ?? String.Empty;
                        lock (_locker) { Add(rule); }
                    }

                    ret = true; // operation succeeded
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcRules.initAsync(AcStream){Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcRules.initAsync(AcStream){Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Populate this container with AcPermission objects.
        /// </summary>
        /// <param name="name">Optional depot or stream name as per
        /// [constructor parameter](@ref AcUtils#AcPermissions#AcPermissions) \e kind, otherwise all.</param>
        /// <returns>\e true if no failure occurred and list was initialized successfully, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c lsacl command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa [AcPermissions constructor](@ref AcUtils#AcPermissions#AcPermissions) */
        /*! \lsacl_ <tt>lsacl -fx {stream|depot} \<name\></tt> */
        public async Task <bool> initAsync(string name = null)
        {
            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync($@"lsacl -fx {_kind} ""{name}""").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    foreach (XElement e in xml.Elements("Element"))
                    {
                        AcPermission perm = new AcPermission(_kind);
                        perm.Name      = (string)e.Attribute("Name");
                        perm.AppliesTo = (string)e.Attribute("Group");
                        string type = (string)e.Attribute("Type");
                        perm.Type = (PermType)Enum.Parse(typeof(PermType), type);
                        string rights = (string)e.Attribute("Rights");
                        perm.Rights      = (PermRights)Enum.Parse(typeof(PermRights), rights);
                        perm.Inheritable = (bool)e.Attribute("Inheritable");
                        lock (_locker) { Add(perm); }
                    }

                    ret = true; // operation succeeded
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcPermissions.initAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcPermissions.initAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
        //@}
        #endregion

        /// <summary>
        /// Optionally called during [list construction](@ref AcUtils#AcGroups#AcGroups) to initialize the
        /// [list of principals](@ref AcPrincipal#Members) (users and groups) that are direct (explicit) members of \e group.
        /// This method is called internally and not by user code.
        /// </summary>
        /// <remarks>Membership lists for inactive groups are empty (not initialized). An inactive group's membership list will
        /// reappear when the group is reactivated.</remarks>
        /// <param name="group">Name of AccuRev group.</param>
        /// <returns>\e true if no exception was thrown and operation succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa [AcUser.initGroupsListAsync](@ref AcUtils#AcUser#initGroupsListAsync) */
        /*! \show_ <tt>show -fx -g \<group\> members</tt> */

        /*! \accunote_ Unlike the \c show command used here, its <tt>show -fx -u \<user\> groups</tt> counterpart
         *   does include memberships resulting from indirect (implicit) membership. */
        private async Task <bool> initMembersListAsync(string group)
        {
            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync($@"show -fx -g ""{group}"" members").ConfigureAwait(false);

                if (r != null && r.RetVal == 0) // if command succeeded
                {
                    SortedSet <string> members = new SortedSet <string>();
                    XElement           xml     = XElement.Parse(r.CmdResult);
                    foreach (XElement e in xml.Elements("Element"))
                    {
                        string name = (string)e.Attribute("User");
                        members.Add(name);
                    }

                    lock (_locker)
                    {
                        AcPrincipal prncpl = getPrincipal(group);
                        prncpl.Members = members;
                    }

                    ret = true; // operation succeeded
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcGroups.initMembersListAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcGroups.initMembersListAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Populate this container with AcLock objects on streams in \e depot or all AcLock objects in the repository.
        /// </summary>
        /// <param name="depot">Limit the list of locks to those on \e depot only, otherwise
        /// \e null for all locks in the repository.</param>
        /// <returns>\e true if initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c show command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        /*! \sa [AcLocks constructor](@ref AcUtils#AcLocks#AcLocks), initAsync(DepotsCollection), initAsync(StreamsCollection) */
        /*! \show_ <tt>show -fx locks</tt> */
        public async Task <bool> initAsync(AcDepot depot = null)
        {
            bool ret = false; // assume failure

            try
            {
                AcResult r = await AcCommand.runAsync("show -fx locks").ConfigureAwait(false);

                if (r != null && r.RetVal == 0)
                {
                    XElement xml = XElement.Parse(r.CmdResult);
                    IEnumerable <XElement> query = null;
                    if (depot == null)
                    {
                        query = from e in xml.Elements("Element")
                                select e;
                    }
                    else
                    {
                        query = from e in xml.Elements("Element")
                                join AcStream s in depot.Streams on(string) e.Attribute("Name") equals s.Name
                                select e;
                    }
                    ret = initList(query);
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcLocks.initAsync(AcDepot){Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcLocks.initAsync(AcDepot){Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
        /// <summary>
        /// For the real version specified in the argument list, get the real stream/version
        /// for the version in the specified version's workspace backing stream.
        /// </summary>
        /// <remarks>\c diff used here with the \c -i option, not to run a diff but to get the EID's only.</remarks>
        /// <param name="realverspec">Real version specification in text format,
        /// for example <tt>PG_MAINT1_barnyrd\4</tt> (numeric format won't work).</param>
        /// <param name="depot">The depot.</param>
        /// <param name="depotrelpath">Depot relative path, for example <tt>\\\\\.\\Bin\\foo.java</tt></param>
        /// <returns>An array initialized as <em>int[]={realStreamNumber, realVersionNumber}</em> if available, otherwise \e null.</returns>

        /*! \diff_ The \c diff command returns <em>zero (0)</em> for no differences found,
         *  <em>one (1)</em> for differences found, or <em>two (2)</em> on \c diff program error.<br>
         *  <tt>diff -fx -v \<realverspec\> -b -i -p \<depot\> \<depotrelpath\></tt> */
        /*! > -v -b Compare the specified version (X) with the version in X's stream's backing stream. (Use -v -V instead if comparing elements of type text that are active in a time-based stream.) */
        /*! > -i Information only: Report the IDs of the two versions, but don't actually compare them. This option is valid only in a command that uses a -v/-V combination or a -v/-b combination. If an element appears only in the workspace stream, not in the workspace's backing stream, this option does not list it. */
        /// <exception cref="AcUtilsException">caught and [logged](@ref AcUtils#AcDebug#initAcLogging)
        /// in <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on \c diff command failure.</exception>
        /// <exception cref="Exception">caught and logged in same on failure to handle a range of exceptions.</exception>
        public static async Task <int[]> getBackedVersionAsync(string realverspec, AcDepot depot, string depotrelpath)
        {
            int[] arr = null; // {realStreamNumber, realVersionNumber}
            try
            {
                AcResult r = await AcCommand.runAsync($@"diff -fx -v ""{realverspec}"" -b -i -p ""{depot}"" ""{depotrelpath}""")
                             .ConfigureAwait(false);

                if (r != null && r.RetVal < 2)
                {
                    XElement xml     = XElement.Parse(r.CmdResult);
                    XElement stream2 = xml.Descendants().Where(n => n.Name == "Stream2").SingleOrDefault();
                    if (stream2 != null)
                    {
                        XAttribute version = stream2.Attributes("Version").SingleOrDefault();
                        if (version != null)
                        {
                            string   temp              = (string)version;
                            string[] a                 = temp.Split('/');
                            int      realStreamNumber  = Int32.Parse(a[0], NumberStyles.Integer);
                            int      realVersionNumber = Int32.Parse(a[1], NumberStyles.Integer);
                            arr = new int[] { realStreamNumber, realVersionNumber };
                        }
                    }
                }
            }

            catch (AcUtilsException ecx)
            {
                AcDebug.Log($"AcUtilsException caught and logged in AcQuery.getBackedVersionAsync{Environment.NewLine}{ecx.Message}");
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcQuery.getBackedVersionAsync{Environment.NewLine}{ecx.Message}");
            }

            return(arr);
        }
Ejemplo n.º 30
0
        //@}
        #endregion

        /// <summary>
        /// Helper function for initializing \e user with their Active Directory properties and group memberships
        /// as per [constructor parameters](@ref AcUtils#AcUsers#AcUsers). Called internally and not by user code.
        /// </summary>
        /// <param name="user">The user to initialize.</param>
        /// <returns>\e true if list initialization succeeded, \e false otherwise.</returns>
        /// <exception cref="Exception">caught and [logged](@ref AcUtils#AcDebug#initAcLogging) in
        /// <tt>\%LOCALAPPDATA\%\\AcTools\\Logs\\<prog_name\>-YYYY-MM-DD.log</tt> on failure to handle a range of exceptions.</exception>
        private async Task <bool> initUserPropsAsync(AcUser user)
        {
            bool ret = false; // assume failure

            try
            {
                if (_dc != null && _includeGroupsList)
                {
                    Task <bool>[] tasks = new Task <bool> [2];
                    // initialize default set and other user properties from Active Directory
                    tasks[0] = user.initFromADAsync(_dc, _pc);
                    // include group membership list initialization
                    tasks[1] = user.initGroupsListAsync();
                    bool[] arr = await Task.WhenAll(tasks).ConfigureAwait(false);

                    ret = (arr != null && arr.All(n => n == true));
                }
                else if (_dc != null && !_includeGroupsList)
                {
                    ret = await user.initFromADAsync(_dc, _pc).ConfigureAwait(false);
                }
                else if (_dc == null && _includeGroupsList)
                {
                    ret = await user.initGroupsListAsync().ConfigureAwait(false);
                }
                else // _dc == null && !_includeGroupsList
                {
                    ret = true; // nothing to do
                }
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in AcUsers.initUserPropsAsync{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }