Beispiel #1
0
        public async System.Threading.Tasks.Task <ActionResult> Import(HttpPostedFileBase file, string PlannerPlan, string clientId)
        {
            SignalRMessage signalR      = new SignalRMessage(clientId);
            GraphPlanner   graphPlanner = new GraphPlanner(clientId);

            try
            {
                // Get current planner object
                var planner = await graphPlanner.GetplannerPlanAsync(PlannerPlan);

                // Count imported tasks
                int importedTasksCounter = 0;

                // Get uploaded json
                BinaryReader b       = new BinaryReader(file.InputStream);
                byte[]       binData = b.ReadBytes(file.ContentLength);
                string       result  = Encoding.UTF8.GetString(binData);

                JsonReader reader = new JsonTextReader(new StringReader(result));
                // Do not parse datetime values
                reader.DateParseHandling    = DateParseHandling.None;
                reader.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
                JObject trelloBoard = JObject.Load(reader);

                // Get trello lists
                ArrayList bucketsToCreate = new ArrayList();

                foreach (JToken list in trelloBoard.SelectToken("lists"))
                {
                    string bucketName = (string)list["name"];
                    // check if list was archived
                    bool isOpen = !(bool)list["closed"];

                    if (!bucketsToCreate.Contains(bucketName) && isOpen)
                    {
                        bucketsToCreate.Add(bucketName);
                    }
                }

                // Get existing planner buckets
                IEnumerable <PlannerBucket> plannerBuckets = await graphPlanner.GetPlannerBucketsAsync(PlannerPlan);

                // Create planner bucket if not exists
                foreach (string bucket in bucketsToCreate)
                {
                    try
                    {
                        if (!plannerBuckets.ToList().Where(p => p.Name == bucket).Any())
                        {
                            PlannerBucket plannerBucket = new PlannerBucket
                            {
                                Name   = bucket,
                                PlanId = PlannerPlan
                            };

                            var reponse = await graphPlanner.AddPlannerBucketAsync(plannerBucket);
                        }
                    }
                    catch
                    {
                    }
                }

                // Get available planner buckets
                plannerBuckets = await graphPlanner.GetPlannerBucketsAsync(PlannerPlan);

                // create tasks
                foreach (JToken task in trelloBoard.SelectToken("cards"))
                {
                    try
                    {
                        // Get name of the trello list which will become a planner bucket
                        string trelloId = (string)task["idList"];
                        string name     = (string)trelloBoard.SelectToken($"$.lists[?(@.id == '{trelloId}')]")["name"];
                        // Check if task is in an archived list --> won't be imported
                        bool isInArchivedList = (bool)trelloBoard.SelectToken($"$.lists[?(@.id == '{trelloId}')]")["closed"];

                        PlannerTask plannerTask = new PlannerTask
                        {
                            PlanId = PlannerPlan,
                            Title  = (string)task["name"],
                        };

                        if (isInArchivedList)
                        {
                            signalR.sendMessage("Discarding task because stored in an archived list: '" + plannerTask.Title + "'");
                        }
                        else
                        {
                            try
                            {
                                // Get bucketId to store tasks
                                string bucketId = plannerBuckets.Where(p => p.Name.Equals(name)).First().Id;
                                plannerTask.BucketId = bucketId;
                            }
                            catch
                            {
                            }

                            // Get completed
                            bool isClosed = bool.Parse((string)task["closed"]);

                            if (isClosed)
                            {
                                plannerTask.PercentComplete = 100;
                            }

                            // Get due
                            string dueDateTime = (string)task["due"];

                            if (!string.IsNullOrEmpty(dueDateTime))
                            {
                                plannerTask.DueDateTime = DateTimeOffset.Parse(dueDateTime);
                            }

                            // Get assigned user
                            try
                            {
                                JToken[] assignedToId = task.SelectTokens("idMembers[*]").ToArray();

                                plannerTask.Assignments = new PlannerAssignments();

                                // workaround: https://github.com/nicolonsky/ModernWorkplaceConcierge/issues/75#issuecomment-821622465
                                plannerTask.Assignments.ODataType = null;

                                foreach (JToken currentUser in assignedToId)
                                {
                                    if (!string.IsNullOrEmpty((string)currentUser))
                                    {
                                        string assignedToname = (string)trelloBoard.SelectToken($"$.members[?(@.id == '{(string)currentUser}')]")["fullName"];

                                        User user = await GraphHelper.GetUser(assignedToname);

                                        plannerTask.Assignments.AddAssignee(user.Id);
                                    }
                                }
                            }
                            catch
                            {
                            }

                            // Add the task
                            var request = await graphPlanner.AddPlannerTaskAsync(plannerTask);

                            signalR.sendMessage("Successfully imported task '" + request.Title + "'");

                            importedTasksCounter++;

                            // Add task details like description and attachments

                            JToken[] attachments     = task.SelectTokens("attachments[*]").ToArray();
                            string   taskDescription = (string)task["desc"];

                            if (!string.IsNullOrEmpty(taskDescription) || attachments.Count() > 0)
                            {
                                PlannerTaskDetails plannerTaskDetails = new PlannerTaskDetails();

                                if (!string.IsNullOrEmpty(taskDescription))
                                {
                                    plannerTaskDetails.Description = taskDescription;
                                }

                                plannerTaskDetails.References = new PlannerExternalReferences();

                                foreach (JToken attachment in attachments)
                                {
                                    string attachmentUrl  = attachment.Value <string>("url");
                                    string attachmentName = attachment.Value <string>("name");

                                    if (!string.IsNullOrEmpty(attachmentUrl))
                                    {
                                        try
                                        {
                                            plannerTaskDetails.References.AddReference(attachmentUrl, attachmentName);
                                        }
                                        catch
                                        {
                                        }
                                    }
                                }

                                try
                                {
                                    plannerTaskDetails.Checklist = new PlannerChecklistItems();

                                    JToken[] checklists = task.SelectTokens("idChecklists[*]").ToArray();

                                    foreach (JToken checklist in checklists)
                                    {
                                        JToken[] checklistItems = trelloBoard.SelectTokens($"$.checklists[?(@.id == '{(string)checklist}')].checkItems[*].name").ToArray();

                                        int checklistCount = 0;

                                        foreach (JToken checklistItem in checklistItems)
                                        {
                                            string checklistItemName = (string)checklistItem;

                                            // truncate string because checklist items are limited to 100 characters
                                            if (checklistItemName.Length >= 100)
                                            {
                                                signalR.sendMessage("Truncating checklist item: '" + checklistItemName + "' on task: '" + plannerTask.Title + "'. The maximum length in Planner is 100 characters!");
                                                checklistItemName = checklistItemName.Substring(0, 100);
                                            }

                                            if (!(checklistCount >= 20))
                                            {
                                                plannerTaskDetails.Checklist.AddChecklistItem(checklistItemName);
                                            }
                                            else
                                            {
                                                signalR.sendMessage("Discarding checklist item: '" + checklistItemName + "' on task: '" + plannerTask.Title + "' because Planner limit's each card to 20 checklist items!");
                                            }

                                            checklistCount++;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    signalR.sendMessage("Error: " + e.Message);
                                }

                                var response = await graphPlanner.AddPlannerTaskDetailsAsync(plannerTaskDetails, request.Id);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        signalR.sendMessage("Error: " + e.Message);
                    }
                }

                signalR.sendMessage("Success imported: " + importedTasksCounter + " tasks to planner: " + planner.Title);
            }
            catch (Exception e)
            {
                signalR.sendMessage("Error: " + e.Message);
            }

            signalR.sendMessage("Done#!");
            return(new HttpStatusCodeResult(204));
        }
Beispiel #2
0
        /// <summary>
        /// Finds the strongly connected components of a square matrix.
        /// </summary>
        /// <returns>strongly connected components, null on error</returns>
        private static DulmageMendelsohn FindScc(SymbolicColumnStorage A, int n)
        {
            // matrix A temporarily modified, then restored

            int i, k, b, nb = 0, top;

            int[] xi, p, r, Ap, ATp;

            var AT = A.Transpose(); // AT = A'

            Ap  = A.ColumnPointers;
            ATp = AT.ColumnPointers;

            xi = new int[2 * n + 1];             // get workspace

            var D = new DulmageMendelsohn(n, 0); // allocate result

            p = D.p;
            r = D.r;

            top = n;
            for (i = 0; i < n; i++) // first dfs(A) to find finish times (xi)
            {
                if (!(Ap[i] < 0))
                {
                    top = GraphHelper.DepthFirstSearch(i, A.ColumnPointers, A.RowIndices, top, xi, xi, n, null);
                }
            }
            for (i = 0; i < n; i++)
            {
                //CS_MARK(Ap, i);
                Ap[i] = -(Ap[i]) - 2; // restore A; unmark all nodes
            }
            top = n;
            nb  = n;
            for (k = 0; k < n; k++) // dfs(A') to find strongly connnected comp
            {
                i = xi[k];          // get i in reverse order of finish times
                if (ATp[i] < 0)
                {
                    continue;  // skip node i if already ordered
                }
                r[nb--] = top; // node i is the start of a component in p
                top     = GraphHelper.DepthFirstSearch(i, AT.ColumnPointers, AT.RowIndices, top, p, xi, n, null);
            }
            r[nb] = 0; // first block starts at zero; shift r up
            for (k = nb; k <= n; k++)
            {
                r[k - nb] = r[k];
            }
            D.nb = nb = n - nb;      // nb = # of strongly connected components
            for (b = 0; b < nb; b++) // sort each block in natural order
            {
                for (k = r[b]; k < r[b + 1]; k++)
                {
                    xi[p[k]] = b;
                }
            }
            for (b = 0; b <= nb; b++)
            {
                xi[n + b] = r[b];
            }
            for (i = 0; i < n; i++)
            {
                p[xi[n + xi[i]]++] = i;
            }
            return(D);
        }
Beispiel #3
0
 public static async Task <HttpResponseMessage> DeleteAppAsync(HttpClient httpClient, string accessToken, string appId)
 {
     return(await GraphHelper.DeleteAsync(httpClient, $"v1.0/appCatalogs/teamsApps/{appId}", accessToken));
 }
Beispiel #4
0
        /// <summary>
        /// Generate minimum degree ordering of A+A' (if A is symmetric) or A'A.
        /// </summary>
        /// <param name="A">Column-compressed matrix</param>
        /// <param name="order">Column ordering method</param>
        /// <returns>amd(A+A') if A is symmetric, or amd(A'A) otherwise, null on
        /// error or for natural ordering</returns>
        /// <remarks>
        /// See Chapter 7.1 (Fill-reducing orderings: Minimum degree ordering) in
        /// "Direct Methods for Sparse Linear Systems" by Tim Davis.
        /// </remarks>
        public static int[] Generate <T>(CompressedColumnStorage <T> A, ColumnOrdering order)
            where T : struct, IEquatable <T>, IFormattable
        {
            int[] Cp, Ci, P, W, nv, next, head, elen, degree, w, hhead;

            int d, dk, dext, lemax = 0, e, elenk, eln, i, j, k, k1,
                k2, k3, jlast, ln, dense, nzmax, mindeg = 0, nvi, nvj, nvk, mark, wnvi,
                cnz, nel = 0, p, p1, p2, p3, p4, pj, pk, pk1, pk2, pn, q, n;
            bool ok;
            int  h;

            n = A.ColumnCount;

            if (order == ColumnOrdering.Natural)
            {
                // TODO: return null here?
                return(Permutation.Create(n));
            }

            var C = ConstructMatrix(SymbolicColumnStorage.Create(A), order);

            Cp  = C.ColumnPointers;
            cnz = Cp[n];

            // Find dense threshold
            dense = Math.Max(16, 10 * (int)Math.Sqrt(n));
            dense = Math.Min(n - 2, dense);

            // add elbow room to C
            if (!C.Resize(cnz + cnz / 5 + 2 * n))
            {
                return(null);
            }

            P      = new int[n + 1]; // allocate result
            W      = new int[n + 1]; // get workspace
            w      = new int[n + 1];
            degree = new int[n + 1];

            elen = new int[n + 1]; // Initialized to 0's

            // Initialize quotient graph
            for (k = 0; k < n; k++)
            {
                W[k] = Cp[k + 1] - Cp[k];
            }
            W[n]  = 0;
            nzmax = C.RowIndices.Length;
            Ci    = C.RowIndices;

            for (i = 0; i <= n; i++)
            {
                P[i]      = -1;
                w[i]      = 1;    // node i is alive
                degree[i] = W[i]; // degree of node i
            }

            next  = new int[n + 1];
            hhead = new int[n + 1];
            head  = new int[n + 1];
            nv    = new int[n + 1];

            Array.Copy(P, next, n + 1);
            Array.Copy(P, head, n + 1);  // degree list i is empty
            Array.Copy(P, hhead, n + 1); // hash list i is empty
            Array.Copy(w, nv, n + 1);    // node i is just one node

            mark    = Clear(0, 0, w, n); // clear w
            elen[n] = -2;                // n is a dead element
            Cp[n]   = -1;                // n is a root of assembly tree
            w[n]    = 0;                 // n is a dead element

            // Initialize degree lists
            for (i = 0; i < n; i++)
            {
                d = degree[i];
                if (d == 0)       // node i is empty
                {
                    elen[i] = -2; // element i is dead
                    nel++;
                    Cp[i] = -1;   // i is a root of assembly tree
                    w[i]  = 0;
                }
                else if (d > dense)   // node i is dense
                {
                    nv[i]   = 0;      // absorb i into element n
                    elen[i] = -1;     // node i is dead
                    nel++;
                    Cp[i] = -(n + 2); // FLIP(n)
                    nv[n]++;
                }
                else
                {
                    if (head[d] != -1)
                    {
                        P[head[d]] = i;
                    }
                    next[i] = head[d]; // put node i in degree list d
                    head[d] = i;
                }
            }
            while (nel < n) // while (selecting pivots) do
            {
                // Select node of minimum approximate degree
                for (k = -1; mindeg < n && (k = head[mindeg]) == -1; mindeg++)
                {
                    ;
                }
                if (next[k] != -1)
                {
                    P[next[k]] = -1;
                }
                head[mindeg] = next[k]; // remove k from degree list
                elenk        = elen[k]; // elenk = |Ek|
                nvk          = nv[k];   // # of nodes k represents
                nel         += nvk;     // nv[k] nodes of A eliminated

                // Garbage collection
                if (elenk > 0 && cnz + mindeg >= nzmax)
                {
                    for (j = 0; j < n; j++)
                    {
                        if ((p = Cp[j]) >= 0) // j is a live node or element
                        {
                            Cp[j] = Ci[p];    // save first entry of object
                            Ci[p] = -(j + 2); // first entry is now CS_FLIP(j)
                        }
                    }
                    for (q = 0, p = 0; p < cnz;)      // scan all of memory
                    {
                        if ((j = FLIP(Ci[p++])) >= 0) // found object j
                        {
                            Ci[q] = Cp[j];            // restore first entry of object
                            Cp[j] = q++;              // new pointer to object j
                            for (k3 = 0; k3 < W[j] - 1; k3++)
                            {
                                Ci[q++] = Ci[p++];
                            }
                        }
                    }
                    cnz = q; // Ci [cnz...nzmax-1] now free
                }

                // Construct new element
                dk    = 0;
                nv[k] = -nvk;                   // flag k as in Lk
                p     = Cp[k];
                pk1   = (elenk == 0) ? p : cnz; // do in place if elen[k] == 0
                pk2   = pk1;
                for (k1 = 1; k1 <= elenk + 1; k1++)
                {
                    if (k1 > elenk)
                    {
                        e  = k;            // search the nodes in k
                        pj = p;            // list of nodes starts at Ci[pj]*/
                        ln = W[k] - elenk; // length of list of nodes in k
                    }
                    else
                    {
                        e  = Ci[p++]; // search the nodes in e
                        pj = Cp[e];
                        ln = W[e];    // length of list of nodes in e
                    }
                    for (k2 = 1; k2 <= ln; k2++)
                    {
                        i = Ci[pj++];
                        if ((nvi = nv[i]) <= 0)
                        {
                            continue;     // node i dead, or seen
                        }
                        dk       += nvi;  // degree[Lk] += size of node i
                        nv[i]     = -nvi; // negate nv[i] to denote i in Lk
                        Ci[pk2++] = i;    // place i in Lk
                        if (next[i] != -1)
                        {
                            P[next[i]] = P[i];
                        }
                        if (P[i] != -1) // remove i from degree list
                        {
                            next[P[i]] = next[i];
                        }
                        else
                        {
                            head[degree[i]] = next[i];
                        }
                    }
                    if (e != k)
                    {
                        Cp[e] = -(k + 2); // absorb e into k // FLIP(k)
                        w[e]  = 0;        // e is now a dead element
                    }
                }
                if (elenk != 0)
                {
                    cnz = pk2;   // Ci [cnz...nzmax] is free
                }
                degree[k] = dk;  // external degree of k - |Lk\i|
                Cp[k]     = pk1; // element k is in Ci[pk1..pk2-1]
                W[k]      = pk2 - pk1;
                elen[k]   = -2;  // k is now an element

                // Find set differences
                mark = Clear(mark, lemax, w, n); // clear w if necessary
                for (pk = pk1; pk < pk2; pk++)   // scan 1: find |Le\Lk|
                {
                    i = Ci[pk];
                    if ((eln = elen[i]) <= 0)
                    {
                        continue;                              // skip if elen[i] empty
                    }
                    nvi  = -nv[i];                             // nv [i] was negated
                    wnvi = mark - nvi;
                    for (p = Cp[i]; p <= Cp[i] + eln - 1; p++) // scan Ei
                    {
                        e = Ci[p];
                        if (w[e] >= mark)
                        {
                            w[e] -= nvi;             // decrement |Le\Lk|
                        }
                        else if (w[e] != 0)          // ensure e is a live element
                        {
                            w[e] = degree[e] + wnvi; // 1st time e seen in scan 1
                        }
                    }
                }

                // Degree update
                for (pk = pk1; pk < pk2; pk++) // scan2: degree update
                {
                    i  = Ci[pk];               // consider node i in Lk
                    p1 = Cp[i];
                    p2 = p1 + elen[i] - 1;
                    pn = p1;
                    for (h = 0, d = 0, p = p1; p <= p2; p++) // scan Ei
                    {
                        e = Ci[p];
                        if (w[e] != 0)          // e is an unabsorbed element
                        {
                            dext = w[e] - mark; // dext = |Le\Lk|
                            if (dext > 0)
                            {
                                d       += dext; // sum up the set differences
                                Ci[pn++] = e;    // keep e in Ei
                                h       += e;    // compute the hash of node i
                            }
                            else
                            {
                                Cp[e] = -(k + 2); // aggressive absorb. e.k // FLIP(k)
                                w[e]  = 0;        // e is a dead element
                            }
                        }
                    }
                    elen[i] = pn - p1 + 1; // elen[i] = |Ei|
                    p3      = pn;
                    p4      = p1 + W[i];
                    for (p = p2 + 1; p < p4; p++) // prune edges in Ai
                    {
                        j = Ci[p];
                        if ((nvj = nv[j]) <= 0)
                        {
                            continue;       // node j dead or in Lk
                        }
                        d       += nvj;     // degree(i) += |j|
                        Ci[pn++] = j;       // place j in node list of i
                        h       += j;       // compute hash for node i
                    }
                    if (d == 0)             // check for mass elimination
                    {
                        Cp[i]   = -(k + 2); // absorb i into k // FLIP(k)
                        nvi     = -nv[i];
                        dk     -= nvi;      // |Lk| -= |i|
                        nvk    += nvi;      // |k| += nv[i]
                        nel    += nvi;
                        nv[i]   = 0;
                        elen[i] = -1; // node i is dead
                    }
                    else
                    {
                        degree[i] = Math.Min(degree[i], d);   // update degree(i)
                        Ci[pn]    = Ci[p3];                   // move first node to end
                        Ci[p3]    = Ci[p1];                   // move 1st el. to end of Ei
                        Ci[p1]    = k;                        // add k as 1st element in of Ei
                        W[i]      = pn - p1 + 1;              // new len of adj. list of node i
                        h         = ((h < 0) ? (-h) : h) % n; // finalize hash of i
                        next[i]   = hhead[h];                 // place i in hash bucket
                        hhead[h]  = i;
                        P[i]      = h;                        // save hash of i in last[i]
                    }
                } // scan2 is done
                degree[k] = dk;                               // finalize |Lk|
                lemax     = Math.Max(lemax, dk);
                mark      = Clear(mark + lemax, lemax, w, n); // clear w

                // Supernode detection
                for (pk = pk1; pk < pk2; pk++)
                {
                    i = Ci[pk];
                    if (nv[i] >= 0)
                    {
                        continue;    // skip if i is dead
                    }
                    h        = P[i]; // scan hash bucket of node i
                    i        = hhead[h];
                    hhead[h] = -1;   // hash bucket will be empty
                    for (; i != -1 && next[i] != -1; i = next[i], mark++)
                    {
                        ln  = W[i];
                        eln = elen[i];
                        for (p = Cp[i] + 1; p <= Cp[i] + ln - 1; p++)
                        {
                            w[Ci[p]] = mark;
                        }
                        jlast = i;
                        for (j = next[i]; j != -1;)  // compare i with all j
                        {
                            ok = (W[j] == ln) && (elen[j] == eln);
                            for (p = Cp[j] + 1; ok && p <= Cp[j] + ln - 1; p++)
                            {
                                if (w[Ci[p]] != mark)
                                {
                                    ok = false;                   // compare i and j
                                }
                            }
                            if (ok)                     // i and j are identical
                            {
                                Cp[j]       = -(i + 2); // absorb j into i // FLIP(i)
                                nv[i]      += nv[j];
                                nv[j]       = 0;
                                elen[j]     = -1;      // node j is dead
                                j           = next[j]; // delete j from hash bucket
                                next[jlast] = j;
                            }
                            else
                            {
                                jlast = j; // j and i are different
                                j     = next[j];
                            }
                        }
                    }
                }

                // Finalize new element
                for (p = pk1, pk = pk1; pk < pk2; pk++) // finalize Lk
                {
                    i = Ci[pk];
                    if ((nvi = -nv[i]) <= 0)
                    {
                        continue;                 // skip if i is dead
                    }
                    nv[i] = nvi;                  // restore nv[i]
                    d     = degree[i] + dk - nvi; // compute external degree(i)
                    d     = Math.Min(d, n - nel - nvi);
                    if (head[d] != -1)
                    {
                        P[head[d]] = i;
                    }
                    next[i]   = head[d]; // put i back in degree list
                    P[i]      = -1;
                    head[d]   = i;
                    mindeg    = Math.Min(mindeg, d); // find new minimum degree
                    degree[i] = d;
                    Ci[p++]   = i;                   // place i in Lk
                }
                nv[k] = nvk;                         // # nodes absorbed into k
                if ((W[k] = p - pk1) == 0)           // length of adj list of element k
                {
                    Cp[k] = -1;                      // k is a root of the tree
                    w[k]  = 0;                       // k is now a dead element
                }
                if (elenk != 0)
                {
                    cnz = p;             // free unused space in Lk
                }
            }

            // Postordering
            for (i = 0; i < n; i++)
            {
                Cp[i] = -(Cp[i] + 2);                     // fix assembly tree // FLIP(Cp[i])
            }
            for (j = 0; j <= n; j++)
            {
                head[j] = -1;
            }
            for (j = n; j >= 0; j--) // place unordered nodes in lists
            {
                if (nv[j] > 0)
                {
                    continue;              // skip if j is an element
                }
                next[j]     = head[Cp[j]]; // place j in list of its parent
                head[Cp[j]] = j;
            }
            for (e = n; e >= 0; e--) // place elements in lists
            {
                if (nv[e] <= 0)
                {
                    continue;             // skip unless e is an element
                }
                if (Cp[e] != -1)
                {
                    next[e]     = head[Cp[e]]; // place e in list of its parent
                    head[Cp[e]] = e;
                }
            }
            for (k = 0, i = 0; i <= n; i++) // postorder the assembly tree
            {
                if (Cp[i] == -1)
                {
                    k = GraphHelper.TreeDepthFirstSearch(i, k, head, next, P, w);
                }
            }
            return(P);
        }
Beispiel #5
0
 public static async Task <TeamTab> GetTabAsync(string accessToken, HttpClient httpClient, string groupId, string channelId, string tabId)
 {
     return(await GraphHelper.GetAsync <TeamTab>(httpClient, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tabId}", accessToken));
 }
Beispiel #6
0
 public static async Task UpdateTabAsync(HttpClient httpClient, string accessToken, string groupId, string channelId, TeamTab tab)
 {
     tab.Configuration = null;
     await GraphHelper.PatchAsync(httpClient, accessToken, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tab.Id}", tab);
 }
Beispiel #7
0
        /// <summary>
        /// Checks if a Group exists by ID
        /// </summary>
        /// <param name="scope">The PnP Provisioning Scope</param>
        /// <param name="groupId">The ID of the Group</param>
        /// <param name="accessToken">The OAuth 2.0 Access Token</param>
        /// <returns>Whether the Group exists or not</returns>
        private static Boolean GroupExistsById(PnPMonitoredScope scope, string groupId, string accessToken)
        {
            var alreadyExistingGroupId = GraphHelper.ItemAlreadyExists($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/groups", "id", groupId, accessToken);

            return(alreadyExistingGroupId != null);
        }
Beispiel #8
0
 public static async Task PostMessageAsync(HttpClient httpClient, string accessToken, string groupId, string channelId, TeamChannelMessage message)
 {
     await GraphHelper.PostAsync(httpClient, $"v1.0/teams/{groupId}/channels/{channelId}/messages", message, accessToken);
 }
Beispiel #9
0
        static void Main(string[] args)
        {
            Console.WriteLine(".NET Core Graph Tutorial\n");

            var appConfig = LoadAppSettings();

            if (appConfig == null)
            {
                Console.WriteLine("Missing or invalid appsettings.json...exiting");
                return;
            }

            var appId        = appConfig["appId"];
            var scopesString = appConfig["scopes"];
            var scopes       = scopesString.Split(';');

            // Initialize the auth provider with values from appsettings.json
            var authProvider = new DeviceCodeAuthProvider(appId, scopes);

            // Request a token to sign in the user
            var accessToken = authProvider.GetAccessToken().Result;

            // Initialize Graph client
            GraphHelper.Initialize(authProvider);

            // Get signed in user
            var user = GraphHelper.GetMeAsync().Result;

            Console.WriteLine($"Welcome {user.DisplayName}!\n");

            int choice = -1;

            while (choice != 0)
            {
                Console.WriteLine("Please choose one of the following options:");
                Console.WriteLine("0. Exit");
                Console.WriteLine("1. Display access token");
                Console.WriteLine("2. View this week's calendar");
                Console.WriteLine("3. Add an event");

                try
                {
                    choice = int.Parse(Console.ReadLine());
                }
                catch (System.FormatException)
                {
                    // Set to invalid value
                    choice = -1;
                }

                switch (choice)
                {
                case 0:
                    // Exit the program
                    Console.WriteLine("Goodbye...");
                    break;

                case 1:
                    // Display access token
                    Console.WriteLine($"Access token: {accessToken}\n");
                    break;

                case 2:
                    // List the calendar
                    ListCalendarEvents(
                        user.MailboxSettings.TimeZone,
                        $"{user.MailboxSettings.DateFormat} {user.MailboxSettings.TimeFormat}"
                        );
                    break;

                case 3:
                    // Create a new event
                    CreateEvent(user.MailboxSettings.TimeZone);
                    break;

                default:
                    Console.WriteLine("Invalid choice! Please try again.");
                    break;
                }
            }
        }
Beispiel #10
0
        static void CreateEvent(string userTimeZone)
        {
            // Prompt user for info

            // Require a subject
            var subject = GetUserInput("subject", true,
                                       (input) => {
                return(GetUserYesNo($"Subject: {input} - is that right?"));
            });

            // Attendees are optional
            var attendeeList = new List <string>();

            if (GetUserYesNo("Do you want to invite attendees?"))
            {
                string attendee = null;

                do
                {
                    attendee = GetUserInput("attendee", false,
                                            (input) => {
                        return(GetUserYesNo($"{input} - add attendee?"));
                    });

                    if (!string.IsNullOrEmpty(attendee))
                    {
                        attendeeList.Add(attendee);
                    }
                }while (!string.IsNullOrEmpty(attendee));
            }

            var startString = GetUserInput("event start", true,
                                           (input) => {
                // Validate that input is a date
                return(DateTime.TryParse(input, out var result));
            });

            var start = DateTime.Parse(startString);

            var endString = GetUserInput("event end", true,
                                         (input) => {
                // Validate that input is a date
                // and is later than start
                return(DateTime.TryParse(input, out var result) &&
                       result.CompareTo(start) > 0);
            });

            var end = DateTime.Parse(endString);

            var body = GetUserInput("body", false,
                                    (input => { return(true); }));

            Console.WriteLine($"Subject: {subject}");
            Console.WriteLine($"Attendees: {string.Join(";", attendeeList)}");
            Console.WriteLine($"Start: {start.ToString()}");
            Console.WriteLine($"End: {end.ToString()}");
            Console.WriteLine($"Body: {body}");
            if (GetUserYesNo("Create event?"))
            {
                GraphHelper.CreateEvent(
                    userTimeZone,
                    subject,
                    start,
                    end,
                    attendeeList,
                    body).Wait();
            }
            else
            {
                Console.WriteLine("Canceled.");
            }
        }
        public async Task<List<Models.User>> GetAssignedUsers()
        {
            try
            {
                // Create the Graph Client
                string tenantId = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value;
                ActiveDirectoryClient graphClient = new ActiveDirectoryClient(new Uri(Globals.GraphApiUrl, tenantId), async () => await GraphHelper.AcquireTokenAsApp());

                // Read users from db for evaluating in memory
                List<Models.User> userHistory = UsersDbHelper.GetUsersForTenant(tenantId);
                List<Models.User> usersWithStatus = new List<Models.User>(userHistory);
                List<Models.User> updatedUserHistory = new List<Models.User>(userHistory);

                // Get the assignments for the application
                ServicePrincipal sp = (ServicePrincipal)graphClient.ServicePrincipals.Where(servicePrincpial => servicePrincpial.AppId.Equals(ConfigHelper.ClientId)).ExecuteAsync().Result.CurrentPage.FirstOrDefault();
                IServicePrincipalFetcher spFetcher = sp;
                List<IAppRoleAssignment> assignments = spFetcher.AppRoleAssignedTo.ExecuteAsync().Result.CurrentPage.ToList(); // TODO: Paging

                // TODO: Better Error Handling
                // TODO: Retry Logic
                // TODO: Nested Groups
                // TODO: Paged Results on Assignments
                // TODO: Paged Results on Group Membership
                // TODO: Performance & Batch Queries

                // Get the groups assigned to the app first
                foreach (IAppRoleAssignment assignment in assignments)
                {
                    if (assignment.PrincipalType == "Group")
                    {
                        // Get the group members
                        IGroupFetcher gFetcher = graphClient.Groups.GetByObjectId(assignment.PrincipalId.ToString());
                        List<IDirectoryObject> members = gFetcher.Members.ExecuteAsync().Result.CurrentPage.ToList();

                        foreach (IDirectoryObject member in members)
                        {
                            if (member is User)
                            {   
                                User user = (User)member;
                                int existingUserIndex = userHistory.FindIndex(u => u.ObjectId == user.ObjectId);

                                // If the user did not exist in the db before
                                if (existingUserIndex == -1)
                                {
                                    // The user is new
                                    usersWithStatus.Add(new Models.User(user) { assignmentStatus = "New" });
                                    updatedUserHistory.Add(new Models.User(user));
                                }
                                else
                                {
                                    // The user is active, but not new
                                    usersWithStatus[usersWithStatus.FindIndex(u => u.ObjectId == user.ObjectId)] = new Models.User(user) { assignmentStatus = "Enabled" };
                                    updatedUserHistory[existingUserIndex] = new Models.User(user);
                                }
                            }
                        }
                    }
                }

                // Get the users assigned to the app second
                foreach (IAppRoleAssignment assignment in assignments)
                {
                    if (assignment.PrincipalType == "User")
                    {
                        int existingUserIndex = userHistory.FindIndex(u => u.ObjectId == assignment.PrincipalId.ToString());
                        int assignedUserIndex = usersWithStatus.FindIndex(u => u.ObjectId == assignment.PrincipalId.ToString());

                        // If we haven't seen the user before, add it
                        if (existingUserIndex == -1 &&  assignedUserIndex == -1)
                        {
                            User user = (User)await graphClient.Users.GetByObjectId(assignment.PrincipalId.ToString()).ExecuteAsync();
                            usersWithStatus.Add(new Models.User(user) { assignmentStatus = "New" });
                            updatedUserHistory.Add(new Models.User(user));
                        }

                        // If we have seen the user before but didn't already update his data as part of group assignment, update the user data.
                        else if (existingUserIndex >= 0 && string.IsNullOrEmpty(usersWithStatus[assignedUserIndex].assignmentStatus))
                        {
                            User user = (User)await graphClient.Users.GetByObjectId(assignment.PrincipalId.ToString()).ExecuteAsync();
                            usersWithStatus[usersWithStatus.FindIndex(u => u.ObjectId == user.ObjectId)] = new Models.User(user) { assignmentStatus = "Enabled" };
                            updatedUserHistory[existingUserIndex] = new Models.User(user);
                        }
                    }
                }

                UsersDbHelper.SaveUsersForTenant(tenantId, updatedUserHistory);
                return usersWithStatus;
            }
            catch (AdalException ex)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }
        }
        public async Task <ActionResult> Delta(string id)
        {
            await GraphHelper.Updateitem(id);

            return(RedirectToAction("Index", "Activities"));
        }
        public async Task <ActionResult> Create(Activities b)
        {
            await GraphHelper.CreateActivities(b);

            return(RedirectToAction("Index"));
        }
Beispiel #14
0
        private PXFieldState CreateFieldStateForFieldValue(object returnState, string entityType, string cacheName, string fieldName)
        {
            Type type = GraphHelper.GetType(entityType);

            if (type != null)
            {
                Type cachetype = GraphHelper.GetType(cacheName);
                if (cachetype == null)
                {
                    return(null);
                }

                PXCache cache = this.Caches[cachetype];
                PXDBAttributeAttribute.Activate(cache);
                PXFieldState state = cache.GetStateExt(null, fieldName) as PXFieldState;
                if (state != null)
                {
                    state.DescriptionName = null;
                }

                var attr = cache.GetAttributes(null, fieldName);

                if (attr != null)
                {
                    var timeListAttribute = attr.FirstOrDefault(a => a is PXTimeListAttribute) as PXTimeListAttribute;
                    var intAttribute      = attr.FirstOrDefault(a => a is PXIntAttribute) as PXIntAttribute;

                    if (timeListAttribute != null && intAttribute != null)
                    {
                        state = PXTimeState.CreateInstance((PXIntState)state, null, null);
                        state.SelectorMode = PXSelectorMode.Undefined;
                    }
                }

                if (state != null)
                {
                    if (returnState == null)
                    {
                        object item = cache.CreateInstance();
                        object newValue;
                        cache.RaiseFieldDefaulting(fieldName, item, out newValue);
                        if (newValue != null)
                        {
                            cache.RaiseFieldSelecting(fieldName, item, ref newValue, false);
                        }
                        state.Value = newValue;
                    }
                    else
                    {
                        state.Value = returnState;
                    }
                    state.Enabled = true;

                    PXView view;
                    if (state.ViewName != null &&
                        this.Views.TryGetValue(state.ViewName, out view) &&
                        view.BqlSelect.GetTables()[0] == typeof(EPEmployee))
                    {
                        state.ViewName = "Employee";
                    }
                }

                if (attr != null)
                {
                    var intListAttribute = attr.FirstOrDefault(a => a.GetType().IsSubclassOf(typeof(PXIntListAttribute))) as PXIntListAttribute;
                    if (intListAttribute != null)
                    {
                        return(state);
                    }
                }

                state = PXFieldState.CreateInstance((state as PXStringState)?.AllowedValues != null ? state : state.Value, state.DataType, state.PrimaryKey, state.Nullable, state.Required == true ? 1 : state.Required == null ? 0 : -1, state.Precision, state.Length, state.DefaultValue, fieldName,
                                                    state.DescriptionName, state.DisplayName, state.Error, state.ErrorLevel, true, true, false, PXUIVisibility.Visible, state.ViewName, state.FieldList, state.HeaderList);

                return(state);
            }
            return(null);
        }
Beispiel #15
0
        /// <summary>
        /// Synchronizes Owners and Members with Team settings
        /// </summary>
        /// <param name="scope">The PnP Provisioning Scope</param>
        /// <param name="team">The Team settings, including security settings</param>
        /// <param name="teamId">The ID of the target Team</param>
        /// <param name="accessToken">The OAuth 2.0 Access Token</param>
        /// <returns>Whether the Security settings have been provisioned or not</returns>
        private static bool SetGroupSecurity(PnPMonitoredScope scope, Team team, string teamId, string accessToken)
        {
            String[] desideredOwnerIds;
            String[] desideredMemberIds;
            String[] finalOwnerIds;
            try
            {
                var userIdsByUPN = team.Security.Owners
                                   .Select(o => o.UserPrincipalName)
                                   .Concat(team.Security.Members.Select(m => m.UserPrincipalName))
                                   .Distinct(StringComparer.OrdinalIgnoreCase)
                                   .ToDictionary(k => k, k =>
                {
                    var jsonUser = HttpHelper.MakeGetRequestForString($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/users/{k}?$select=id", accessToken);
                    return(JToken.Parse(jsonUser).Value <string>("id"));
                });

                desideredOwnerIds  = team.Security.Owners.Select(o => userIdsByUPN[o.UserPrincipalName]).ToArray();
                desideredMemberIds = team.Security.Members.Select(o => userIdsByUPN[o.UserPrincipalName]).Union(desideredOwnerIds).ToArray();
            }
            catch (Exception ex)
            {
                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Teams_Team_FetchingUserError, ex.Message);
                return(false);
            }

            String[] ownerIdsToAdd;
            String[] ownerIdsToRemove;
            try
            {
                // Get current group owners
                var jsonOwners = HttpHelper.MakeGetRequestForString($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/groups/{teamId}/owners?$select=id", accessToken);

                string[] currentOwnerIds = GraphHelper.GetIdsFromList(jsonOwners);

                // Exclude owners already into the group
                ownerIdsToAdd = desideredOwnerIds.Except(currentOwnerIds).ToArray();

                if (team.Security.ClearExistingOwners)
                {
                    ownerIdsToRemove = currentOwnerIds.Except(desideredOwnerIds).ToArray();
                }
                else
                {
                    ownerIdsToRemove = new string[0];
                }

                // Define the complete set of owners
                finalOwnerIds = currentOwnerIds.Union(ownerIdsToAdd).Except(ownerIdsToRemove).ToArray();
            }
            catch (Exception ex)
            {
                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Teams_Team_ListingOwnersError, ex.Message);
                return(false);
            }

            // Add new owners
            foreach (string ownerId in ownerIdsToAdd)
            {
                try
                {
                    object content = new JObject
                    {
                        ["@odata.id"] = $"{GraphHelper.MicrosoftGraphBaseURI}v1.0/users/{ownerId}"
                    };
                    HttpHelper.MakePostRequest($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/groups/{teamId}/owners/$ref", content, "application/json", accessToken);
                }
                catch (Exception ex)
                {
                    scope.LogError(CoreResources.Provisioning_ObjectHandlers_Teams_Team_AddingOwnerError, ex.Message);
                    return(false);
                }
            }

            // Remove exceeding owners
            foreach (string ownerId in ownerIdsToRemove)
            {
                try
                {
                    HttpHelper.MakeDeleteRequest($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/groups/{teamId}/owners/{ownerId}/$ref", accessToken);
                }
                catch (Exception ex)
                {
                    scope.LogError(CoreResources.Provisioning_ObjectHandlers_Teams_Team_RemovingOwnerError, ex.Message);
                    return(false);
                }
            }

            String[] memberIdsToAdd;
            String[] memberIdsToRemove;
            try
            {
                // Get current group members
                var jsonMembers = HttpHelper.MakeGetRequestForString($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/groups/{teamId}/members?$select=id", accessToken);

                string[] currentMemberIds = GraphHelper.GetIdsFromList(jsonMembers);

                // Exclude members already into the group
                memberIdsToAdd = desideredMemberIds.Except(currentMemberIds).ToArray();

                if (team.Security.ClearExistingMembers)
                {
                    memberIdsToRemove = currentMemberIds.Except(desideredMemberIds.Union(finalOwnerIds)).ToArray();
                }
                else
                {
                    memberIdsToRemove = new string[0];
                }
            }
            catch (Exception ex)
            {
                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Teams_Team_ListingMembersError, ex.Message);
                return(false);
            }

            // Add new members
            foreach (string memberId in memberIdsToAdd)
            {
                try
                {
                    object content = new JObject
                    {
                        ["@odata.id"] = $"{GraphHelper.MicrosoftGraphBaseURI}v1.0/users/{memberId}"
                    };
                    HttpHelper.MakePostRequest($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/groups/{teamId}/members/$ref", content, "application/json", accessToken);
                }
                catch (Exception ex)
                {
                    scope.LogError(CoreResources.Provisioning_ObjectHandlers_Teams_Team_AddingMemberError, ex.Message);
                    return(false);
                }
            }

            // Remove exceeding members
            foreach (string memberId in memberIdsToRemove)
            {
                try
                {
                    HttpHelper.MakeDeleteRequest($"{GraphHelper.MicrosoftGraphBaseURI}v1.0/groups/{teamId}/members/{memberId}/$ref", accessToken);
                }
                catch (Exception ex)
                {
                    scope.LogError(CoreResources.Provisioning_ObjectHandlers_Teams_Team_RemovingMemberError, ex.Message);
                    return(false);
                }
            }

            return(true);
        }
Beispiel #16
0
 public static async Task <Group> GetGroupWithTeamAsync(HttpClient httpClient, string accessToken, string mailNickname)
 {
     return(await GraphHelper.GetAsync <Group>(httpClient, $"beta/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and mailNickname eq '{mailNickname}')&$select=Id,DisplayName,MailNickName,Description,Visibility", accessToken));
 }
        private bool IsEpApproval(PXSiteMapNode node)
        {
            var views = GraphHelper.GetGraphViews(node.GraphType, false);

            return(views.Any(x => x.Cache != null && x.Cache.CacheType == typeof(EPApproval)));
        }
Beispiel #18
0
 public static async Task <TeamChannel> UpdateChannelAsync(HttpClient httpClient, string accessToken, string groupId, string channelId, TeamChannel channel)
 {
     return(await GraphHelper.PatchAsync(httpClient, accessToken, $"beta/teams/{groupId}/channels/{channelId}", channel));
 }
Beispiel #19
0
        static async Task Main(string[] args)
        {
            try
            {
                Output.WriteLine("Parts Inventory Search Connector\n");

                // Load configuration from appsettings.json
                var appConfig = LoadAppSettings();
                if (appConfig == null)
                {
                    Output.WriteLine(Output.Error, "Missing or invalid user secrets");
                    Output.WriteLine(Output.Error, "Please see README.md for instructions on configuring the application.");
                    return;
                }

                // Save tenant ID for setting ACL on items
                _tenantId = appConfig["tenantId"];

                // Initialize the auth provider
                var authProvider = new ClientCredentialAuthProvider(
                    appConfig["appId"],
                    appConfig["tenantId"],
                    appConfig["appSecret"]
                    );

                // Check if the database is empty
                using (var db = new ApplianceDbContext())
                {
                    if (db.Parts.IgnoreQueryFilters().Count() <= 0)
                    {
                        Output.WriteLine(Output.Warning, "Database empty, importing entries from CSV file");
                        ImportCsvToDatabase(db, "ApplianceParts.csv");
                    }
                }

                _graphHelper = new GraphHelper(authProvider);

                do
                {
                    var userChoice = DoMenuPrompt();

                    switch (userChoice)
                    {
                    case MenuChoice.CreateConnection:
                        await CreateConnectionAsync();

                        break;

                    case MenuChoice.ChooseExistingConnection:
                        await SelectExistingConnectionAsync();

                        break;

                    case MenuChoice.DeleteConnection:
                        await DeleteCurrentConnectionAsync();

                        break;

                    case MenuChoice.RegisterSchema:
                        await RegisterSchemaAsync();

                        break;

                    case MenuChoice.ViewSchema:
                        await GetSchemaAsync();

                        break;

                    case MenuChoice.PushUpdatedItems:
                        await UpdateItemsFromDatabase(true);

                        break;

                    case MenuChoice.PushAllItems:
                        await UpdateItemsFromDatabase(false);

                        break;

                    case MenuChoice.Exit:
                        // Exit the program
                        Output.WriteLine("Goodbye...");
                        return;

                    case MenuChoice.Invalid:
                    default:
                        Output.WriteLine(Output.Warning, "Invalid choice! Please try again.");
                        break;
                    }

                    Output.WriteLine("");
                } while (true);
            }
            catch (Exception ex)
            {
                Output.WriteLine(Output.Error, "An unexpected exception occurred.");
                Output.WriteLine(Output.Error, ex.Message);
                Output.WriteLine(Output.Error, ex.StackTrace);
            }
        }
Beispiel #20
0
 public static async Task <HttpResponseMessage> DeleteTabAsync(string accessToken, HttpClient httpClient, string groupId, string channelId, string tabId)
 {
     return(await GraphHelper.DeleteAsync(httpClient, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tabId}", accessToken));
 }
Beispiel #21
0
        public static void BuildIndex(FullTextIndexRebuildProc graph, RecordType item)
        {
            Debug.Print("Start processing {0}", item.Name);
            Stopwatch sw = new Stopwatch();

            graph.Caches.Clear();
            graph.Clear(PXClearOption.ClearAll);

            PXProcessing <RecordType> .SetCurrentItem(item);

            Type entity = GraphHelper.GetType(item.Entity);

            PXSearchableAttribute searchableAttribute = null;
            var list = graph.Caches[entity].GetAttributes("NoteID");

            foreach (PXEventSubscriberAttribute att in list)
            {
                PXSearchableAttribute attribute = att as PXSearchableAttribute;
                if (attribute != null)
                {
                    searchableAttribute = attribute;
                    break;
                }
            }

            if (searchableAttribute == null)
            {
                return;
            }

            Type viewType;


            Type joinNote = typeof(LeftJoin <Note, On <Note.noteID, Equal <SearchIndex.noteID> > >);

            if (searchableAttribute.SelectForFastIndexing != null)
            {
                Type noteentity = entity;
                if (searchableAttribute.SelectForFastIndexing.IsGenericType)
                {
                    Type[] tables = searchableAttribute.SelectForFastIndexing.GetGenericArguments();
                    if (tables != null && tables.Length > 0 && typeof(IBqlTable).IsAssignableFrom(tables[0]))
                    {
                        noteentity = tables[0];
                    }
                }
                Type joinSearchIndex = BqlCommand.Compose(
                    typeof(LeftJoin <,>),
                    typeof(SearchIndex),
                    typeof(On <,>),
                    typeof(SearchIndex.noteID),
                    typeof(Equal <>),
                    noteentity.GetNestedType("noteID"));

                viewType = BqlCommand.AppendJoin(searchableAttribute.SelectForFastIndexing, joinSearchIndex);
                viewType = BqlCommand.AppendJoin(viewType, joinNote);
            }
            else
            {
                Type joinSearchIndex = BqlCommand.Compose(
                    typeof(LeftJoin <,>),
                    typeof(SearchIndex),
                    typeof(On <,>),
                    typeof(SearchIndex.noteID),
                    typeof(Equal <>),
                    entity.GetNestedType("noteID"));

                viewType = BqlCommand.Compose(typeof(Select <>), entity);
                viewType = BqlCommand.AppendJoin(viewType, joinSearchIndex);
                viewType = BqlCommand.AppendJoin(viewType, joinNote);
            }

            BqlCommand cmd = BqlCommand.CreateInstance(viewType);

            PXView        itemView = new PXView(graph, true, cmd);
            List <object> resultset;

            List <Type> fieldList       = new List <Type>(searchableAttribute.GetSearchableFields(graph.Caches[entity]));
            Type        entityForNoteId = entity;

            while (typeof(IBqlTable).IsAssignableFrom(entityForNoteId))
            {
                Type tN = entityForNoteId.GetNestedType("noteID");
                if (null != tN)
                {
                    fieldList.Add(tN);
                }
                entityForNoteId = entityForNoteId.BaseType;
            }
            fieldList.Add(typeof(SearchIndex.noteID));
            fieldList.Add(typeof(SearchIndex.category));
            fieldList.Add(typeof(SearchIndex.content));
            fieldList.Add(typeof(SearchIndex.entityType));
            fieldList.Add(typeof(Note.noteID));
            fieldList.Add(typeof(Note.noteText));

            sw.Start();
            using (new PXFieldScope(itemView, fieldList))
            {
                resultset = itemView.SelectMulti();
            }
            sw.Stop();
            Debug.Print("{0} GetResultset in {1} sec. Total records={2}", item.DisplayName, sw.Elapsed.TotalSeconds, resultset.Count);
            sw.Reset();
            sw.Start();

            int totalcount = resultset.Count;
            int cx         = 0;
            int dx         = 0;

            try
            {
                Dictionary <Guid, SearchIndex> insertDict = new Dictionary <Guid, SearchIndex>(resultset.Count);
                foreach (var res in resultset)
                {
                    cx++;

                    bool isSearchable = searchableAttribute.IsSearchable(graph.Caches[entity], ((PXResult)res)[entity]);
                    if (isSearchable)
                    {
                        dx++;

                        Note        note = (Note)((PXResult)res)[typeof(Note)];
                        SearchIndex si   = searchableAttribute.BuildSearchIndex(graph.Caches[entity], ((PXResult)res)[entity],
                                                                                (PXResult)res, ExtractNoteText(note));
                        SearchIndex searchIndex = (SearchIndex)((PXResult)res)[typeof(SearchIndex)];

                        if (searchIndex.NoteID != null && searchIndex.NoteID != si.NoteID)
                        {
                            PXSearchableAttribute.Delete(si);
                        }

                        if (searchIndex.NoteID == null)
                        {
                            if (!insertDict.ContainsKey(si.NoteID.Value))
                            {
                                insertDict.Add(si.NoteID.Value, si);
                            }
                        }
                        else if (si.Content != searchIndex.Content || si.Category != searchIndex.Category ||
                                 si.EntityType != searchIndex.EntityType)
                        {
                            PXSearchableAttribute.Update(si);
                        }
                    }
                }
                sw.Stop();
                Debug.Print("{0} Content building in {1} sec. Records processed = {2}. Searchable={3}", item.DisplayName, sw.Elapsed.TotalSeconds, totalcount, dx);
                sw.Reset();
                sw.Start();
                PXSearchableAttribute.BulkInsert(insertDict.Values);
                sw.Stop();
                Debug.Print("{0} BulkInsert in {1} sec.", item.DisplayName, sw.Elapsed.TotalSeconds);
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0} out of {1} processed. {2} are searchable. Error:{3}", cx, totalcount, dx, ex.Message);
                throw new Exception(msg, ex);
            }

            PXProcessing <RecordType> .SetProcessed();
        }
Beispiel #22
0
        public static async Task <TeamTab> AddTabAsync(HttpClient httpClient, string accessToken, string groupId, string channelId, string displayName, TeamTabType tabType, string teamsAppId, string entityId, string contentUrl, string removeUrl, string websiteUrl)
        {
            TeamTab tab = new TeamTab();

            switch (tabType)
            {
            case TeamTabType.Custom:
            {
                tab.TeamsAppId               = teamsAppId;
                tab.Configuration            = new TeamTabConfiguration();
                tab.Configuration.EntityId   = entityId;
                tab.Configuration.ContentUrl = contentUrl;
                tab.Configuration.RemoveUrl  = removeUrl;
                tab.Configuration.WebsiteUrl = websiteUrl;
                break;
            }

            case TeamTabType.DocumentLibrary:
            {
                tab.TeamsAppId               = "com.microsoft.teamspace.tab.files.sharepoint";
                tab.Configuration            = new TeamTabConfiguration();
                tab.Configuration.EntityId   = "";
                tab.Configuration.ContentUrl = contentUrl;
                tab.Configuration.RemoveUrl  = null;
                tab.Configuration.WebsiteUrl = null;
                break;
            }

            case TeamTabType.WebSite:
            {
                tab.TeamsAppId               = "com.microsoft.teamspace.tab.web";
                tab.Configuration            = new TeamTabConfiguration();
                tab.Configuration.EntityId   = null;
                tab.Configuration.ContentUrl = contentUrl;
                tab.Configuration.RemoveUrl  = null;
                tab.Configuration.WebsiteUrl = contentUrl;
                break;
            }

            case TeamTabType.Word:
            {
                tab.TeamsAppId               = "com.microsoft.teamspace.tab.file.staticviewer.word";
                tab.Configuration            = new TeamTabConfiguration();
                tab.Configuration.EntityId   = entityId;
                tab.Configuration.ContentUrl = contentUrl;
                tab.Configuration.RemoveUrl  = null;
                tab.Configuration.WebsiteUrl = null;
                break;
            }

            case TeamTabType.Excel:
            {
                tab.TeamsAppId               = "com.microsoft.teamspace.tab.file.staticviewer.excel";
                tab.Configuration            = new TeamTabConfiguration();
                tab.Configuration.EntityId   = entityId;
                tab.Configuration.ContentUrl = contentUrl;
                tab.Configuration.RemoveUrl  = null;
                tab.Configuration.WebsiteUrl = null;
                break;
            }

            case TeamTabType.PowerPoint:
            {
                tab.TeamsAppId               = "com.microsoft.teamspace.tab.file.staticviewer.powerpoint";
                tab.Configuration            = new TeamTabConfiguration();
                tab.Configuration.EntityId   = entityId;
                tab.Configuration.ContentUrl = contentUrl;
                tab.Configuration.RemoveUrl  = null;
                tab.Configuration.WebsiteUrl = null;
                break;
            }

            case TeamTabType.PDF:
            {
                tab.TeamsAppId               = "com.microsoft.teamspace.tab.file.staticviewer.pdf";
                tab.Configuration            = new TeamTabConfiguration();
                tab.Configuration.EntityId   = entityId;
                tab.Configuration.ContentUrl = contentUrl;
                tab.Configuration.RemoveUrl  = null;
                tab.Configuration.WebsiteUrl = null;
                break;
            }

            case TeamTabType.Wiki:
            {
                tab.TeamsAppId = "com.microsoft.teamspace.tab.wiki";
                break;
            }

            case TeamTabType.Planner:
            {
                tab.TeamsAppId = "com.microsoft.teamspace.tab.planner";
                break;
            }

            case TeamTabType.MicrosoftStream:
            {
                tab.TeamsAppId = "com.microsoftstream.embed.skypeteamstab";
                break;
            }

            case TeamTabType.MicrosoftForms:
            {
                tab.TeamsAppId = "81fef3a6-72aa-4648-a763-de824aeafb7d";
                break;
            }

            case TeamTabType.OneNote:
            {
                tab.TeamsAppId = "0d820ecd-def2-4297-adad-78056cde7c78";
                break;
            }

            case TeamTabType.PowerBI:
            {
                tab.TeamsAppId = "com.microsoft.teamspace.tab.powerbi";
                break;
            }

            case TeamTabType.SharePointPageAndList:
            {
                tab.TeamsAppId = "2a527703-1f6f-4559-a332-d8a7d288cd88";
                break;
            }
            }
            tab.DisplayName = displayName;
            tab.TeamsApp    = $"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{tab.TeamsAppId}";
            return(await GraphHelper.PostAsync <TeamTab>(httpClient, $"v1.0/teams/{groupId}/channels/{channelId}/tabs", tab, accessToken));
        }
Beispiel #23
0
        public static async Task <Team> NewTeamAsync(string accessToken, HttpClient httpClient, string groupId, string displayName, string description, string classification, string mailNickname, string owner, GroupVisibility visibility, TeamCreationInformation teamCI)
        {
            Group group      = null;
            Team  returnTeam = null;

            // Create group
            if (string.IsNullOrEmpty(groupId))
            {
                group = await CreateGroupAsync(accessToken, httpClient, displayName, description, classification, mailNickname, owner, visibility);

                bool wait       = true;
                int  iterations = 0;
                while (wait)
                {
                    iterations++;

                    try
                    {
                        var createdGroup = await GraphHelper.GetAsync <Group>(httpClient, $"v1.0/groups/{group.Id}", accessToken);

                        if (!string.IsNullOrEmpty(createdGroup.DisplayName))
                        {
                            wait = false;
                        }
                    }
                    catch (Exception)
                    {
                        // In case of exception wait for 5 secs
                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
                    }

                    // Don't wait more than 1 minute
                    if (iterations > 12)
                    {
                        wait = false;
                    }
                }
            }
            else
            {
                group = await GraphHelper.GetAsync <Group>(httpClient, $"v1.0/groups/{groupId}", accessToken);

                if (group == null)
                {
                    throw new PSArgumentException($"Cannot find group with id {groupId}");
                }
                teamCI.Visibility  = group.Visibility;
                teamCI.Description = group.Description;
            }
            if (group != null)
            {
                Team team      = teamCI.ToTeam();
                var  retry     = true;
                var  iteration = 0;
                while (retry)
                {
                    try
                    {
                        var teamSettings = await GraphHelper.PutAsync(httpClient, $"v1.0/groups/{group.Id}/team", team, accessToken);

                        if (teamSettings != null)
                        {
                            returnTeam = await TeamsUtility.GetTeamAsync(accessToken, httpClient, group.Id);
                        }
                        retry = false;
                    }

                    catch (Exception)
                    {
                        System.Threading.Thread.Sleep(5000);
                        iteration++;
                    }

                    if (iteration > 10) // don't try more than 10 times
                    {
                        retry = false;
                    }
                }
            }
            return(returnTeam);
        }
Beispiel #24
0
 public static async Task <HttpResponseMessage> DeleteTeamAsync(string accessToken, HttpClient httpClient, string groupId)
 {
     return(await GraphHelper.DeleteAsync(httpClient, $"v1.0/groups/{groupId}", accessToken));
 }
Beispiel #25
0
 public static async Task <Team> UpdateTeamAsync(HttpClient httpClient, string accessToken, string groupId, Team team)
 {
     return(await GraphHelper.PatchAsync <Team>(httpClient, accessToken, $"v1.0/teams/{groupId}", team));
 }
        private async void EmailLogsButton_Click(object sender, RoutedEventArgs e)
        {
            var provider = App.AuthManager.GetGraphProvider();

            if (provider == null)
            {
                return;
            }

            if (!provider.IsTokenValid())
            {
                AppService.DisplayAadSignInDialog(typeof(LogsPage));
                return;
            }

            var selected = LogFilesCollection.Where(item => item.IsSelected);
            var logs     = await LogUtil.GetLogFilesAsync();

            var fileList = new List <StorageFile>();

            foreach (var sel in selected)
            {
                var temp = logs.Where(file => file.Path == sel.Path).FirstOrDefault();
                if (temp != null)
                {
                    fileList.Add(temp as StorageFile);
                }
            }

            if (fileList.Count > 0)
            {
                var emailConfirmText = string.Format(fileList.Count > 1 || fileList.Count == 0 ?
                                                     Common.GetLocalizedText("EmailLogsSelfText") :
                                                     Common.GetLocalizedText("EmailLogSelfText"), fileList.Count);
                if (!await AppService.YesNoAsync(Common.GetLocalizedText("EmailLogsText"), emailConfirmText))
                {
                    return;
                }

                var messageContent = LogUtil.CreateMessageContent(GetType().Name, CustomContentService?.GetContent <string>(CustomContentConstants.BugTemplate));
                using (var graphHelper = new GraphHelper(provider))
                {
                    try
                    {
                        var email = await LogUtil.EmailLogsAsync(graphHelper, "[Smart Display] LOG MAILER", messageContent, fileList.ToArray());

                        var emailSuccessText = string.Format(fileList.Count > 1 || fileList.Count == 0 ?
                                                             Common.GetLocalizedText("EmailedLogsText") :
                                                             Common.GetLocalizedText("EmailedLogText"), fileList.Count, email);
                        PageService.ShowNotification(emailSuccessText);
                    }
                    catch (Exception ex)
                    {
                        PageService.ShowNotification(string.Format(Common.GetLocalizedText("EmailLogsProblemText"), ex.Message));
                    }
                }
            }
            else
            {
                PageService.ShowNotification(Common.GetLocalizedText("NoLogsSelectedText"));
            }
        }
Beispiel #27
0
 public static async Task <Group> UpdateGroupAsync(HttpClient httpClient, string accessToken, string groupId, Group group)
 {
     return(await GraphHelper.PatchAsync <Group>(httpClient, accessToken, $"v1.0/groups/{groupId}", group));
 }
Beispiel #28
0
        /// <summary>
        /// Compute the Numeric Cholesky factorization, L = chol (A, [pinv parent cp]).
        /// </summary>
        /// <returns>Numeric Cholesky factorization</returns>
        private void Factorize(CompressedColumnStorage <double> A, IProgress progress)
        {
            double d, lki;
            int    top, i, p, k, cci;

            int n = A.ColumnCount;

            // Allocate workspace.
            var c = new int[n];
            var s = new int[n];

            var x = this.temp;

            var colp   = S.cp;
            var pinv   = S.pinv;
            var parent = S.parent;

            var C = pinv != null?PermuteSym(A, pinv, true) : A;

            var cp = C.ColumnPointers;
            var ci = C.RowIndices;
            var cx = C.Values;

            this.L = CompressedColumnStorage <double> .Create(n, n, colp[n]);

            var lp = L.ColumnPointers;
            var li = L.RowIndices;
            var lx = L.Values;

            for (k = 0; k < n; k++)
            {
                lp[k] = c[k] = colp[k];
            }

            double current = 0.0;
            double step    = n / 100.0;

            for (k = 0; k < n; k++) // compute L(k,:) for L*L' = C
            {
                // Progress reporting.
                if (k >= current)
                {
                    current += step;

                    if (progress != null)
                    {
                        progress.Report(k / (double)n);
                    }
                }

                // Find nonzero pattern of L(k,:)
                top  = GraphHelper.EtreeReach(SymbolicColumnStorage.Create(C, false), k, parent, s, c);
                x[k] = 0;                           // x (0:k) is now zero
                for (p = cp[k]; p < cp[k + 1]; p++) // x = full(triu(C(:,k)))
                {
                    if (ci[p] <= k)
                    {
                        x[ci[p]] = cx[p];
                    }
                }
                d    = x[k]; // d = C(k,k)
                x[k] = 0;    // clear x for k+1st iteration

                // Triangular solve
                for (; top < n; top++)       // solve L(0:k-1,0:k-1) * x = C(:,k)
                {
                    i    = s[top];           // s [top..n-1] is pattern of L(k,:)
                    lki  = x[i] / lx[lp[i]]; // L(k,i) = x (i) / L(i,i)
                    x[i] = 0;                // clear x for k+1st iteration
                    cci  = c[i];
                    for (p = lp[i] + 1; p < cci; p++)
                    {
                        x[li[p]] -= lx[p] * lki;
                    }
                    d    -= lki * lki; // d = d - L(k,i)*L(k,i)
                    p     = c[i]++;
                    li[p] = k;         // store L(k,i) in column i
                    lx[p] = lki;
                }
                // Compute L(k,k)
                if (d <= 0)
                {
                    throw new Exception(Resources.MatrixSymmetricPositiveDefinite);
                }

                p     = c[k]++;
                li[p] = k; // store L(k,k) = sqrt (d) in column k
                lx[p] = Math.Sqrt(d);
            }
            lp[n] = colp[n]; // finalize L
        }
Beispiel #29
0
        public static async Task <List <User> > GetUsersAsync(HttpClient httpClient, string accessToken, string groupId, string role)
        {
            var selectedRole = role != null?role.ToLower() : null;

            var owners  = new List <User>();
            var guests  = new List <User>();
            var members = new List <User>();

            if (selectedRole != "guest")
            {
                owners = (await GraphHelper.GetAsync <RestResultCollection <User> >(httpClient, $"v1.0/groups/{groupId}/owners?$select=Id,displayName,userPrincipalName,userType", accessToken)).Items.Select(t => new User()
                {
                    Id                = t.Id,
                    DisplayName       = t.DisplayName,
                    UserPrincipalName = t.UserPrincipalName,
                    UserType          = "Owner"
                }).ToList();
            }
            if (selectedRole != "owner")
            {
                var users = (await GraphHelper.GetAsync <RestResultCollection <User> >(httpClient, $"v1.0/groups/{groupId}/members?$select=Id,displayName,userPrincipalName,userType", accessToken)).Items;
                HashSet <string> hashSet = new HashSet <string>(owners.Select(u => u.Id));
                foreach (var user in users)
                {
                    if (!hashSet.Contains(user.Id))
                    {
                        if (user.UserType != null && user.UserType.ToLower().Equals("guest"))
                        {
                            guests.Add(new User()
                            {
                                DisplayName = user.DisplayName, Id = user.Id, UserPrincipalName = user.UserPrincipalName, UserType = "Guest"
                            });
                        }
                        else
                        {
                            members.Add(new User()
                            {
                                DisplayName = user.DisplayName, Id = user.Id, UserPrincipalName = user.UserPrincipalName, UserType = "Member"
                            });
                        }
                    }
                }
            }
            var finalList = new List <User>();

            if (string.IsNullOrEmpty(selectedRole))
            {
                finalList.AddRange(owners);
                finalList.AddRange(members);
                finalList.AddRange(guests);
            }
            else if (selectedRole == "owner")
            {
                finalList.AddRange(owners);
            }
            else if (selectedRole == "member")
            {
                finalList.AddRange(members);
            }
            else if (selectedRole == "guest")
            {
                finalList.AddRange(guests);
            }
            return(finalList);
        }
Beispiel #30
0
    private void RenderCurve(SerializedPropertyX curveProperty, ConsiderationRenderData data)
    {
        ResponseCurve curve         = curveProperty.GetValue <ResponseCurve>();
        bool          updateTexture = false;
        Texture2D     graphTexture  = data.graphTexture;

        if (graphTexture == null)
        {
            data.graphTexture = new Texture2D(1, 1, TextureFormat.RGBA32, true);
        }
        EditorGUILayout.BeginHorizontal();
        data.isCurveShown = EditorGUILayout.Foldout(data.isCurveShown, "Curve(" + curve.curveType.ToString() + ")");
        if (!data.isCurveShown)
        {
            if (graphTexture.width != 64)
            {
                graphTexture.Resize(64, 32);

                Rect rect = new Rect()
                {
                    x      = 0,
                    y      = 0,
                    width  = graphTexture.width,
                    height = graphTexture.height
                };
                GraphHelper.DrawGraphLines(rect, graphTexture, (float input) => {
                    return(curve.Evaluate(input));
                });
                graphTexture.FlipVertically();
                graphTexture.Apply(true);
            }
            GUILayout.FlexibleSpace();
            GUIContent content = new GUIContent();
            content.text  = curve.DisplayString;
            content.image = graphTexture;
            GUIStyle style = new GUIStyle(GUI.skin.box);
            style.alignment = TextAnchor.MiddleLeft;
            GUILayout.Box(content, style);
        }

        EditorGUILayout.EndHorizontal();

        if (!data.isCurveShown)
        {
            return;
        }

        DrawerUtil.PushIndentLevel(1);

        EditorGUILayout.BeginHorizontal();
        {
            EditorGUI.BeginChangeCheck();
            GUILayout.BeginVertical(GUILayout.MaxWidth(400f));
            curve.curveType = (ResponseCurveType)EditorGUILayout.EnumPopup("Curve Type", curve.curveType);
            curve.slope     = EditorGUILayout.FloatField("Slope", curve.slope);
            curve.exp       = EditorGUILayout.FloatField("Exp", curve.exp);
            curve.vShift    = EditorGUILayout.FloatField("Vertical Shift", curve.vShift);
            curve.hShift    = EditorGUILayout.FloatField("Horizontal Shift", curve.hShift);
            curve.threshold = EditorGUILayout.FloatField("Threshold", curve.threshold);
            curve.invert    = EditorGUILayout.Toggle(new GUIContent("Inverted"), curve.invert);
            GUILayout.BeginHorizontal();
            GUILayout.Space(EditorGUIUtility.labelWidth);
            if (GUILayout.Button("Reset"))
            {
                curve.Reset();
            }
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
            updateTexture = EditorGUI.EndChangeCheck();
        }
        //draw the graph
        {
            if (updateTexture || graphTexture.width != 512)
            {
                curveProperty.Update();
                graphTexture.Resize(512, (int)(8.75f * EditorGUIUtility.singleLineHeight));
                Rect rect = new Rect()
                {
                    x      = 0,
                    y      = 0,
                    width  = graphTexture.width,
                    height = graphTexture.height
                };
                GraphHelper.DrawGraphLines(rect, graphTexture, (float input) => {
                    return(curve.Evaluate(input));
                });
                graphTexture.FlipVertically();
                graphTexture.Apply(true);
            }
            DrawerUtil.DrawLayoutTexture(graphTexture);
        }

        EditorGUILayout.EndHorizontal();
        DrawerUtil.PopIndentLevel();
    }
Beispiel #31
0
        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            _graphHelper = new GraphHelper(exampleChart);
            _fftwHelper = new FFTWHelper();

            foreach (string choice in DropDownChoices)
            {
                ComboBox_Input.Items.Add(new ComboBoxItem { Content = choice });
            }
        }