public async Task Post([FromBody] GraphSettings value, [FromUri] string collectionId)
 {
     await settingsRepo.CreateOrUpdateItemAsync(value, collectionId);
 }
 public GraphService(GraphSettings graphSettings, ILogger <GraphService> logger)
 {
     _settings = graphSettings;
     _log      = logger;
 }
        static async Task Main(string[] args)
        {
            var plants = new List <string>();

            if (args.Length > 1)
            {
                Console.WriteLine(@"Error: Invalid number of arguments.");
                return;
            }

            if (args.Length == 1)
            {
                var argPlants = args[0].Split(',');

                foreach (var plant in argPlants)
                {
                    if (!plant.StartsWith("PCS$"))
                    {
                        Console.WriteLine(@"Error: Plant names must start with 'PCS$'");
                        return;
                    }

                    plants.Add(plant);
                }
            }

            var path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

            var config = new ConfigurationBuilder()
                         .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                         .AddJsonFile($"{path}\\hosting.json", false, true)
                         .AddUserSecrets <Program>()
                         .Build();

            var removeUserAccess = bool.Parse(config["RemoveUserAccessEnabled"]);

            var personCreatedById    = long.Parse(config["PersonCreatedById"], CultureInfo.InvariantCulture);
            var personCreatedByCache = new PersonCreatedByCache(personCreatedById);

            var graphSettings = new GraphSettings();

            config.Bind(nameof(GraphSettings), graphSettings);

            //setup our DI
            var serviceCollection = new ServiceCollection()
                                    .AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(config.GetSection("Logging"));
                loggingBuilder.AddConsole();
            })
                                    .AddApplicationInsightsTelemetryWorkerService(config["ApplicationInsights:InstrumentationKey"])
                                    .AddSingleton <ISyncService, SyncService>()
                                    .AddSingleton(personCreatedByCache)
                                    .AddSingleton(graphSettings)
                                    .AddServices()
                                    .AddRepositories()
                                    .AddDbContext(config["ConnectionString"]);

            var services = serviceCollection.BuildServiceProvider();

            var logger = services.GetRequiredService <ILogger <Program> >();

            var syncService = services.GetService <ISyncService>();

            try
            {
                await syncService.StartAccessSync(plants, removeUserAccess);
            }
            catch (Exception e)
            {
                logger.LogError($"[GroupSync Error] : {e.Message}");
                logger.LogError(e.StackTrace);
            }

            // Take a break to allow AI to finish logging.
            await Task.Delay(10000);
        }
Exemplo n.º 4
0
 public DiagramSettingsView(DynamicGraph dGraph)
 {
     this.GSettings = new GraphSettings();
     this.Graph = dGraph;
     this.Graph.Settings = this.GSettings;
 }
Exemplo n.º 5
0
        private void resetViewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            graphSettings = defaultGraphSettings.Clone();

            graph.ResetView();
        }
Exemplo n.º 6
0
 public RexProClient(Func <TcpClient> tcpClientProvider, GraphSettings settings)
 {
     this.tcpClientProvider = tcpClientProvider;
 }
 public static bool IsValide(this GraphSettings settings) =>
 Uri.TryCreate(settings.ServiceUri, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
Exemplo n.º 8
0
        public ActionResult ShowThumbnail(string id)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // Setup Graph API connection and get Group membership
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                // User user = graphConnection.Get<User>(id);
                User user = new User();
                user.ObjectId = id;

                try
                {
                    Stream ms = graphConnection.GetStreamProperty(user, GraphProperty.ThumbnailPhoto, "image/jpeg");
                    user.ThumbnailPhoto = ms;
                }
                catch
                {
                    user.ThumbnailPhoto = null;
                }


                if (user.ThumbnailPhoto != null)
                {
                    return(File(user.ThumbnailPhoto, "image/jpeg"));
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
            }

            return(View());
        }
Exemplo n.º 9
0
 public IndexModel(ITokenAcquisition tokenAcquisition, IOptions <GraphSettings> graphSettingsValue, IHttpClientFactory httpClientFactory)
 {
     httpClient            = httpClientFactory.CreateClient();
     this.tokenAcquisition = tokenAcquisition;
     graphSettings         = graphSettingsValue.Value;
 }
 public AssociativyInternalLinkGraphManageGraphPart()
 {
     GraphSettings = new GraphSettings();
 }
Exemplo n.º 11
0
 public OrientApiConnectionSettings(GraphSettings graphSettings)
     : this(graphSettings.Server, graphSettings.Database, graphSettings.Port, graphSettings.Username, graphSettings.Password)
 {
 }
Exemplo n.º 12
0
 public void Draw(IGraphLayout graphLayout, Rect drawingArea, GraphSettings graphSettings)
 {
     Draw(graphLayout, drawingArea, graphSettings, 10, Vector2.zero);
 }
 internal AssemblyGraphService(GraphSettings settings) => this.settings = settings;
Exemplo n.º 14
0
        private void seriesColorsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GraphColorSettings graphColorSettings = new GraphColorSettings();

            graphColorSettings.GraphSettings = collectorTimeGraph.GetGraphSettings();
            graphColorSettings.GraphSettings.SeriesColors.AddRange((from Color s in seriesColors select GraphSettings.ConvertColorToName(s)));

            //graphColorSettings.InitializeGraphSettings();
            //graphColorSettings.GraphSettings.SeriesColors.AddRange((from string s in Properties.Settings.Default.GraphLineColors select s));
            //graphColorSettings.GraphSettings.BackgroundColor1 = GraphSettings.ConvertColorToName(Properties.Settings.Default.GraphBackgroundColor1);
            //graphColorSettings.GraphSettings.BackgroundColor2 = GraphSettings.ConvertColorToName(Properties.Settings.Default.GraphBackgroundColor2);
            //graphColorSettings.GraphSettings.GridColor = GraphSettings.ConvertColorToName(Properties.Settings.Default.GraphGridColor);
            //graphColorSettings.GraphSettings.AxisLabelsColor = GraphSettings.ConvertColorToName(Properties.Settings.Default.GraphAxisLabelsColor);
            //graphColorSettings.GraphSettings.SelectionBarColor = GraphSettings.ConvertColorToName(Properties.Settings.Default.GraphSelectionBarColor);
            //graphColorSettings.GraphSettings.GraphType = Properties.Settings.Default.GraphDefaultType;
            //graphColorSettings.GraphSettings.GradientDirection = Properties.Settings.Default.GraphGradientDirection;
            //graphColorSettings.GraphSettings.ClosestClickedValueType = Properties.Settings.Default.GraphClosestClickedValueType;
            //graphColorSettings.GraphSettings.ClosestClickedValueColor = GraphSettings.ConvertColorToName(Properties.Settings.Default.GraphClosestClickedValueColor);
            //graphColorSettings.GraphSettings.HeaderVisible = Properties.Settings.Default.GraphHeaderVisible;
            //graphColorSettings.GraphSettings.FooterVisible = Properties.Settings.Default.GraphLegendVisible;
            //graphColorSettings.GraphSettings.HorisontalGridLinesVisible = Properties.Settings.Default.GraphHorisontalGridLinesVisible;
            //graphColorSettings.GraphSettings.VerticalGridLinesVisible = Properties.Settings.Default.GraphVerticalGridLinesVisible;
            //graphColorSettings.GraphSettings.SelectionBarVisible = Properties.Settings.Default.GraphSelectionBarVisible;
            //graphColorSettings.GraphSettings.HighlightClickedSeriesVisible = Properties.Settings.Default.GraphHighlightClickedSeriesVisible;
            //graphColorSettings.GraphSettings.EnableFillAreaBelowSeries = Properties.Settings.Default.GraphEnableFillAreaBelowSeries;
            //graphColorSettings.GraphSettings.FillAreaBelowSeriesAlpha = Properties.Settings.Default.GraphFillAreaBelowSeriesAlpha;

            //graphColorSettings.GraphSettings.GridColor = Properties.Settings.Default.GraphGridColor.Name;
            if (graphColorSettings.ShowDialog() == DialogResult.OK)
            {
                collectorTimeGraph.SetFromGraphSettings(graphColorSettings.GraphSettings);
                seriesColors = new List <Color>();
                seriesColors.AddRange((from string colorName in graphColorSettings.GraphSettings.SeriesColors
                                       select GraphSettings.ConvertColorFromName(colorName)));

                //Properties.Settings.Default.GraphLineColors = new System.Collections.Specialized.StringCollection();
                //Properties.Settings.Default.GraphLineColors.AddRange(graphColorSettings.GraphSettings.SeriesColors.ToArray());
                //Properties.Settings.Default.GraphBackgroundColor1 = GraphSettings.ConvertColorFromName(graphColorSettings.GraphSettings.BackgroundColor1);
                //Properties.Settings.Default.GraphBackgroundColor2 = GraphSettings.ConvertColorFromName(graphColorSettings.GraphSettings.BackgroundColor2);
                //Properties.Settings.Default.GraphGridColor = GraphSettings.ConvertColorFromName(graphColorSettings.GraphSettings.GridColor);
                //Properties.Settings.Default.GraphAxisLabelsColor = GraphSettings.ConvertColorFromName(graphColorSettings.GraphSettings.AxisLabelsColor);
                //Properties.Settings.Default.GraphDefaultType = graphColorSettings.GraphSettings.GraphType;
                //Properties.Settings.Default.GraphGradientDirection = graphColorSettings.GraphSettings.GradientDirection;
                //Properties.Settings.Default.GraphClosestClickedValueType = graphColorSettings.GraphSettings.ClosestClickedValueType;
                //Properties.Settings.Default.GraphClosestClickedValueColor = GraphSettings.ConvertColorFromName(graphColorSettings.GraphSettings.ClosestClickedValueColor);
                //Properties.Settings.Default.GraphHeaderVisible = graphColorSettings.GraphSettings.HeaderVisible;
                //Properties.Settings.Default.GraphLegendVisible = graphColorSettings.GraphSettings.FooterVisible;
                //Properties.Settings.Default.GraphHorisontalGridLinesVisible = graphColorSettings.GraphSettings.HorisontalGridLinesVisible;
                //Properties.Settings.Default.GraphVerticalGridLinesVisible = graphColorSettings.GraphSettings.VerticalGridLinesVisible;
                //Properties.Settings.Default.GraphSelectionBarVisible = graphColorSettings.GraphSettings.SelectionBarVisible;
                //Properties.Settings.Default.GraphHighlightClickedSeriesVisible = graphColorSettings.GraphSettings.HighlightClickedSeriesVisible;
                //Properties.Settings.Default.GraphEnableFillAreaBelowSeries = graphColorSettings.GraphSettings.EnableFillAreaBelowSeries;
                //Properties.Settings.Default.GraphFillAreaBelowSeriesAlpha = graphColorSettings.GraphSettings.FillAreaBelowSeriesAlpha;

                //collectorTimeGraph.GraphVerticalAxisType = (GraphVerticalAxisType)Properties.Settings.Default.GraphDefaultType;
                //LoadGraphColors();
                LoadControls(true);
            }
        }
Exemplo n.º 15
0
        static void Main()
        {
            // get OAuth token using Client Credentials
            string tenantName = "GraphDir1.onMicrosoft.com";
            string authString = "https://login.windows.net/" + tenantName;

            AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);

            // Config for OAuth client credentials
            string           clientId     = "118473c2-7619-46e3-a8e4-6da8d5f56e12";
            string           clientSecret = "hOrJ0r0TZ4GQ3obp+vk3FZ7JBVP+TX353kNo6QwNq7Q=";
            ClientCredential clientCred   = new ClientCredential(clientId, clientSecret);
            string           resource     = "https://graph.windows.net";
            string           token;

            try
            {
                AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred);
                token = authenticationResult.AccessToken;
            }

            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                Console.ResetColor();
                Console.ReadKey();
                return;
            }


            // record start DateTime of execution
            string CurrentDateTime = DateTime.Now.ToUniversalTime().ToString();

            //*********************************************************************
            // setup Graph connection
            //*********************************************************************
            Guid          ClientRequestId = Guid.NewGuid();
            GraphSettings graphSettings   = new GraphSettings();

            graphSettings.ApiVersion      = "2013-11-08";
            graphSettings.GraphDomainName = "graph.windows.net";
            GraphConnection graphConnection = new GraphConnection(token, ClientRequestId, graphSettings);
            VerifiedDomain  initialDomain   = new VerifiedDomain();
            VerifiedDomain  defaultDomain   = new VerifiedDomain();

            //*********************************************************************
            // Get Tenant Details
            // Note: update the string tenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your tenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************
            string      tenantId = "4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34";
            GraphObject tenant   = graphConnection.Get(typeof(TenantDetail), tenantId);

            if (tenant == null)
            {
                Console.WriteLine("Tenant not found");
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
                defaultDomain = tenantDetail.VerifiedDomains.First(x => x.Default.HasValue && x.Default.Value);
                Console.WriteLine("Default Domain Name: " + defaultDomain.Name);
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    Console.WriteLine("Tenant Tech Contact: " + techContact);
                }
            }
            //*********************************************************************
            // Demonstrate Getting a list of Users with paging (get 4 users), sort by displayName
            //*********************************************************************
            Console.WriteLine("\n Retrieving Users");

            FilterGenerator userFilter = new FilterGenerator();

            userFilter.Top             = 4;
            userFilter.OrderByProperty = GraphProperty.DisplayName;
            PagedResults <User> users = graphConnection.List <User>(null, userFilter);

            foreach (User user in users.Results)
            {
                Console.WriteLine("UserObjectId: {0}  UPN: {1}", user.ObjectId, user.UserPrincipalName);
            }

            // if there are more users to retrieve, get the rest of the users, and specify maximum page size 999
            do
            {
                userFilter.Top = 999;
                if (users.PageToken != null)
                {
                    users = graphConnection.List <User>(users.PageToken, userFilter);
                    Console.WriteLine("\n Next page of results");
                }

                foreach (User user in users.Results)
                {
                    Console.WriteLine("DisplayName: {0}  UPN: {1}", user.DisplayName, user.UserPrincipalName);
                }
            } while (users.PageToken != null);

            // search for a single user by UPN
            string          searchString     = "adam@" + initialDomain.Name;
            FilterGenerator filter           = new FilterGenerator();
            Expression      filterExpression = ExpressionHelper.CreateEqualsExpression(typeof(User), GraphProperty.UserPrincipalName, searchString);

            filter.QueryFilter = filterExpression;


            User retrievedUser = new User();
            PagedResults <User> pagedUserResults = graphConnection.List <User>(null, filter);

            // should only find one user with the specified UPN
            if (pagedUserResults.Results.Count == 1)
            {
                retrievedUser = pagedUserResults.Results[0] as User;
            }
            else
            {
                Console.WriteLine("User not found {0}", searchString);
            }

            if (retrievedUser.UserPrincipalName != null)
            {
                Console.WriteLine("\n Found User: "******"  UPN: " + retrievedUser.UserPrincipalName);

                // get the user's Manager
                int count = 0;
                PagedResults <GraphObject> managers = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.Manager, null);
                foreach (GraphObject managerObject in managers.Results)
                {
                    if (managerObject.ODataTypeName.Contains("User"))
                    {
                        User manager = (User)managers.Results[count];
                        Console.WriteLine(" Manager: {0}  UPN: {1}", manager.DisplayName, manager.UserPrincipalName);
                    }
                    count++;
                }
                //*********************************************************************
                // get the user's Direct Reports
                //*********************************************************************
                int top = 99;
                PagedResults <GraphObject> directReportObjects = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.DirectReports, null, top);
                foreach (GraphObject graphObject in directReportObjects.Results)
                {
                    if (graphObject.ODataTypeName.Contains("User"))
                    {
                        User User = (User)graphObject;
                        Console.WriteLine(" DirectReport {0}: {1}  UPN: {2}", User.ObjectType, User.DisplayName, User.UserPrincipalName);
                    }

                    if (graphObject.ODataTypeName.Contains("Contact"))
                    {
                        Contact Contact = (Contact)graphObject;
                        Console.WriteLine(" DirectReport {0}: {1}  Mail: {2} ", Contact.ObjectType, Contact.DisplayName, Contact.Mail);
                    }
                }
                //*********************************************************************
                // get a list of Group IDs that the user is a member of
                //*********************************************************************
                Console.WriteLine("\n {0} is a member of the following Groups (IDs)", retrievedUser.DisplayName);
                bool           securityGroupsOnly   = false;
                IList <string> usersGroupMembership = graphConnection.GetMemberGroups(retrievedUser, securityGroupsOnly);
                foreach (String groupId in usersGroupMembership)
                {
                    Console.WriteLine("Member of Group ID: " + groupId);
                }


                //*********************************************************************
                // get the User's Group and Role membership, getting the complete set of objects
                //*********************************************************************
                PagedResults <GraphObject> memberOfObjects = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.MemberOf, null, top);
                foreach (GraphObject graphObject in memberOfObjects.Results)
                {
                    if (graphObject.ODataTypeName.Contains("Group"))
                    {
                        Group Group = (Group)graphObject;
                        Console.WriteLine(" Group: {0}  Description: {1}", Group.DisplayName, Group.Description);
                    }

                    if (graphObject.ODataTypeName.Contains("Role"))
                    {
                        Role Role = (Role)graphObject;
                        Console.WriteLine(" Role: {0}  Description: {1}", Role.DisplayName, Role.Description);
                    }
                }
            }
            //*********************************************************************
            // People picker
            // Search for a user using text string "ad" match against userPrincipalName, proxyAddresses, displayName, giveName, surname
            //*********************************************************************
            searchString = "ad";
            Console.WriteLine("\nSearching for any user with string {0} in UPN,ProxyAddresses,DisplayName,First or Last Name", searchString);

            FilterGenerator userMatchFilter = new FilterGenerator();

            userMatchFilter.Top = 19;
            Expression firstExpression  = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.UserPrincipalName, searchString);
            Expression secondExpression = ExpressionHelper.CreateAnyExpression(typeof(User), GraphProperty.ProxyAddresses, "smtp:" + searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(firstExpression, secondExpression, ExpressionType.Or);

            Expression thirdExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.DisplayName, searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, thirdExpression, ExpressionType.Or);

            Expression fourthExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.GivenName, searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, fourthExpression, ExpressionType.Or);

            Expression fifthExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.Surname, searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, fifthExpression, ExpressionType.Or);

            PagedResults <User> serachResults = graphConnection.List <User>(null, userMatchFilter);

            if (serachResults.Results.Count > 0)
            {
                foreach (User User in serachResults.Results)
                {
                    Console.WriteLine("User DisplayName: {0}  UPN: {1}", User.DisplayName, User.UserPrincipalName);
                }
            }
            else
            {
                Console.WriteLine("User not found");
            }

            //*********************************************************************
            // Search for a group using a startsWith filter (displayName property)
            //*********************************************************************
            Group retrievedGroup = new Group();

            searchString       = "Wash";
            filter.QueryFilter = ExpressionHelper.CreateStartsWithExpression(typeof(Group), GraphProperty.DisplayName, searchString);
            filter.Top         = 99;

            PagedResults <Group> pagedGroupResults = graphConnection.List <Group>(null, filter);

            if (pagedGroupResults.Results.Count > 0)
            {
                retrievedGroup = pagedGroupResults.Results[0] as Group;
            }
            else
            {
                Console.WriteLine("Group Not Found");
            }

            if (retrievedGroup.ObjectId != null)
            {
                Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + "  " + retrievedGroup.Description);

                //*********************************************************************
                // get the groups' membership using GetAllDirectLinks -
                // Note this method retrieves ALL links in one request - please use this method with care - this
                // may return a very large number of objects
                //*********************************************************************

                GraphObject graphObj = (GraphObject)retrievedGroup;

                IList <GraphObject> members = graphConnection.GetAllDirectLinks(graphObj, LinkProperty.Members);
                if (members.Count > 0)
                {
                    Console.WriteLine(" Members:");
                    foreach (GraphObject graphObject in members)
                    {
                        if (graphObject.ODataTypeName.Contains("User"))
                        {
                            User User = (User)graphObject;
                            Console.WriteLine("User DisplayName: {0}  UPN: {1}", User.DisplayName, User.UserPrincipalName);
                        }

                        if (graphObject.ODataTypeName.Contains("Group"))
                        {
                            Group Group = (Group)graphObject;
                            Console.WriteLine("Group DisplayName: {0}", Group.DisplayName);
                        }

                        if (graphObject.ODataTypeName.Contains("Contact"))
                        {
                            Contact Contact = (Contact)graphObject;
                            Console.WriteLine("Contact DisplayName: {0}", Contact.DisplayName);
                        }
                    }
                }
            }
            //*********************************************************************
            // Search for a Role by displayName
            //*********************************************************************
            searchString       = "Company Administrator";
            filter.QueryFilter = ExpressionHelper.CreateStartsWithExpression(typeof(Role), GraphProperty.DisplayName, searchString);
            PagedResults <Role> pagedRoleResults = graphConnection.List <Role>(null, null);

            if (pagedRoleResults.Results.Count > 0)
            {
                foreach (GraphObject graphObject in pagedRoleResults.Results)
                {
                    Role role = graphObject as Role;
                    if (role.DisplayName == searchString.Trim())
                    {
                        Console.WriteLine("\n Found Role: {0} {1} {2} ", role.DisplayName, role.Description, role.ObjectId);
                    }
                }
            }
            else
            {
                Console.WriteLine("Role Not Found {0}", searchString);
            }

            //*********************************************************************
            // get the Service Principals
            //*********************************************************************
            filter.Top         = 999;
            filter.QueryFilter = null;
            PagedResults <ServicePrincipal> servicePrincipals = new PagedResults <ServicePrincipal>();

            do
            {
                servicePrincipals = graphConnection.List <ServicePrincipal>(servicePrincipals.PageToken, filter);
                if (servicePrincipals != null)
                {
                    foreach (ServicePrincipal servicePrincipal in servicePrincipals.Results)
                    {
                        Console.WriteLine("Service Principal AppId: {0}  Name: {1}", servicePrincipal.AppId, servicePrincipal.DisplayName);
                    }
                }
            } while (servicePrincipals.PageToken != null);

            //*********************************************************************
            // get the  Application objects
            //*********************************************************************
            filter.Top = 999;
            PagedResults <Application> applications = new PagedResults <Application>();

            do
            {
                applications = graphConnection.List <Application>(applications.PageToken, filter);
                if (applications != null)
                {
                    foreach (Application application in applications.Results)
                    {
                        Console.WriteLine("Application AppId: {0}  Name: {1}", application.AppId, application.DisplayName);
                    }
                }
            }while (applications.PageToken != null);

            string targetAppId = applications.Results[0].ObjectId;


            //********************************************************************************************
            //  We'll now switch to Authenticating using OAuth Authorization Code Grant
            //  which includes user Authentication/Delegation
            //*********************************************************************************************
            var    redirectUri                   = new Uri("https://localhost");
            string clientIdForUserAuthn          = "66133929-66a4-4edc-aaee-13b04b03207d";
            AuthenticationResult userAuthnResult = null;

            try
            {
                userAuthnResult = authenticationContext.AcquireToken(resource, clientIdForUserAuthn, redirectUri, PromptBehavior.Always);
                token           = userAuthnResult.AccessToken;
                Console.WriteLine("\n Welcome " + userAuthnResult.UserInfo.GivenName + " " + userAuthnResult.UserInfo.FamilyName);
            }
            catch (AuthenticationException ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "InnerException : " + ex.InnerException.Message;
                }
                Console.WriteLine(message);
                Console.ReadKey();
                return;
            }

            // re-establish Graph connection using the new token
            graphConnection = new GraphConnection(token, ClientRequestId, graphSettings);

            //*********************************************************************************************
            // Create a new User with a temp password
            //*********************************************************************************************
            User userToBeAdded = new User();

            userToBeAdded.DisplayName              = "Sample App Demo User";
            userToBeAdded.UserPrincipalName        = "SampleAppDemoUser@" + defaultDomain.Name;
            userToBeAdded.AccountEnabled           = true;
            userToBeAdded.MailNickname             = "SampleAppDemoUser";
            userToBeAdded.PasswordProfile          = new PasswordProfile();
            userToBeAdded.PasswordProfile.Password = "******";
            userToBeAdded.PasswordProfile.ForceChangePasswordNextLogin = true;
            userToBeAdded.UsageLocation = "US";
            User newlyCreatedUser = new User();

            try
            {
                newlyCreatedUser = graphConnection.Add <User>(userToBeAdded);
                Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName);
            }
            catch (GraphException graphException)
            {
                Console.WriteLine("\nError creating new user {0} {1}", graphException.Code, graphException.Message);
            }

            //*********************************************************************************************
            // update the newly created user's Password, PasswordPolicies and City
            //*********************************************************************************************
            if (newlyCreatedUser.ObjectId != null)
            {
                string userObjectId = newlyCreatedUser.ObjectId;

                // update User's city and reset their User's password
                User updateUser = graphConnection.Get <User>(userObjectId);
                updateUser.City = "Seattle";
                PasswordProfile passwordProfile = new PasswordProfile();
                passwordProfile.Password = "******";
                passwordProfile.ForceChangePasswordNextLogin = false;
                updateUser.PasswordProfile  = passwordProfile;
                updateUser.PasswordPolicies = "DisablePasswordExpiration, DisableStrongPassword";
                try
                {
                    graphConnection.Update(updateUser);
                    Console.WriteLine("\nUser {0} was updated", updateUser.DisplayName);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("\nError Updating the user {0} {1}", graphException.Code, graphException.Message);
                }


                //*********************************************************************************************
                // Add, then retrieve a thumbnailPhoto for the newly created user
                //*********************************************************************************************
                Bitmap thumbnailPhoto = new Bitmap(20, 20);
                thumbnailPhoto.SetPixel(5, 5, Color.Beige);
                thumbnailPhoto.SetPixel(5, 6, Color.Beige);
                thumbnailPhoto.SetPixel(6, 5, Color.Beige);
                thumbnailPhoto.SetPixel(6, 6, Color.Beige);

                using (MemoryStream ms = new MemoryStream())
                {
                    thumbnailPhoto.Save(ms, ImageFormat.Jpeg);
                    graphConnection.SetStreamProperty(newlyCreatedUser, GraphProperty.ThumbnailPhoto, ms, "image/jpeg");
                    //  graphConnection.SetStreamProperty(newlyCreatedUser, "thumbnailPhoto", ms, "image/jpeg");
                }

                using (Stream ms = graphConnection.GetStreamProperty(newlyCreatedUser, GraphProperty.ThumbnailPhoto, "image/jpeg"))
                {
                    Image jpegImage = Image.FromStream(ms);
                }



                //*********************************************************************************************
                // User License Assignment - assign EnterprisePack license to new user, and disable SharePoint service
                //   first get a list of Tenant's subscriptions and find the "Enterprisepack" one
                //   Enterprise Pack includes service Plans for ExchangeOnline, SharePointOnline and LyncOnline
                //   validate that Subscription is Enabled and there are enough units left to assign to users
                //*********************************************************************************************
                PagedResults <SubscribedSku> skus = graphConnection.List <SubscribedSku>(null, null);
                foreach (SubscribedSku sku in skus.Results)
                {
                    if (sku.SkuPartNumber == "ENTERPRISEPACK")
                    {
                        if ((sku.PrepaidUnits.Enabled.Value > sku.ConsumedUnits) && (sku.CapabilityStatus == "Enabled"))
                        {
                            // create addLicense object and assign the Enterprise Sku GUID to the skuId
                            //
                            AssignedLicense addLicense = new AssignedLicense();
                            addLicense.SkuId = sku.SkuId.Value;

                            // find plan id of SharePoint Service Plan
                            foreach (ServicePlanInfo servicePlan in sku.ServicePlans)
                            {
                                if (servicePlan.ServicePlanName.Contains("SHAREPOINT"))
                                {
                                    addLicense.DisabledPlans.Add(servicePlan.ServicePlanId.Value);
                                    break;
                                }
                            }

                            IList <AssignedLicense> licensesToAdd    = new AssignedLicense[] { addLicense };
                            IList <Guid>            licensesToRemove = new Guid[] { };

                            // attempt to assign the license object to the new user
                            try
                            {
                                graphConnection.AssignLicense(newlyCreatedUser, licensesToAdd, licensesToRemove);
                                Console.WriteLine("\n User {0} was assigned license {1}", newlyCreatedUser.DisplayName, addLicense.SkuId);
                            }
                            catch (GraphException graphException)
                            {
                                Console.WriteLine("\nLicense assingment failed {0} {1}", graphException.Code, graphException.Message);
                            }
                        }
                    }
                }

                //*********************************************************************************************
                // Add User to the "WA" Group
                //*********************************************************************************************
                if (retrievedGroup.ObjectId != null)
                {
                    try
                    {
                        graphConnection.AddLink(retrievedGroup, newlyCreatedUser, LinkProperty.Members);
                        Console.WriteLine("\nUser {0} was added to Group {1}", newlyCreatedUser.DisplayName, retrievedGroup.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("\nAdding user to group failed {0} {1}", graphException.Code, graphException.Message);
                    }
                }

                //*********************************************************************************************
                // Create a new Group
                //*********************************************************************************************
                Group CaliforniaEmployees = new Group();
                CaliforniaEmployees.DisplayName     = "California Employees";
                CaliforniaEmployees.Description     = "Employees in the state of California";
                CaliforniaEmployees.MailNickname    = "CalEmployees";
                CaliforniaEmployees.MailEnabled     = false;
                CaliforniaEmployees.SecurityEnabled = true;
                Group newGroup = null;
                try
                {
                    newGroup = graphConnection.Add <Group>(CaliforniaEmployees);
                    Console.WriteLine("\nNew Group {0} was created", newGroup.DisplayName);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("\nError creating new Group {0} {1}", graphException.Code, graphException.Message);
                }

                //*********************************************************************************************
                // Add the new User member to the new Group
                //*********************************************************************************************
                if (newGroup.ObjectId != null)
                {
                    try
                    {
                        graphConnection.AddLink(newGroup, newlyCreatedUser, LinkProperty.Members);
                        Console.WriteLine("\nUser {0} was added to Group {1}", newlyCreatedUser.DisplayName, newGroup.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("\nAdding user to group failed {0} {1}", graphException.Code, graphException.Message);
                    }
                }


                //*********************************************************************************************
                // Delete the user that we just created
                //*********************************************************************************************
                if (newlyCreatedUser.ObjectId != null)
                {
                    try
                    {
                        graphConnection.Delete(newlyCreatedUser);
                        Console.WriteLine("\nUser {0} was deleted", newlyCreatedUser.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Deleting User failed {0} {1}", graphException.Code, graphException.Message);
                    }
                }

                //*********************************************************************************************
                // Delete the Group that we just created
                //*********************************************************************************************
                if (newGroup.ObjectId != null)
                {
                    try
                    {
                        graphConnection.Delete(newGroup);
                        Console.WriteLine("\nGroup {0} was deleted", newGroup.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Deleting Group failed: {0} {1}", graphException.Code, graphException.Message);
                    }
                }
            }

            //*********************************************************************************************
            // Get a list of Mobile Devices from tenant
            //*********************************************************************************************
            Console.WriteLine("\nGetting Devices");
            FilterGenerator deviceFilter = new FilterGenerator();

            deviceFilter.Top = 999;
            PagedResults <Device> devices = graphConnection.List <Device>(null, deviceFilter);

            foreach (Device device in devices.Results)
            {
                if (device.ObjectId != null)
                {
                    Console.WriteLine("Device ID: {0}, Type: {1}", device.DeviceId, device.DeviceOSType);
                    foreach (GraphObject owner in device.RegisteredOwners)
                    {
                        Console.WriteLine("Device Owner ID: " + owner.ObjectId);
                    }
                }
            }

            //*********************************************************************************************
            // Create a new Application object
            //*********************************************************************************************
            Application appObject = new Application();

            appObject.DisplayName = "Test-Demo App";
            appObject.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid().ToString());
            appObject.ReplyUrls.Add("https://localhost/demo");

            // created Keycredential object for the new App object
            KeyCredential KeyCredential = new KeyCredential();

            KeyCredential.StartDate = DateTime.UtcNow;
            KeyCredential.EndDate   = DateTime.UtcNow.AddYears(1);
            KeyCredential.Type      = "Symmetric";
            KeyCredential.Value     = Convert.FromBase64String("g/TMLuxgzurjQ0Sal9wFEzpaX/sI0vBP3IBUE/H/NS4=");
            KeyCredential.Usage     = "Verify";
            appObject.KeyCredentials.Add(KeyCredential);

            GraphObject newApp = null;

            try
            {
                newApp = graphConnection.Add(appObject);
                Console.WriteLine("New Application created: " + newApp.ObjectId);
            }
            catch (GraphException graphException)
            {
                Console.WriteLine("Application Creation execption: {0} {1}", graphException.Code, graphException.Message);
            }

            // Get the application object that was just created
            if (newApp != null)
            {
                GraphObject app          = graphConnection.Get(typeof(Application), newApp.ObjectId);
                Application retrievedApp = (Application)app;

                //*********************************************************************************************
                // create a new Service principal
                //*********************************************************************************************
                ServicePrincipal newServicePrincpal = new ServicePrincipal();
                newServicePrincpal.DisplayName    = "Test-Demo App";
                newServicePrincpal.AccountEnabled = true;
                newServicePrincpal.AppId          = retrievedApp.AppId;

                GraphObject newSP = null;
                try
                {
                    newSP = graphConnection.Add <ServicePrincipal>(newServicePrincpal);
                    //    newSP = graphConnection.Add(newServicePrincpal);
                    Console.WriteLine("New Service Principal created: " + newSP.ObjectId);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("Service Principal Creation execption: {0} {1}", graphException.Code, graphException.Message);
                }


                //*********************************************************************************************
                // get all Permission Objects
                //*********************************************************************************************
                Console.WriteLine("\n Getting Permissions");
                filter.Top = 999;
                PagedResults <Permission> permissions = new PagedResults <Permission>();
                do
                {
                    try
                    {
                        permissions = graphConnection.List <Permission>(permissions.PageToken, filter);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Error: {0} {1}", graphException.Code, graphException.Message);
                        break;
                    }

                    foreach (Permission permission in permissions.Results)
                    {
                        Console.WriteLine("Permission: {0}  Name: {1}", permission.ClientId, permission.Scope);
                    }
                } while (permissions.PageToken != null);

                //*********************************************************************************************
                // Create new permission object
                //*********************************************************************************************
                Permission permissionObject = new Permission();
                permissionObject.ConsentType = "AllPrincipals";
                permissionObject.Scope       = "user_impersonation";
                permissionObject.StartTime   = DateTime.Now;
                permissionObject.ExpiryTime  = (DateTime.Now).AddMonths(12);

                // resourceId is objectId of the resource, in this case objectId of AzureAd (Graph API)
                permissionObject.ResourceId = "dbf73c3e-e80b-495b-a82f-2f772bb0a417";

                //ClientId = objectId of servicePrincipal
                permissionObject.ClientId = newSP.ObjectId;

                GraphObject newPermission = null;
                try
                {
                    newPermission = graphConnection.Add(permissionObject);
                    Console.WriteLine("New Permission object created: " + newPermission.ObjectId);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("Permission Creation exception: {0} {1}", graphException.Code, graphException.Message);
                }

                //*********************************************************************************************
                // Delete Application Objects
                //*********************************************************************************************

                if (retrievedApp.ObjectId != null)
                {
                    try
                    {
                        graphConnection.Delete(retrievedApp);
                        Console.WriteLine("Deleting Application object: " + retrievedApp.ObjectId);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Application Deletion execption: {0} {1}", graphException.Code, graphException.Message);
                    }
                }
            }

            //*********************************************************************************************
            // Show Batching with 3 operators.  Note: up to 5 operations can be in a batch
            //*********************************************************************************************
            // get users
            Console.WriteLine("\n Executing Batch Request");
            BatchRequestItem firstItem = new BatchRequestItem(
                "GET",
                false,
                Utils.GetListUri <User>(graphConnection, null, new FilterGenerator()),
                null,
                String.Empty);

            // get members of a Group
            Uri membersUri = Utils.GetRequestUri <Group>(graphConnection, retrievedGroup.ObjectId, "members");

            BatchRequestItem secondItem = new BatchRequestItem(
                "GET",
                false,
                new Uri(membersUri.ToString()),
                null,
                String.Empty);

            // update an existing group's Description property

            retrievedGroup.Description = "New Employees in Washington State";

            BatchRequestItem thirdItem = new BatchRequestItem(
                "Patch",
                true,
                Utils.GetRequestUri <Group>(graphConnection, retrievedGroup.ObjectId),
                null,
                retrievedGroup.ToJson(true));

            // Execute the batch requst
            IList <BatchRequestItem>  batchRequest   = new BatchRequestItem[] { firstItem, secondItem, thirdItem };
            IList <BatchResponseItem> batchResponses = graphConnection.ExecuteBatch(batchRequest);

            int responseCount = 0;

            foreach (BatchResponseItem responseItem in batchResponses)
            {
                if (responseItem.Failed)
                {
                    Console.WriteLine("Failed: {0} {1}",
                                      responseItem.Exception.Code,
                                      responseItem.Exception.ErrorMessage);
                }
                else
                {
                    Console.WriteLine("Batch Item Result {0} succeeded {1}",
                                      responseCount++,
                                      !responseItem.Failed);
                }
            }

            // this next section shows how to access the signed-in user's mailbox.
            // First we get a new token for Office365 Exchange Online Resource
            // using the multi-resource refresh token tha was included when the previoius
            // token was acquired.
            // We can now request a new token for Office365 Exchange Online.
            //
            string office365Emailresource = "https://outlook.office365.com/";
            string office365Token         = null;

            if (userAuthnResult.IsMultipleResourceRefreshToken)
            {
                userAuthnResult = authenticationContext.AcquireTokenByRefreshToken(userAuthnResult.RefreshToken, clientIdForUserAuthn, office365Emailresource);
                office365Token  = userAuthnResult.AccessToken;

                //
                // Call the Office365 API and retrieve the top item from the user's mailbox.
                //
                string     requestUrl = "https://outlook.office365.com/EWS/OData/Me/Inbox/Messages?$top=1";
                WebRequest getMailboxRequest;
                getMailboxRequest = WebRequest.Create(requestUrl);
                getMailboxRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + office365Token);
                Console.WriteLine("\n Getting the User's Mailbox Contents \n");

                //
                // Read the contents of the user's mailbox, and display to the console.
                //
                Stream objStream = null;
                try
                {
                    objStream = getMailboxRequest.GetResponse().GetResponseStream();
                    StreamReader objReader = new StreamReader(objStream);

                    string sLine = "";
                    int    i     = 0;

                    while (sLine != null)
                    {
                        i++;
                        sLine = objReader.ReadLine();
                        if (sLine != null)
                        {
                            Console.WriteLine("{0}:{1}", i, sLine);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\n Error Getting User's Mailbox: {0} \n", ex.Message);
                }
            }

            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************
            Console.WriteLine("\nCompleted at {0} \n ClientRequestId: {1}", CurrentDateTime, ClientRequestId);
            Console.ReadKey();
            return;
        }
Exemplo n.º 16
0
        public ActionResult Edit([Bind(Include = "ObjectId,UserPrincipalName,DisplayName,AccountEnabled,GivenName,Surname,JobTitle,Department,Mobile,StreetAddress,City,State,Country,")] User user, FormCollection values)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and update single User
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);
                graphConnection.Update(user);

                // update thumbnail photo
                if (!String.IsNullOrEmpty(values["photofile"]))
                {
                    //string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
                    //string filename = Path.GetFileName(values["photofile"]);
                    //Image image = Image.FromFile(filename);

                    var   imageFile = Path.Combine(Server.MapPath("~/app_data"), values["photofile"]);
                    Image image     = Image.FromFile(imageFile);

                    MemoryStream stream = new MemoryStream();
                    image.Save(stream, ImageFormat.Jpeg);

                    // Write the photo file to the Graph service.
                    graphConnection.SetStreamProperty(user, GraphProperty.ThumbnailPhoto, stream, "image/jpeg");
                }


                return(RedirectToAction("Index"));
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Generates XAML for the markdown element.
        /// </summary>
        /// <param name="Output">XAML will be output here.</param>
        /// <param name="Settings">XAML settings.</param>
        /// <param name="TextAlignment">Alignment of text in element.</param>
        public override void GenerateXAML(XmlWriter Output, XamlSettings Settings, TextAlignment TextAlignment)
        {
            object Result = this.EvaluateExpression();

            if (Result == null)
            {
                return;
            }

            Graph   G = Result as Graph;
            SKImage Img;
            string  s;

            if (G != null)
            {
                GraphSettings GraphSettings = new GraphSettings();
                object        Obj;
                double        d;

                if (this.variables.TryGetVariable("GraphWidth", out Variable v) && (Obj = v.ValueObject) is double && (d = (double)Obj) >= 1)
                {
                    GraphSettings.Width       = (int)Math.Round(d);
                    GraphSettings.MarginLeft  = (int)Math.Round(15 * d / 640);
                    GraphSettings.MarginRight = GraphSettings.MarginLeft;
                }
                else if (!this.variables.ContainsVariable("GraphWidth"))
                {
                    this.variables["GraphWidth"] = (double)Settings.DefaultGraphWidth;
                    GraphSettings.MarginLeft     = (int)Math.Round(15.0 * Settings.DefaultGraphWidth / 640);
                    GraphSettings.MarginRight    = GraphSettings.MarginLeft;
                }

                if (this.variables.TryGetVariable("GraphHeight", out v) && (Obj = v.ValueObject) is double && (d = (double)Obj) >= 1)
                {
                    GraphSettings.Height        = (int)Math.Round(d);
                    GraphSettings.MarginTop     = (int)Math.Round(15 * d / 480);
                    GraphSettings.MarginBottom  = GraphSettings.MarginTop;
                    GraphSettings.LabelFontSize = 12 * d / 480;
                }
                else if (!this.variables.ContainsVariable("GraphHeight"))
                {
                    this.variables["GraphHeight"] = (double)Settings.DefaultGraphHeight;
                    GraphSettings.MarginTop       = (int)Math.Round(15.0 * Settings.DefaultGraphHeight / 480);
                    GraphSettings.MarginBottom    = GraphSettings.MarginTop;
                }

                using (SKImage Bmp = G.CreateBitmap(GraphSettings))
                {
                    SKData Data = Bmp.Encode(SKEncodedImageFormat.Png, 100);
                    byte[] Bin  = Data.ToArray();

                    s = "data:image/png;base64," + System.Convert.ToBase64String(Bin, 0, Bin.Length);

                    // TODO: WPF does not support data URI scheme. Change to local temporary file.

                    Output.WriteStartElement("Image");
                    Output.WriteAttributeString("Source", s);
                    Output.WriteAttributeString("Width", Bmp.Width.ToString());
                    Output.WriteAttributeString("Height", Bmp.Height.ToString());
                    Output.WriteEndElement();

                    Data.Dispose();
                }
            }
            else if ((Img = Result as SKImage) != null)
            {
                using (SKData Data = Img.Encode(SKEncodedImageFormat.Png, 100))
                {
                    byte[] Bin = Data.ToArray();

                    s = "data:image/png;base64," + System.Convert.ToBase64String(Bin, 0, Bin.Length);

                    // TODO: WPF does not support data URI scheme. Change to local temporary file.

                    Output.WriteStartElement("Image");
                    Output.WriteAttributeString("Source", s);
                    Output.WriteAttributeString("Width", Img.Width.ToString());
                    Output.WriteAttributeString("Height", Img.Height.ToString());
                    Output.WriteEndElement();
                }
            }
            else if (Result is Exception ex)
            {
                ex = Log.UnnestException(ex);

                if (ex is AggregateException ex2)
                {
                    foreach (Exception ex3 in ex2.InnerExceptions)
                    {
                        Output.WriteStartElement("TextBlock");
                        Output.WriteAttributeString("TextWrapping", "Wrap");
                        Output.WriteAttributeString("Margin", Settings.ParagraphMargins);

                        if (TextAlignment != TextAlignment.Left)
                        {
                            Output.WriteAttributeString("TextAlignment", TextAlignment.ToString());
                        }

                        Output.WriteAttributeString("Foreground", "Red");
                        Output.WriteValue(ex.Message);
                        Output.WriteEndElement();
                    }
                }
                else
                {
                    if (this.aloneInParagraph)
                    {
                        Output.WriteStartElement("TextBlock");
                        Output.WriteAttributeString("TextWrapping", "Wrap");
                        Output.WriteAttributeString("Margin", Settings.ParagraphMargins);
                        if (TextAlignment != TextAlignment.Left)
                        {
                            Output.WriteAttributeString("TextAlignment", TextAlignment.ToString());
                        }
                    }
                    else
                    {
                        Output.WriteStartElement("Run");
                    }

                    Output.WriteAttributeString("Foreground", "Red");
                    Output.WriteValue(ex.Message);
                    Output.WriteEndElement();
                }
            }
            else
            {
                if (this.aloneInParagraph)
                {
                    Output.WriteStartElement("TextBlock");
                    Output.WriteAttributeString("TextWrapping", "Wrap");
                    Output.WriteAttributeString("Margin", Settings.ParagraphMargins);
                    if (TextAlignment != TextAlignment.Left)
                    {
                        Output.WriteAttributeString("TextAlignment", TextAlignment.ToString());
                    }
                }

                Output.WriteValue(Result.ToString());

                if (this.aloneInParagraph)
                {
                    Output.WriteEndElement();
                }
            }
        }
Exemplo n.º 18
0
        public void SaveSettings()
        {
            graphSettings.AxesRange = graph.AxesRange;

            GraphSettings.SaveToFile(GraphSettingsFilePath, graphSettings);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Generates HTML for the markdown element.
        /// </summary>
        /// <param name="Output">HTML will be output here.</param>
        public override void GenerateHTML(StringBuilder Output)
        {
            object Result = this.EvaluateExpression();

            if (Result == null)
            {
                return;
            }

            string s;

            Graph   G = Result as Graph;
            SKImage Img;

            if (G != null)
            {
                GraphSettings GraphSettings = new GraphSettings();
                object        Obj;
                double        d;

                if (this.variables.TryGetVariable("GraphWidth", out Variable v) && (Obj = v.ValueObject) is double && (d = (double)Obj) >= 1)
                {
                    GraphSettings.Width       = (int)Math.Round(d);
                    GraphSettings.MarginLeft  = (int)Math.Round(15 * d / 640);
                    GraphSettings.MarginRight = GraphSettings.MarginLeft;
                }
                else if (!this.variables.ContainsVariable("GraphWidth"))
                {
                    this.variables["GraphWidth"] = (double)GraphSettings.Width;
                }


                if (this.variables.TryGetVariable("GraphHeight", out v) && (Obj = v.ValueObject) is double && (d = (double)Obj) >= 1)
                {
                    GraphSettings.Height        = (int)Math.Round(d);
                    GraphSettings.MarginTop     = (int)Math.Round(15 * d / 480);
                    GraphSettings.MarginBottom  = GraphSettings.MarginTop;
                    GraphSettings.LabelFontSize = 12 * d / 480;
                }
                else if (!this.variables.ContainsVariable("GraphHeight"))
                {
                    this.variables["GraphHeight"] = (double)GraphSettings.Height;
                }

                using (SKImage Bmp = G.CreateBitmap(GraphSettings))
                {
                    SKData Data = Bmp.Encode(SKEncodedImageFormat.Png, 100);
                    byte[] Bin  = Data.ToArray();

                    s = System.Convert.ToBase64String(Bin, 0, Bin.Length);
                    s = "<img border=\"2\" width=\"" + GraphSettings.Width.ToString() + "\" height=\"" + GraphSettings.Height.ToString() +
                        "\" src=\"data:image/png;base64," + s + "\" />";

                    if (this.aloneInParagraph)
                    {
                        s = "<figure>" + s + "</figure>";
                    }

                    Data.Dispose();
                }
            }
            else if ((Img = Result as SKImage) != null)
            {
                using (SKData Data = Img.Encode(SKEncodedImageFormat.Png, 100))
                {
                    byte[] Bin = Data.ToArray();

                    s = System.Convert.ToBase64String(Bin, 0, Bin.Length);
                    s = "<img border=\"2\" width=\"" + Img.Width.ToString() + "\" height=\"" + Img.Height.ToString() +
                        "\" src=\"data:image/png;base64," + s + "\" />";

                    if (this.aloneInParagraph)
                    {
                        s = "<figure>" + s + "</figure>";
                    }
                }
            }
            else if (Result is Exception ex)
            {
                ex = Log.UnnestException(ex);

                if (ex is AggregateException ex2)
                {
                    StringBuilder sb = new StringBuilder();

                    foreach (Exception ex3 in ex2.InnerExceptions)
                    {
                        sb.Append("<p><font style=\"color:red\">");
                        sb.Append(XML.HtmlValueEncode(ex3.Message));
                        sb.AppendLine("</font></p>");
                    }

                    s = sb.ToString();
                }
                else
                {
                    s = "<font style=\"color:red\">" + XML.HtmlValueEncode(ex.Message) + "</font>";

                    if (this.aloneInParagraph)
                    {
                        s = "<p>" + s + "</p>";
                    }
                }
            }
            else
            {
                s = XML.HtmlValueEncode(Result.ToString());

                if (this.aloneInParagraph)
                {
                    s = "<p>" + s + "</p>";
                }
            }

            Output.Append(s);

            if (this.aloneInParagraph)
            {
                Output.AppendLine();
            }
        }
Exemplo n.º 20
0
 public RexProClient(string host, int port, GraphSettings settings)
 {
     this.host     = host;
     this.port     = port;
     this.Settings = settings;
 }
Exemplo n.º 21
0
    // Draw the graph and returns the selected Node if there's any.
    private void DrawGraph(IGraphLayout graphLayout, Rect drawingArea, GraphSettings graphSettings)
    {
        // add border, except on right-hand side where the legend will provide necessary padding
        drawingArea = new Rect(drawingArea.x + s_BorderSize,
                               drawingArea.y + s_BorderSize,
                               drawingArea.width - s_BorderSize * 2,
                               drawingArea.height - s_BorderSize * 2);

        var b = new Bounds(Vector3.zero, Vector3.zero);

        foreach (Vertex v in graphLayout.vertices)
        {
            b.Encapsulate(new Vector3(v.position.x, v.position.y, 0.0f));
        }

        // Increase b by maximum node size (since b is measured between node centers)
        b.Expand(new Vector3(graphSettings.maximumNormalizedNodeSize, graphSettings.maximumNormalizedNodeSize, 0));

        var scale  = new Vector2(drawingArea.width / b.size.x, drawingArea.height / b.size.y);
        var offset = new Vector2(-b.min.x, -b.min.y);

        Vector2 nodeSize = ComputeNodeSize(scale, graphSettings);

        GUI.BeginGroup(drawingArea);

        foreach (var e in graphLayout.edges)
        {
            Vector2 v0   = ScaleVertex(e.source.position, offset, scale);
            Vector2 v1   = ScaleVertex(e.destination.position, offset, scale);
            Node    node = e.source.node;

            if (graphLayout.leftToRight)
            {
                DrawEdge(v1, v0, node.weight);
            }
            else
            {
                DrawEdge(v0, v1, node.weight);
            }
        }

        Event currentEvent = Event.current;

        bool oldSelectionFound = false;
        Node newSelectedNode   = null;

        foreach (Vertex v in graphLayout.vertices)
        {
            Vector2 nodeCenter = ScaleVertex(v.position, offset, scale) - nodeSize / 2;
            var     nodeRect   = new Rect(nodeCenter.x, nodeCenter.y, nodeSize.x, nodeSize.y);

            bool clicked = false;
            if (currentEvent.type == EventType.MouseUp && currentEvent.button == 0)
            {
                Vector2 mousePos = currentEvent.mousePosition;
                if (nodeRect.Contains(mousePos))
                {
                    clicked = true;
                    currentEvent.Use();
                }
            }

            bool currentSelection = (m_SelectedNode != null) &&
                                    v.node.content.Equals(m_SelectedNode.content); // Make sure to use Equals() and not == to call any overriden comparison operator in the content type.

            DrawNode(nodeRect, v.node, currentSelection || clicked);

            if (currentSelection)
            {
                // Previous selection still there.
                oldSelectionFound = true;
            }
            else if (clicked)
            {
                // Just Selected a new node.
                newSelectedNode = v.node;
            }
        }

        if (newSelectedNode != null)
        {
            m_SelectedNode = newSelectedNode;
        }
        else if (!oldSelectionFound)
        {
            m_SelectedNode = null;
        }

        GUI.EndGroup();
    }
Exemplo n.º 22
0
        private void ExecuteButton_Click(object sender, RoutedEventArgs e)
        {
            Expression Exp;
            TextBlock  ScriptBlock;

            try
            {
                Exp = new Expression(this.Input.Text);

                ScriptBlock = new TextBlock()
                {
                    Text         = this.Input.Text,
                    FontFamily   = new FontFamily("Courier New"),
                    TextWrapping = TextWrapping.Wrap
                };

                ScriptBlock.PreviewMouseDown += TextBlock_PreviewMouseDown;

                this.HistoryPanel.Children.Add(ScriptBlock);
                this.HistoryScrollViewer.ScrollToBottom();

                this.Input.Text = string.Empty;
                this.Input.Focus();
            }
            catch (Exception ex)
            {
                ex = Log.UnnestException(ex);
                MessageBox.Show(this, ex.Message, "Unable to parse script.", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            Task.Run(() =>
            {
                try
                {
                    IElement Ans;

                    try
                    {
                        Ans = Exp.Root.Evaluate(this.variables);
                    }
                    catch (ScriptReturnValueException ex)
                    {
                        Ans = ex.ReturnValue;
                    }
                    catch (Exception ex)
                    {
                        Ans = new ObjectValue(ex);
                    }

                    this.variables["Ans"] = Ans;

                    this.Dispatcher.Invoke(() =>
                    {
                        Graph G = Ans as Graph;
                        SKImage Img;
                        object Obj;

                        if (G != null)
                        {
                            GraphSettings Settings = new GraphSettings();
                            Tuple <int, int> Size;
                            double d;

                            if ((Size = G.RecommendedBitmapSize) != null)
                            {
                                Settings.Width  = Size.Item1;
                                Settings.Height = Size.Item2;

                                Settings.MarginLeft  = (int)Math.Round(15.0 * Settings.Width / 640);
                                Settings.MarginRight = Settings.MarginLeft;

                                Settings.MarginTop     = (int)Math.Round(15.0 * Settings.Height / 480);
                                Settings.MarginBottom  = Settings.MarginTop;
                                Settings.LabelFontSize = 12.0 * Settings.Height / 480;
                            }
                            else
                            {
                                if (this.variables.TryGetVariable("GraphWidth", out Variable v) && (Obj = v.ValueObject) is double && (d = (double)Obj) >= 1)
                                {
                                    Settings.Width       = (int)Math.Round(d);
                                    Settings.MarginLeft  = (int)Math.Round(15 * d / 640);
                                    Settings.MarginRight = Settings.MarginLeft;
                                }
                                else if (!this.variables.ContainsVariable("GraphWidth"))
                                {
                                    this.variables["GraphWidth"] = (double)Settings.Width;
                                }

                                if (this.variables.TryGetVariable("GraphHeight", out v) && (Obj = v.ValueObject) is double && (d = (double)Obj) >= 1)
                                {
                                    Settings.Height        = (int)Math.Round(d);
                                    Settings.MarginTop     = (int)Math.Round(15 * d / 480);
                                    Settings.MarginBottom  = Settings.MarginTop;
                                    Settings.LabelFontSize = 12 * d / 480;
                                }
                                else if (!this.variables.ContainsVariable("GraphHeight"))
                                {
                                    this.variables["GraphHeight"] = (double)Settings.Height;
                                }
                            }

                            using (SKImage Bmp = G.CreateBitmap(Settings, out object[] States))
                            {
                                this.AddImageBlock(ScriptBlock, Bmp);
                            }
                        }
                        else if ((Img = Ans.AssociatedObjectValue as SKImage) != null)
                        {
                            this.AddImageBlock(ScriptBlock, Img);
                        }
                        else if (Ans.AssociatedObjectValue is Exception ex)
                        {
                            AggregateException ex2;

                            ex = Log.UnnestException(ex);

                            if ((ex2 = ex as AggregateException) != null)
                            {
                                foreach (Exception ex3 in ex2.InnerExceptions)
                                {
                                    ScriptBlock = this.AddTextBlock(ScriptBlock, ex3.Message, Colors.Red);
                                }
                            }
                            else
                            {
                                this.AddTextBlock(ScriptBlock, ex.Message, Colors.Red);
                            }
                        }
                        else
                        {
                            this.AddTextBlock(ScriptBlock, Ans.ToString(), Colors.Red);
                        }
                    });
                }
Exemplo n.º 23
0
 public GnomGraph(GraphSettings settings) : base(settings)
 {
 }
Exemplo n.º 24
0
        static DefaultGraphSettings()
        {
            const float lowSpeedTimespan  = 60;
            const float highSpeedTimespan = 10;

            uint graphSampleBufferSize = GetGraphSampleBufferSize();

            #region Define Default Configurations

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Messages Per Second",
                    YAxisLabel             = "Messages per second",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Messages Per Second", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Gyroscope",
                    YAxisLabel             = "Angular velocity (°/s)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.White, Name = "Magnitude", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Accelerometer",
                    YAxisLabel             = "Acceleration (g)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.White, Name = "Magnitude", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Magnetometer",
                    YAxisLabel             = "Intensity (uT)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    ShowLegend             = true,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.White, Name = "Magnitude", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Barometer",
                    YAxisLabel             = "Pressure (hPa)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Barometer", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Euler Angles",
                    YAxisLabel             = "Angle (°)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Red, Name = "Roll", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Green, Name = "Pitch", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "Yaw", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Linear Acceleration",
                    YAxisLabel             = "Acceleration (g)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Earth Acceleration",
                    YAxisLabel             = "Acceleration (g)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Altimeter",
                    YAxisLabel             = "Altitude (m)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Altitude", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Temperature",
                    YAxisLabel             = "Temperature (°C)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "Gyroscope And Accelerometer", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Cyan, Name = "Environmental Sensor", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Humidity",
                    YAxisLabel             = "Humidity (%)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Humidity", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Battery Percentage",
                    YAxisLabel             = "Percentage (%)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Battery Percentage", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Battery Time To Empty",
                    YAxisLabel             = "Time (minutes)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Battery Time To Empty", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Battery Voltage",
                    YAxisLabel             = "Voltage (V)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Battery Voltage", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Battery Current",
                    YAxisLabel             = "Current (mA)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Battery Current", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Analogue Inputs",
                    YAxisLabel             = "Voltage (V)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Red, Name = "1", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Green, Name = "2", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Blue, Name = "3", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Cyan, Name = "4", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "5", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Magenta, Name = "6", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Orange, Name = "7", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.White, Name = "8", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "RSSI Power",
                    YAxisLabel             = "Power (dBm)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Power", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "RSSI Percentage",
                    YAxisLabel             = "Percentage (%)",
                    AxesRange              = new AxesRange(0, -1, lowSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Colors.Yellow, Name = "Percentage (%)", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            #endregion Define Default Configurations
        }
Exemplo n.º 25
0
        static DefaultGraphSettings()
        {
            //const float lowSpeedTimespan = 60;
            const float highSpeedTimespan     = 10;
            uint        graphSampleBufferSize = 10000;

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Gyroscope",
                    YAxisLabel             = "Angular velocity (0.1 °/s)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.White, Name = "Magnitude", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Accelerometer",
                    YAxisLabel             = "Acceleration (0.001G)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.White, Name = "Magnitude", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Magnetometer",
                    YAxisLabel             = "Intensity (millGuass)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    ShowLegend             = true,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Red, Name = "X", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Green, Name = "Y", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Blue, Name = "Z", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.White, Name = "Magnitude", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }

            {
                GraphSettings settings = new GraphSettings()
                {
                    Title                  = "Euler Angles",
                    YAxisLabel             = "Angle (°)",
                    AxesRange              = new AxesRange(0, -1, highSpeedTimespan, 1),
                    GraphType              = GraphType.Timestamp,
                    VerticalAutoscaleIndex = int.MaxValue,
                };
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Red, Name = "Roll", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Green, Name = "Pitch", MaxDataPoints = graphSampleBufferSize
                });
                settings.Traces.Add(new Trace()
                {
                    Color = Color.Blue, Name = "Yaw", MaxDataPoints = graphSampleBufferSize
                });

                settings.ShowLegend = settings.Traces.Count > 1;
                graphSettings.Add(settings.Title, settings);
            }
        }
 public ProfileModel(ITokenAcquisition tokenAcquisition, IOptions <GraphSettings> graphSettingsValue)
 {
     this.tokenAcquisition = tokenAcquisition;
     graphSettings         = graphSettingsValue.Value;
 }
Exemplo n.º 27
0
        public static void GetUsersFromAD()
        {
            //if (HttpContext.Current.Cache["ADUSERS"] == null)
            IDatabase cache = MvcApplication.RedisCache.GetDatabase();
            var adUsers = cache.Get<List<ActiveDirectoryUser>>("ADUSERS");
            if (adUsers == null)
            {
                // Graph API Settings
                string graphResourceId = "https://graph.windows.net";
                string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
                string appPassword = ConfigurationManager.AppSettings["ida:Password"];
                Uri audienceUri = new Uri(ConfigurationManager.AppSettings["ida:AudienceUri"]);
                string tenant = audienceUri.Host;
                string Authority = String.Format("https://login.windows.net/{0}", tenant);

                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Authority);
                activeDirectoryUsers = new List<ActiveDirectoryUser>();
                ClientCredential credential = new ClientCredential(clientId, appPassword);
                AuthenticationResult result = null;
                List<User> userList = new List<User>();
                result = authContext.AcquireToken(graphResourceId, credential);

                //Setup Graph API connection and get a list of users 
                Guid ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings = new GraphSettings();
                graphSettings.ApiVersion = "2013-11-08";

                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);
                // Get results from all pages into a list 
                PagedResults<User> pagedResults = graphConnection.List<User>(null, new FilterGenerator());
                userList.AddRange(pagedResults.Results);
                while (!pagedResults.IsLastPage)
                {
                    pagedResults = graphConnection.List<User>(pagedResults.PageToken, new FilterGenerator());
                    userList.AddRange(pagedResults.Results);
                }
                foreach (var u in userList)
                {
                    var adUser = new ActiveDirectoryUser();
                    adUser.Location = String.Format("{0},{1}", u.City, u.State);
                    adUser.FullName = u.GivenName + " " + u.Surname;
                    adUser.Position = u.JobTitle;
                    adUser.ActiveDirectoryId = u.UserPrincipalName;
                    adUser.ObjectId = u.ObjectId;

                    try
                    {
                        using (Stream ms = graphConnection.GetStreamProperty(u, GraphProperty.ThumbnailPhoto, "image/jpeg"))
                        {
                            if (ms != null)
                            {
                                byte[] b;
                                using (BinaryReader br = new BinaryReader(ms))
                                {
                                    b = br.ReadBytes((int)ms.Length);
                                }
                                adUser.ThumbnailPhoto = b;
                                // Retrieve via the controller
                                adUser.ImageUrl = String.Format("/AdImages/Details/{0}", adUser.ObjectId);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        adUser.ImageUrl = "/images/user-placeholder.png";
                    }
                    activeDirectoryUsers.Add(adUser);
                }
                // HttpContext.Current.Cache.Insert("ADUSERS", activeDirectoryUsers, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                cache.Set("ADUSERS", activeDirectoryUsers, TimeSpan.FromMinutes(5));

            }
            else
            {
                //activeDirectoryUsers = (List<ActiveDirectoryUser>)HttpContext.Current.Cache["ADUSERS"];
                activeDirectoryUsers = (List<ActiveDirectoryUser>)cache.Get("ADUSERS");
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Gets a list of <see cref="User"/> objects that are members of a give <see cref="Group"/>.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="Group"/>.</param>
        /// <returns>A view with the list of <see cref="User"/> objects.</returns>
        public ActionResult GetMembers(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;
            IList <User>         users  = new List <User>();

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // Setup Graph API connection and get Group membership
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                Group group = graphConnection.Get <Group>(objectId);
                PagedResults <GraphObject> members = graphConnection.GetLinkedObjects(group, LinkProperty.Members, null, 999);

                // Filter for users
                foreach (GraphObject obj in members.Results)
                {
                    if (obj is User)
                    {
                        users.Add((User)obj);
                    }
                }

                // Perform same filter for all pages
                while (!members.IsLastPage)
                {
                    members = graphConnection.GetLinkedObjects(group, LinkProperty.Members, members.PageToken, 999);
                    foreach (GraphObject obj in members.Results)
                    {
                        if (obj is User)
                        {
                            users.Add((User)obj);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            return(View(users));
        }
 public GraphSDKHelper(GraphSettings _settings)
 {
     settings = _settings;
 }