Beispiel #1
0
 public ImporterTests()
 {
     CoreEntitiesContainer = new CoreEntitiesContainer();
     CoreEntitiesContainer.ContextOptions.LazyLoadingEnabled = false;
     //Admin role on GotGrease?
     _roleId = CoreEntitiesContainer.Roles.First(r => r.OwnerBusinessAccountId == _gotGreaseId && r.RoleTypeInt == (int)RoleType.Administrator).Id;
 }
Beispiel #2
0
        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            CoreEntitiesContainer = new CoreEntitiesContainer();

            var currentBusinessAccount = CurrentBusinessAccount.Get<BusinessAccount>(context);
            QuickBooksTools.GetBaseUrl(currentBusinessAccount, CoreEntitiesContainer);
        }
        public void GetTrackPoints()
        {
            var coreEntitiesContainer = new CoreEntitiesContainer();

            var currentUser = coreEntitiesContainer.CurrentUserAccount();

            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
            //var controller = new TrackPointController { Request = request };

            var date = new DateTime(2012, 4, 16);

            //var response = controller.GetTrackPoints(new Guid("F7349D7F-77AF-4AED-8425-5AF979AC74B9"), date);
        }
        /// <summary>
        /// Return the signature svg of a signature field
        /// </summary>
        /// <param name="id">The id of the signature field</param>
        /// <returns>An image of the signature</returns>
        public string Image(Guid id)
        {
            var coreEntitiesContainer = new CoreEntitiesContainer();
            
            var signatureField = coreEntitiesContainer.Fields.OfType<SignatureField>().FirstOrDefault(sf => sf.Id == id);
            if (signatureField == null) return null;

            //Data must be stored using https://github.com/brinley/jSignature base30 format
            var data = new jSignature.Tools.Base30Converter().GetData(signatureField.Value);
            
            string svg = jSignature.Tools.SVGConverter.ToSVG(data);
            return svg;
        }
Beispiel #5
0
        /// <summary>
        /// Sets the empty recurring service destinations to the RecurringService's client's first location.
        /// </summary>
        private static void SetEmptyDestinations()
        {
            var coreEntitiesContainer = new CoreEntitiesContainer();
            var recurringServicesWithoutLocations = coreEntitiesContainer.RecurringServices
                .Include("Client")
                .Include("ServiceTemplate.Fields")
                .Where(rs => rs.ServiceTemplate.Fields.OfType<LocationField>().All(lf => lf.LocationId == null && lf.LocationFieldTypeInt == (decimal) LocationFieldType.Destination))
                .ToArray();

            foreach (var recurringService in recurringServicesWithoutLocations)
            {
                var locationField = recurringService.ServiceTemplate.Fields.OfType<LocationField>().First();
                locationField.Value = recurringService.Client.Locations.FirstOrDefault();
            }

            coreEntitiesContainer.SaveChanges();
        }
Beispiel #6
0
        /// <summary>
        /// Finds the BaseURL for the current QuickBooks user
        /// </summary>
        /// <param name="currentBusinessAccount">The current business account.</param>
        /// <param name="coreEntitiesContainer">The core entities container.</param>
        public static void GetBaseUrl(BusinessAccount currentBusinessAccount, CoreEntitiesContainer coreEntitiesContainer)
        {
            var quickBooksSession = SerializationTools.Deserialize<QuickBooksSession>(currentBusinessAccount.QuickBooksSessionXml);

            //URL for the QuickBooks Data Service for getting the BaseURL
            var serviceEndPoint = String.Format("https://qbo.intuit.com/qbo1/rest/user/v2/" + quickBooksSession.RealmId);

            var oSession = CreateOAuthSessionAndAccessToken(currentBusinessAccount);

            //Sends and signs the request to the Data Service
            IConsumerRequest conReq = oSession.Request().Get().ForUrl(serviceEndPoint).SignWithToken();

            //OAuth parameters are needed in the header for this call
            conReq.Context.GenerateOAuthParametersForHeader();

            //Reads the response XML
            var responseString = conReq.ReadBody();

            //Splits the response XML into by line
            string[] responseArray = responseString.Split('<');

            //Checks each line for the one containing the BaseURL
            foreach (string s in responseArray)
            {
                if (s.Contains("qbo:BaseURI>"))
                {
                    responseArray = s.Split('>');
                    quickBooksSession.BaseUrl = responseArray[1];
                    break;
                }
            }

            //Ensures that the BaseURL is saved for later use
            currentBusinessAccount.QuickBooksSessionXml = SerializationTools.Serialize(quickBooksSession);
            coreEntitiesContainer.SaveChanges();
        }
Beispiel #7
0
        /// <summary>
        /// Exchanges the request token attained earlier for the access token needed to make calls to QuickBooks
        /// </summary>
        /// <param name="currentBusinessAccount">The current business account.</param>
        /// <param name="coreEntitiesContainer">The current CoreEntitiesContainer</param>
        public static void GetAccessToken(BusinessAccount currentBusinessAccount, CoreEntitiesContainer coreEntitiesContainer)
        {
            //Deserializes QuicBooksSessionXml from the Database to a quickBooksSession Class
            var quickBooksSession = SerializationTools.Deserialize<QuickBooksSession>(currentBusinessAccount.QuickBooksSessionXml);

            //Creates the OAuth Session
            var clientSession = CreateOAuthSession();

            //The AccessToken is attained by exchanging the request token and the OAuthVerifier that we attained earlier
            IToken accessToken = clientSession.ExchangeRequestTokenForAccessToken(quickBooksSession.Token, quickBooksSession.OAuthVerifier);

            //Saving the Token to private storage
            currentBusinessAccount.QuickBooksAccessToken = accessToken.Token;
            currentBusinessAccount.QuickBooksAccessTokenSecret = accessToken.TokenSecret;

            coreEntitiesContainer.SaveChanges();
        }
Beispiel #8
0
 protected BaseApiController()
 {
     CoreEntitiesContainer = new CoreEntitiesContainer();
     CoreEntitiesContainer.ContextOptions.LazyLoadingEnabled = false;
     CoreEntitiesMembershipProvider = new CoreEntitiesMembershipProvider(CoreEntitiesContainer);
 }
        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            var coreEntitiesContainer = new CoreEntitiesContainer();

            ListOfBusinessAccounts.Set(context, coreEntitiesContainer.Parties.OfType<BusinessAccount>().ToArray());
        }
        /// <summary>
        /// Clear and create the database. Then populate it with design data.
        /// </summary>
        public static void ClearCreateCoreEntitiesDatabaseAndPopulateDesignData()
        {
            ClearCreateCoreEntitiesDatabase();

            var container = new CoreEntitiesContainer(ServerConstants.ContainerConnectionString);

            //Setup blocks
            PopulateBlocks(container);

            //Setup Business Accounts (and ServiceTemplates)
            var businessAccountsDesignData = new BusinessAccountsDesignData();

            //Setup User Accounts
            var userAccountsDesignData = new UserAccountsDesignData
                                             {
                                                 //Set Passwords
                                                 Andrew = { PasswordHash = EncryptionTools.Hash("f00sballchamp", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" },
                                                 Jon = { PasswordHash = EncryptionTools.Hash("seltzer", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" },
                                                 Oren = { PasswordHash = EncryptionTools.Hash("nachoman", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" },
                                                 Zach = { PasswordHash = EncryptionTools.Hash("curlyhair", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" },
                                                 David = { PasswordHash = EncryptionTools.Hash("starofdavid", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" },
                                                 Linda = { PasswordHash = EncryptionTools.Hash("auntie", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" },
                                                 Terri = { PasswordHash = EncryptionTools.Hash("iam1randompassword", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" },
                                                 AlanMcClure = { PasswordHash = EncryptionTools.Hash("youngster", new byte[] { 65, 0, 65 }), TimeZone = "Eastern Standard Time" }
                                             };

            //Setup roles
            new RolesDesignData(businessAccountsDesignData, userAccountsDesignData);

            //var changes = container.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Select(o => o.Entity).OfType<ServiceTemplate>().Where(st => st.CreatedDate < DateTime.UtcNow.AddDays(-1) || st.LastModified < DateTime.UtcNow.AddDays(-1));

            //container.SaveChanges();

            //Populate ServiceProvider Design Data
            foreach (var serviceProvider in businessAccountsDesignData.DesignServiceProviders)
            {
                var employeesDesignData = new EmployeesDesignData(serviceProvider);
                foreach (var employee in employeesDesignData.DesignEmployees)
                    serviceProvider.Employees.Add(employee);

                //container.SaveChanges();

                //Add Vehicles (and Vehicle Maintenance, and VehicleTypes)
                var vehiclesDesignData = new VehiclesDesignData(serviceProvider);
                foreach (var vehicle in vehiclesDesignData.DesignVehicles)
                    serviceProvider.Vehicles.Add(vehicle);

                //container.SaveChanges();

                //Add Regions
                var regionsDesignData = new RegionsDesignData();
                foreach (var region in regionsDesignData.DesignRegions)
                    serviceProvider.Regions.Add(region);

                //container.SaveChanges();

                //Add Clients (and ContactInfo, Locations, and RecurringServices)
                var clientsDesignData = new ClientsDesignData(serviceProvider, regionsDesignData);
                foreach (var client in clientsDesignData.DesignClients)
                    serviceProvider.Clients.Add(client);

                //container.SaveChanges();

                //Add Routes (with RouteTasks, Vehicles, Technicians)
                var routesDesignData = new RoutesDesignData(serviceProvider, clientsDesignData, vehiclesDesignData, employeesDesignData);
                foreach (var route in routesDesignData.DesignRoutes)
                    serviceProvider.Routes.Add(route);

                //container.SaveChanges();

                //Add Services
                var servicesDesignData = new ServicesDesignData(serviceProvider, clientsDesignData.DesignClients.ElementAt(0), serviceProvider.ServiceTemplates);
                foreach (var service in servicesDesignData.DesignServices)
                    serviceProvider.ServicesToProvide.Add(service);

                //container.SaveChanges();
            }

            container.SaveChanges();
        }
 public static void PopulateBlocks(CoreEntitiesContainer coreEntitiesContainer)
 {
     foreach (var block in BlocksData.AllBlocks)
         coreEntitiesContainer.Blocks.AddObject(block);
 }
        /// <summary>
        /// Populates HistoricalTrackPoints design data on the Azure tables.
        /// </summary>
        public static void CreateHistoricalTrackPoints()
        {
            var coreEntitiesContainer = new CoreEntitiesContainer();
            var businessAccountIds = coreEntitiesContainer.Parties.OfType<BusinessAccount>().Select(ba => ba.Id);

            foreach (var businessAccountId in businessAccountIds)
            {
                var tableName = businessAccountId.TrackPointTableName();

                var storageAccount = CloudStorageAccount.Parse(AzureServerHelpers.StorageConnectionString);
                var serviceContext = new TrackPointsHistoryContext(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials);

                var tableClient = storageAccount.CreateCloudTableClient();
                //Create the empty table once again
                tableClient.CreateTableIfNotExist(tableName);

                var serviceDate = DateTime.UtcNow;

                var routes = coreEntitiesContainer.Routes.Where(r => r.Date == serviceDate.Date && r.OwnerBusinessAccountId == businessAccountId).OrderBy(r => r.Id);

                //Do not setup design data for Test or Release
#if DEBUG
                #region Setup Design Data for Historical Track Points

                var numberOfRoutes = routes.Count();

                var count = 1;

                foreach (var route in routes)
                {
                    var routeNumber = count % numberOfRoutes;

                    switch (routeNumber)
                    {
                        //This would be the 4th, 8th, etc
                        case 0:
                            var employees = route.Employees;
                            foreach (var employee in employees)
                            {
                                var latitude = 40.4599;
                                var longitude = -86.9309;

                                //Sets timeStamp to be 9:00 AM yesterday
                                var timeStamp = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 9, 0, 0);

                                for (var totalCount = 1; totalCount <= 3; totalCount++)
                                {
                                    var partitionKey = Guid.NewGuid().ToString();
                                    for (var innerCount = 1; innerCount < 99; innerCount++)
                                    {
                                        //Create the object to be stored in the Azure table
                                        var newTrackPoint = new TrackPointsHistoryTableDataModel(partitionKey, Guid.NewGuid().ToString())
                                        {
                                            EmployeeId = employee.Id,
                                            VehicleId = null,
                                            RouteId = route.Id,
                                            Latitude = latitude,
                                            Longitude = longitude,
                                            CollectedTimeStamp = timeStamp,
                                            Accuracy = 1
                                        };

                                        latitude = latitude + .001;
                                        longitude = longitude + .001;
                                        timeStamp = timeStamp.AddSeconds(30);

                                        //Push to Azure Table
                                        serviceContext.AddObject(tableName, newTrackPoint);
                                    }
                                    serviceContext.SaveChangesWithRetries(SaveChangesOptions.Batch);
                                }
                            }
                            break;
                        //This would be the 1st, 5th, etc
                        case 1:
                            employees = route.Employees;
                            foreach (var employee in employees)
                            {
                                var latitude = 40.4599;
                                var longitude = -86.9309;

                                //Sets timeStamp to be 9:00 AM yesterday
                                var timeStamp = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 9, 0, 0);

                                for (var totalCount = 1; totalCount <= 3; totalCount++)
                                {
                                    var partitionKey = Guid.NewGuid().ToString();

                                    for (var innerCount = 1; innerCount <= 99; innerCount++)
                                    {
                                        //Create the object to be stored in the Azure table
                                        var newTrackPoint = new TrackPointsHistoryTableDataModel(partitionKey, Guid.NewGuid().ToString())
                                        {
                                            EmployeeId = employee.Id,
                                            VehicleId = null,
                                            RouteId = route.Id,
                                            Latitude = latitude,
                                            Longitude = longitude,
                                            CollectedTimeStamp = timeStamp,
                                            Accuracy = 1
                                        };

                                        latitude = latitude - .001;
                                        longitude = longitude + .001;
                                        timeStamp = timeStamp.AddSeconds(30);

                                        //Push to Azure Table
                                        serviceContext.AddObject(tableName, newTrackPoint);
                                    }
                                    serviceContext.SaveChangesWithRetries(SaveChangesOptions.Batch);

                                }
                            }
                            break;
                        //This would be the 2nd, 6th, etc
                        case 2:
                            employees = route.Employees;
                            foreach (var employee in employees)
                            {
                                var latitude = 40.4599;
                                var longitude = -86.9309;

                                //Sets timeStamp to be 9:00 AM yesterday
                                var timeStamp = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 9, 0, 0);

                                for (var totalCount = 1; totalCount <= 3; totalCount++)
                                {
                                    var partitionKey = Guid.NewGuid().ToString();

                                    for (var innerCount = 1; innerCount <= 99; innerCount++)
                                    {
                                        //Create the object to be stored in the Azure table
                                        var newTrackPoint = new TrackPointsHistoryTableDataModel(partitionKey, Guid.NewGuid().ToString())
                                        {
                                            EmployeeId = employee.Id,
                                            VehicleId = null,
                                            RouteId = route.Id,
                                            Latitude = latitude,
                                            Longitude = longitude,
                                            CollectedTimeStamp = timeStamp,
                                            Accuracy = 2
                                        };

                                        latitude = latitude + .001;
                                        longitude = longitude - .001;
                                        timeStamp = timeStamp.AddSeconds(30);

                                        //Push to Azure Table
                                        serviceContext.AddObject(tableName, newTrackPoint);
                                    }
                                    serviceContext.SaveChangesWithRetries(SaveChangesOptions.Batch);
                                }
                            }
                            break;
                        //This would be the 3rd, 7th, etc
                        case 3:
                            employees = route.Employees;
                            foreach (var employee in employees)
                            {
                                var latitude = 40.4599;
                                var longitude = -86.9309;

                                //Sets timeStamp to be 9:00 AM yesterday
                                var timeStamp = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 9, 0, 0);

                                for (var totalCount = 1; totalCount <= 3; totalCount++)
                                {
                                    var partitionKey = Guid.NewGuid().ToString();

                                    for (var innerCount = 1; innerCount <= 99; innerCount++)
                                    {
                                        //Create the object to be stored in the Azure table
                                        var newTrackPoint = new TrackPointsHistoryTableDataModel(partitionKey, Guid.NewGuid().ToString())
                                        {
                                            EmployeeId = employee.Id,
                                            VehicleId = null,
                                            RouteId = route.Id,
                                            Latitude = latitude,
                                            Longitude = longitude,
                                            CollectedTimeStamp = timeStamp,
                                            Accuracy = 3
                                        };

                                        latitude = latitude - .001;
                                        longitude = longitude - .001;
                                        timeStamp = timeStamp.AddSeconds(30);

                                        //Push to Azure Table
                                        serviceContext.AddObject(tableName, newTrackPoint);
                                    }
                                    serviceContext.SaveChangesWithRetries(SaveChangesOptions.Batch);
                                }
                            }
                            break;
                    }
                    count++;
                }

                #endregion
#endif
            }
        }
        /// <summary>
        /// Deletes the HistoricalTrackPoints tables.
        /// Must do this seperately from Create, because deleting tables takes time.
        /// </summary>
        public static void ClearHistoricalTrackPoints()
        {
            var coreEntitiesContainer = new CoreEntitiesContainer();
            var businessAccountIds = coreEntitiesContainer.Parties.OfType<BusinessAccount>().Select(ba => ba.Id);

            foreach (var businessAccountId in businessAccountIds)
            {
                var tableName = businessAccountId.TrackPointTableName();

                var storageAccount = CloudStorageAccount.Parse(AzureServerHelpers.StorageConnectionString);

                var tableClient = storageAccount.CreateCloudTableClient();

                //Delete the Table in Azure and all rows in it
                tableClient.DeleteTableIfExist(tableName);
            }
        }
 public CoreEntitiesMembershipProvider(CoreEntitiesContainer coreEntitiesContainer)
 {
     _coreEntitiesContainer = coreEntitiesContainer;
 }
 public CoreEntitiesMembershipProvider()
 {
     _coreEntitiesContainer = new CoreEntitiesContainer();
 }
Beispiel #16
0
        /// <summary>
        /// Loads a service template
        /// </summary>
        /// <param name="container">The container to attach it to</param>
        /// <param name="serviceTemplateId">Optional filter parameter</param>
        /// <param name="clientId">Optional filter parameter</param>
        /// <param name="serviceProviderId">Optional filter parameter</param>
        /// <param name="levelInt">Optional filter parameter</param>
        /// <returns>The applicable service templates</returns>
        public static ServiceTemplate[] LoadServiceTemplateWithDetails(CoreEntitiesContainer container, Guid? serviceTemplateId, Guid? clientId, Guid? serviceProviderId, int? levelInt)
        {
            using (var db = new DbContext(ServerConstants.SqlConnectionString))
            {
                db.Database.Connection.Open();

                var loadServiceTemplate = db.Database.Connection.CreateCommand();
                loadServiceTemplate.CommandText = "GetServiceTemplatesAndFields";
                loadServiceTemplate.CommandType = CommandType.StoredProcedure;

                #region Add Parameters

                var parameter = new SqlParameter
                {
                    ParameterName = "serviceProviderContextId",
                    DbType = DbType.Guid,
                    Direction = ParameterDirection.Input,
                    Value = serviceProviderId ?? (object) DBNull.Value
                };

                loadServiceTemplate.Parameters.Add(parameter);

                parameter = new SqlParameter
                {
                    ParameterName = "clientContextId",
                    DbType = DbType.Guid,
                    Direction = ParameterDirection.Input,
                    Value = clientId ?? (object)DBNull.Value
                };

                loadServiceTemplate.Parameters.Add(parameter);

                parameter = new SqlParameter
                {
                    ParameterName = "serviceTemplateContextId",
                    DbType = DbType.Guid,
                    Direction = ParameterDirection.Input,
                    Value = serviceTemplateId ?? (object)DBNull.Value
                };

                loadServiceTemplate.Parameters.Add(parameter);

                parameter = new SqlParameter
                {
                    ParameterName = "levelInt",
                    DbType = DbType.Int32,
                    Direction = ParameterDirection.Input,
                    Value = levelInt ?? (object)DBNull.Value
                };

                loadServiceTemplate.Parameters.Add(parameter);

                #endregion

                var reader = loadServiceTemplate.ExecuteReader();

                var serviceTemplates = container.Translate<ServiceTemplate>(reader, "ServiceTemplates", MergeOption.AppendOnly).ToArray();

                reader.NextResult();

                var fields = container.Translate<Field>(reader, "Fields", MergeOption.AppendOnly);

                reader.NextResult();

                var numericFields = container.Translate<NumericField>(reader, "Fields", MergeOption.AppendOnly).ToList();

                reader.NextResult();

                var textBoxFields = container.Translate<TextBoxField>(reader, "Fields", MergeOption.AppendOnly).ToList();

                reader.NextResult();

                var signatureFields = container.Translate<SignatureField>(reader, "Fields", MergeOption.AppendOnly).ToList();

                reader.NextResult();

                var optionsFields = container.Translate<OptionsField>(reader, "Fields", MergeOption.AppendOnly).ToList();

                reader.NextResult();

                var locationFields = container.Translate<LocationField>(reader, "Fields", MergeOption.AppendOnly).ToList();

                reader.NextResult();

                var locations = container.Translate<Location>(reader, "Locations", MergeOption.AppendOnly).ToList();

                db.Database.Connection.Close();

                return serviceTemplates;
            }
        }