コード例 #1
0
 private void LoadAppMetaData(AppDefinition thisApp)
 {
     txtAppId.Text    = thisApp.id.ToString();
     txtTitle.Text    = thisApp.title;
     txtAuthor.Text   = thisApp.author;
     txtVendorID.Text = thisApp.vendorId;
     foreach (ComboBoxItem comboChoice in comboCategory.Items)
     {
         if (comboChoice.Content.ToString().ToLower() == thisApp.category.ToLower())
         {
             comboCategory.SelectedItem = comboChoice;
         }
     }
     txtSummary.Text         = thisApp.summary;
     txtAppIcon.Text         = thisApp.appIcon;
     txtAppIconBig.Text      = thisApp.appIconBig;
     checkAdult.IsChecked    = thisApp.Adult;
     checkPixi.IsChecked     = thisApp.Pixi;
     checkVeer.IsChecked     = thisApp.Veer;
     checkPre.IsChecked      = thisApp.Pre;
     checkPre2.IsChecked     = thisApp.Pre2;
     checkPre3.IsChecked     = thisApp.Pre3;
     checkTouchPad.IsChecked = thisApp.TouchPad;
     checkLuneOS.IsChecked   = thisApp.LuneOS;
     radioTouchPad.IsChecked = thisApp.touchpad_exclusive;
 }
コード例 #2
0
 /// <summary>
 /// Gets the product at.
 /// </summary>
 public Product GetProductAt(int productIndex)
 {
     if (!AppDefinition.IsInIntervalRange(productIndex, 0, _products.Count - 1))
     {
         throw new ArgumentOutOfRangeException(ERROR_PRODUCT_INDEX_IS_OUT_OF_RANGE);
     }
     return(_products[productIndex]);
 }
コード例 #3
0
 /// <summary>
 /// Return true if the given product type index is in range of _productTypes.
 /// </summary>
 private bool IsInProductTypesIndexRange(int productTypeIndex)
 {
     if (_productTypes.Count <= 0)
     {
         throw new ArgumentException(ERROR_PRODUCT_TYPES_IS_EMPTY);
     }
     return(AppDefinition.IsInIntervalRange(productTypeIndex, 0, _productTypes.Count - 1));
 }
コード例 #4
0
 /// <summary>
 /// Set current product page index.
 /// </summary>
 private void SetCurrentProductPageIndexAndNotifyObserver(int productPageIndex)
 {
     if (!AppDefinition.IsInIntervalRange(productPageIndex, 0, _model.GetTabPageProductPagesCount(_currentTabPageIndex) - 1))
     {
         throw new ArgumentOutOfRangeException(ERROR_PRODUCT_PAGE_INDEX_IS_OUT_OF_RANGE);
     }
     _currentProductPageIndex = productPageIndex;
     NotifyObserverChangeCurrentProductPageIndex();
 }
コード例 #5
0
 /// <summary>
 /// Select the product tab page whose index is tabPageIndex.
 /// </summary>
 public void SelectProductTabPage(int tabPageIndex)
 {
     if (!AppDefinition.IsInIntervalRange(tabPageIndex, 0, _model.GetProductTypesCount() - 1))
     {
         throw new ArgumentOutOfRangeException(ERROR_TAB_PAGE_INDEX_IS_OUT_OF_RANGE);
     }
     _currentTabPageIndex = tabPageIndex;
     SetCurrentProductPageIndexAndNotifyObserver(CURRENT_PRODUCT_PAGE_INDEX_INITIAL_VALUE);
     SelectNoProduct();
 }
コード例 #6
0
        private void AddAndCheckRandomAppWithVersion(WebModelNode web, Version version)
        {
            var def = new AppDefinition();

            def.ProductId = DefaultContainers.Apps.ProductId;
            def.Version   = version.ToString();

            def.Content = File.ReadAllBytes(string.Format(DefaultContainers.Apps.GenericVersionableAppFilePath, version));

            web.AddApp(def, app =>
            {
                app.OnProvisioned <object, AppDefinition>(context =>
                {
                    Trace.WriteLine(context.ObjectDefinition.ToString());
                    Trace.WriteLine(context.Object.ToString());

                    var expectedAppVersion = new Version(context.ObjectDefinition.Version);

                    var obj     = context.Object;
                    var objType = context.Object.GetType();

                    if (objType.ToString().Contains("Microsoft.SharePoint.Client.AppInstance"))
                    {
                        // with CSOM there is no API to know current app installed version
                        // checking if app is Installed after every single update
                        var appStatus = obj.GetPropertyValue("Status").ToString();

                        Assert.IsTrue(appStatus == "Installed",
                                      string.Format("App should be installed after every update"));
                    }
                    else if (objType.ToString().Contains("Microsoft.SharePoint.Administration.SPAppInstance"))
                    {
                        var appObjet = obj.GetPropertyValue("App");

                        var versionString = appObjet.GetPropertyValue("VersionString") as string;
                        var spAppVersion  = new Version(versionString);

                        // either equal (update) or SharePoint version greater than local (second update)
                        // the test is run several times, so only once we have =, and then we have <
                        Assert.IsTrue(expectedAppVersion <= spAppVersion,
                                      string.Format("Expecting app version:[{0}] SharePoint app version:[{1}]", expectedAppVersion, spAppVersion));
                    }
                    else
                    {
                        throw new SPMeta2NotImplementedException(string.Format("ID property extraction is not implemented for type: [{0}]", objType));
                    }
                });
            });
        }
コード例 #7
0
        /// <summary>
        /// Get the product at productIndex in the product page of productPageIndex, which is of type productType. Return null if product does not exist.
        /// </summary>
        public Product GetProduct(string productType, int productPageIndex, int productIndex)
        {
            List <Product> productTypeProducts = GetProductTypeProducts(productType);

            if (productTypeProducts.Count == 0)
            {
                return(null);
            }
            int productTypeProductsIndex = productPageIndex * AppDefinition.TAB_PAGE_MAX_PRODUCTS_COUNT + productIndex;

            if (!AppDefinition.IsInIntervalRange(productTypeProductsIndex, 0, productTypeProducts.Count - 1))
            {
                return(null);
            }
            return(productTypeProducts[productTypeProductsIndex]);
        }
コード例 #8
0
        //[SampleMetadataTag(Name = BuiltInTagNames.SampleHidden)]
        public void CanDeploySimpleAppDefinition()
        {
            var appDef = new AppDefinition
            {
                Content   = File.ReadAllBytes("path-to-your-app-file"),
                ProductId = new Guid("your-app-product-id"),
                // your app version
                Version = "1.0.0.0"
            };

            var model = SPMeta2Model.NewWebModel(web =>
            {
                web.AddApp(appDef);
            });

            DeployModel(model);
        }
        /// <summary>
        /// Update enabled states of page navigation buttons.
        /// </summary>
        private void UpdatePageNavigationButtons()
        {
            int humanIndex = AppDefinition.GetHumanIndex(_currentProductPageIndex);

            if (humanIndex == 1)
            {
                _leftArrowButton.Enabled = false;
            }
            else
            {
                _leftArrowButton.Enabled = true;
            }
            if (humanIndex == _orderModel.GetTabPageProductPagesCount(_currentTabPageIndex))
            {
                _rightArrowButton.Enabled = false;
            }
            else
            {
                _rightArrowButton.Enabled = true;
            }
        }
コード例 #10
0
        private bool TryReplaceAppInCatalog(AppDefinition newApp, List <AppDefinition> catalogToUpdate, out List <AppDefinition> updatedCatalog)
        {
            AppDefinition appToReplace = new AppDefinition();
            bool          found        = false;

            foreach (AppDefinition checkApp in catalogToUpdate)
            {
                if (checkApp.id == newApp.id)
                {
                    appToReplace = checkApp;
                    found        = true;
                }
            }
            if (found)
            {
                catalogToUpdate[catalogToUpdate.IndexOf(appToReplace)] = newApp;
                updatedCatalog = catalogToUpdate;
                return(true);
            }
            updatedCatalog = catalogToUpdate;
            return(false);
        }
コード例 #11
0
        public async Task <AppDefinition> GetLwm2mModelsForClient(string endpoint)
        {
            var uri = $"{Constants.VisionApiUri}/api/app-management/get-client-models/{endpoint.Trim()}";

            var client        = new HttpClient();
            var appDefinition = new AppDefinition();

            try
            {
                client.MaxResponseContentBufferSize = 999999;
                client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", bearerToken.access_token));

                HttpResponseMessage response = await client.GetAsync(uri);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    appDefinition = JsonConvert.DeserializeObject <AppDefinition>(content);
                }
                else
                {
                    ConsoleHelper.WriteFailure("Could not get models: " + response.ToString());
                }
            }
            catch (Exception ex)
            {
                ConsoleHelper.WriteException("Error retrieving models", ex);
                throw;
            }
            finally
            {
                client.Dispose();
            }
            return(appDefinition);
        }
コード例 #12
0
        public async Task <Tuple <AppDefinition, Blob> > GetDataForPeriod(string endpoint, DateTime from, bool FileNamesRequired = false, DateTime?to = null)
        {
            var uri = $"{Constants.VisionApiUri}/api/app-data/data-for-period/{endpoint.Trim()}";

            var builder = new UriBuilder(uri);
            var query   = HttpUtility.ParseQueryString(builder.Query);

            query["from"] = from.ToString();
            query["to"]   = to.ToString();
            query["FileNamesRequired"] = FileNamesRequired.ToString();

            string queryString = query.ToString();
            string url         = builder.ToString();
            var    client      = new HttpClient();
            //client.MaxResponseContentBufferSize = 999999;
            var result = new Blob();

            try
            {
                client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", bearerToken.access_token));
                HttpResponseMessage response = await client.GetAsync(url + "?" + queryString);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    result = JsonConvert.DeserializeObject <Blob>(content);
                }
                else
                {
                    ConsoleHelper.WriteFailure("Could not retrieve app data. Please try again. If issue persits, conatact your system admin");
                }
            }
            catch (Exception ex)
            {
                ConsoleHelper.WriteException(ex);
            }
            finally
            {
                client.Dispose();
            }

            if (result?.FileNames?.Count > 0)
            {
                AppDefinition def = await GetLwm2mModelsForClient(endpoint);

                if (def == null)
                {
                    ConsoleHelper.WriteFailure("Could not retrieve app definition");
                }

                if (!def.lwm2mModel.Any())
                {
                    ConsoleHelper.WriteFailure($"No LWM2M Models retrieved for endpoint {endpoint}. Ensure host device is available/connected.");
                }

                ConsoleHelper.WriteSuccess(string.Format("Total files to process for period: {0}", result?.FileNames?.Count));
                return(new Tuple <AppDefinition, Blob>(def, result));
            }
            else
            {
                ConsoleHelper.WriteWarning("No files found for period.");
            }

            return(null);
        }
コード例 #13
0
        private void DeployApp(object modelHost, WebModelHost webHost, AppDefinition appModel)
        {
            var  web   = webHost.HostWeb;
            Guid appId = Guid.Empty;

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Creating memory stream on appModel.Content");

            using (var appPackage = new MemoryStream(appModel.Content))
            {
                var currentApplications = FindExistingApps(webHost, appModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioning,
                    Object           = currentApplications.FirstOrDefault(),
                    ObjectType       = typeof(AppInstance),
                    ObjectDefinition = appModel,
                    ModelHost        = modelHost
                });


                if (currentApplications == null || currentApplications.Count == 0)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Cannot find application by productId. Loading and installing new instance.");

                    // install new
                    var newAppInstance = web.LoadAndInstallApp(appPackage);

                    var context = web.Context;

                    context.Load(newAppInstance);
                    context.ExecuteQueryWithTrace();

                    if (newAppInstance != null && newAppInstance.Status == AppInstanceStatus.Initialized)
                    {
                        appId = newAppInstance.Id;

                        var         count         = 0;
                        AppInstance localInstance = null;

                        do
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                                       "Waiting while app is being installed for [{0}] milliseconds.",
                                                       WaitTimeInMillliseconds);

                            Thread.Sleep(WaitTimeInMillliseconds);
                            localInstance = web.GetAppInstanceById(appId);

                            context.Load(localInstance, l => l.Status);
                            context.ExecuteQueryWithTrace();

                            count++;
                        } while (localInstance != null &&
                                 localInstance.Status != AppInstanceStatus.Installed &&
                                 count < MaxInstallAttempCount);
                    }

                    newAppInstance = web.GetAppInstanceById(appId);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model            = null,
                        EventType        = ModelEventType.OnProvisioned,
                        Object           = newAppInstance,
                        ObjectType       = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost        = modelHost
                    });
                }
                else
                {
                    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing application. CSOM update is not supported yet.");

                    // R&D for update
                    // upApp.App is not available

                    //for (int i = 0; i < currentApplications.Count; i++)
                    //{
                    //    var upApp = currentApplications[i];
                    //    var upVersion = new Version(upApp.App.VersionString);

                    //    var targetVersion = new Version(appModel.Version);

                    //    if (upVersion < targetVersion)
                    //        currentApplications[i].Upgrade(appPackage);
                    //}

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model            = null,
                        EventType        = ModelEventType.OnProvisioned,
                        Object           = currentApplications.FirstOrDefault(),
                        ObjectType       = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost        = modelHost
                    });
                }
            }
        }
コード例 #14
0
ファイル: AppModelHandler.cs プロジェクト: tobi960/spmeta2
        private void DeployApp(object modelHost, WebModelHost webHost, AppDefinition appModel)
        {
            var  web   = webHost.HostWeb;
            Guid appId = Guid.Empty;

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Creating memory stream on appModel.Content");


            using (var appPackage = new MemoryStream(appModel.Content))
            {
                var currentApplications = FindExistingApps(webHost, appModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioning,
                    Object           = currentApplications.FirstOrDefault(),
                    ObjectType       = typeof(SPAppInstance),
                    ObjectDefinition = appModel,
                    ModelHost        = modelHost
                });

                if (currentApplications.Count == 0)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Cannot find application by productId. Loading and installing new instance.");

                    // install new
                    var newAppInstance = web.LoadAndInstallApp(appPackage);

                    if (newAppInstance != null && newAppInstance.Status == SPAppInstanceStatus.Initialized)
                    {
                        appId = newAppInstance.Id;

                        var           count         = 0;
                        SPAppInstance localInstance = null;

                        do
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                                       "Waiting while app is being installed for [{0}] milliseconds.",
                                                       WaitTimeInMillliseconds);

                            Thread.Sleep(WaitTimeInMillliseconds);
                            localInstance = web.GetAppInstanceById(appId);

                            count++;
                        } while (localInstance != null &&
                                 localInstance.Status != SPAppInstanceStatus.Installed &&
                                 count < MaxInstallAttempCount);
                    }

                    newAppInstance = web.GetAppInstanceById(appId);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model            = null,
                        EventType        = ModelEventType.OnProvisioned,
                        Object           = newAppInstance,
                        ObjectType       = typeof(SPAppInstance),
                        ObjectDefinition = appModel,
                        ModelHost        = modelHost
                    });
                }
                else
                {
                    //we had check early
                    var currentApp = currentApplications.FirstOrDefault();

                    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject,
                                             string.Format("Processing existing application. Upgrading from [{0}] to [{1}]", currentApp.App.VersionString, appModel.Version));

                    var hasUpdate = false;

                    for (int i = 0; i < currentApplications.Count; i++)
                    {
                        var spApp        = currentApplications[i];
                        var spAppVersion = new Version(spApp.App.VersionString);

                        var definitionVersion = new Version(appModel.Version);

                        if (definitionVersion > spAppVersion)
                        {
                            TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Performing upgrade");

                            var updateAppInstance = currentApplications[i];
                            var updateAppId       = updateAppInstance.Id;

                            var           count = 0;
                            SPAppInstance localUpdateAppInstance = null;

                            updateAppInstance.Upgrade(appPackage);

                            do
                            {
                                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                                           "Waiting while app is being installed for [{0}] milliseconds.",
                                                           WaitTimeInMillliseconds);

                                Thread.Sleep(WaitTimeInMillliseconds);
                                localUpdateAppInstance = web.GetAppInstanceById(updateAppId);

                                count++;
                            } while (localUpdateAppInstance != null &&
                                     localUpdateAppInstance.Status != SPAppInstanceStatus.Installed &&
                                     count < MaxInstallAttempCount);

                            hasUpdate = true;
                        }
                        else
                        {
                            TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Skipping upgrade due to the lower version");
                        }
                    }

                    if (hasUpdate)
                    {
                        // refreshing the app collection after update
                        // the .App.VersionString property will be refreshed
                        currentApplications = FindExistingApps(webHost, appModel);
                    }

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model            = null,
                        EventType        = ModelEventType.OnProvisioned,
                        Object           = currentApplications.FirstOrDefault(),
                        ObjectType       = typeof(SPAppInstance),
                        ObjectDefinition = appModel,
                        ModelHost        = modelHost
                    });
                }
            }
        }
コード例 #15
0
        public List <Lwm2mModel> MapDataToModels(AppDefinition deviceInfo, List <Dictionary <string, dynamic> > allData)
        {
            try
            {
                var dataToReturn = new List <Lwm2mModel>();
                foreach (var json in allData)
                {
                    var data        = Json.Decode(json.Values.FirstOrDefault());
                    var actualData  = data.Data;
                    var objId       = Convert.ToInt32(data.ObjectId);
                    var model       = deviceInfo.lwm2mModel.Where(x => x.id == objId).FirstOrDefault();
                    var modelToPush = new Lwm2mModel();
                    modelToPush.id                 = model.id;
                    modelToPush.name               = model.name;
                    modelToPush.instancetype       = model.instancetype;
                    modelToPush.instance           = model.instance;
                    modelToPush.mandatory          = model.mandatory;
                    modelToPush.description        = model.description;
                    modelToPush.serverCreationTime = json.Keys.FirstOrDefault().Substring(0, json.Keys.FirstOrDefault().IndexOf("."));
                    modelToPush.resourcedefs       = new List <ResourceDefnitions>();
                    if (actualData != null)
                    {
                        var checkIfInstance = actualData.resources;

                        // determine if instance
                        var ObjectObserve = actualData.instances;
                        if (ObjectObserve != null && ObjectObserve is DynamicJsonArray)
                        {
                            foreach (var instance in ObjectObserve)
                            {
                                var instanceID = instance.id;
                                var resources  = instance.resources;
                                foreach (var item in resources)
                                {
                                    var resourceID = Convert.ToInt32(item.id);
                                    var resDef     = model.resourcedefs.Where(x => x.id == resourceID).FirstOrDefault();
                                    resDef.value = Convert.ToString(item.value);
                                    modelToPush.resourcedefs.Add(resDef);
                                }
                            }
                            dataToReturn.Add(modelToPush);
                        }
                        else
                        {  // determine if resource observe or instance observe data
                            if (checkIfInstance != null && checkIfInstance is DynamicJsonArray)
                            {
                                var instance = Convert.ToInt32(actualData.id);
                                foreach (var item in checkIfInstance)
                                {
                                    var resourceID = Convert.ToInt32(item.id);
                                    var resDef     = model.resourcedefs.Where(x => x.id == resourceID).FirstOrDefault();
                                    resDef.value = Convert.ToString(item.value);
                                    modelToPush.resourcedefs.Add(resDef);
                                }
                                dataToReturn.Add(modelToPush);
                            }
                            else
                            {
                                // its resource observe data
                                var resourceID = Convert.ToInt32(data.Data.id);
                                var resDef     = model.resourcedefs.Where(x => x.id == resourceID).FirstOrDefault();
                                resDef.value = Convert.ToString(data.Data.value);
                                modelToPush.resourcedefs.Add(resDef);
                                dataToReturn.Add(modelToPush);
                            }
                        }
                    }
                }
                return(dataToReturn);
            }
            catch (Exception ex)
            {
                ConsoleHelper.WriteException("Error mapping models", ex);
                return(null);
            }
        }
コード例 #16
0
 public OrderProductTabPage(int tabPageIndexData, List <Product> allProducts)
 {
     _tabPageProductType = AppDefinition.ConvertTabPageIndexToProductType(tabPageIndexData);
     InitializeProducts(allProducts);
     InitializeProductPages();
 }
コード例 #17
0
ファイル: AppModelHandler.cs プロジェクト: tobi960/spmeta2
 protected IList <SPAppInstance> FindExistingApps(WebModelHost webHost, AppDefinition appModel)
 {
     return(webHost.HostWeb.GetAppInstancesByProductId(appModel.ProductId));
 }
コード例 #18
0
 public static TModelNode AddApp <TModelNode>(this TModelNode model, AppDefinition definition)
     where TModelNode : ModelNode, IWebHostModelNode, new()
 {
     return(AddApp(model, definition, null));
 }
コード例 #19
0
ファイル: AppModelHandler.cs プロジェクト: tobi960/spmeta2
        private void DeployApp(object modelHost, WebModelHost webHost, AppDefinition appModel)
        {
            var web     = webHost.HostWeb;
            var context = web.Context;

            var appId = Guid.Empty;

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Creating memory stream on appModel.Content");

            using (var appPackage = new MemoryStream(appModel.Content))
            {
                var currentApplications = FindExistingApps(webHost, appModel);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioning,
                    Object           = currentApplications.FirstOrDefault(),
                    ObjectType       = typeof(AppInstance),
                    ObjectDefinition = appModel,
                    ModelHost        = modelHost
                });


                if (currentApplications == null || currentApplications.Count == 0)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Cannot find application by productId. Loading and installing new instance.");

                    // install new
                    var newAppInstance = web.LoadAndInstallApp(appPackage);



                    context.Load(newAppInstance);
                    context.ExecuteQueryWithTrace();

                    if (newAppInstance != null && newAppInstance.Status == AppInstanceStatus.Initialized)
                    {
                        appId = newAppInstance.Id;

                        var         count         = 0;
                        AppInstance localInstance = null;

                        do
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                                       "Waiting while app is being installed for [{0}] milliseconds.",
                                                       WaitTimeInMillliseconds);

                            Thread.Sleep(WaitTimeInMillliseconds);
                            localInstance = web.GetAppInstanceById(appId);

                            context.Load(localInstance, l => l.Status);
                            context.ExecuteQueryWithTrace();

                            count++;
                        } while (localInstance != null &&
                                 localInstance.Status != AppInstanceStatus.Installed &&
                                 count < MaxInstallAttempCount);
                    }

                    newAppInstance = web.GetAppInstanceById(appId);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model            = null,
                        EventType        = ModelEventType.OnProvisioned,
                        Object           = newAppInstance,
                        ObjectType       = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost        = modelHost
                    });
                }
                else
                {
                    //we had check early
                    var currentApp = currentApplications.FirstOrDefault();

                    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject,
                                             string.Format("Processing existing application. Upgrading from [{0}] to [{1}]", currentApp.Title, appModel.Version));

                    var hasUpdate = false;

                    for (int i = 0; i < currentApplications.Count; i++)
                    {
                        var spApp = currentApplications[i];
                        //var spAppVersion = new Version(spApp.App.VersionString);

                        var definitionVersion = new Version(appModel.Version);

                        // always install
                        //if (definitionVersion > spAppVersion)
                        //{
                        TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Performing upgrade");

                        var updateAppInstance = currentApplications[i];
                        var updateAppId       = updateAppInstance.Id;

                        var         count = 0;
                        AppInstance localUpdateAppInstance = null;

                        try
                        {
                            updateAppInstance.Upgrade(appPackage);
                            context.ExecuteQueryWithTrace();
                        }
                        catch (Exception upgradeException)
                        {
                            // handling early version upgrades
                            // Microsoft.SharePoint.Client.ServerException]
                            // {"An App Instance can only be upgraded to a newer version of the same product. The upgrade request was for product 1.0.0.3 version e81b6820-5d57-4d17-a098-5f4317f6c400 to product 1.0.0.0 version e81b6820-5d57-4d17-a098-5f4317f6c400."}

                            if (IsAppUpgradeException(upgradeException))
                            {
                                // fascinating
                                // jumping to the happy end
                                goto AppShouldNotBeUpdated;
                            }

                            throw;
                        }

                        do
                        {
                            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                                                       "Waiting while app is being installed for [{0}] milliseconds.",
                                                       WaitTimeInMillliseconds);

                            Thread.Sleep(WaitTimeInMillliseconds);
                            localUpdateAppInstance = web.GetAppInstanceById(updateAppId);

                            context.Load(localUpdateAppInstance, l => l.Status);
                            context.ExecuteQueryWithTrace();

                            count++;
                        } while (localUpdateAppInstance != null &&
                                 localUpdateAppInstance.Status != AppInstanceStatus.Installed &&
                                 count < MaxInstallAttempCount);

                        hasUpdate = true;

                        //}
                        //else
                        //{
                        //    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Skipping upgrade due to the lower version");
                        //}
                    }

                    if (hasUpdate)
                    {
                        // refreshing the app collection after update
                        // the .App.VersionString property will be refreshed
                        currentApplications = FindExistingApps(webHost, appModel);
                    }

AppShouldNotBeUpdated:

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model            = null,
                        EventType        = ModelEventType.OnProvisioned,
                        Object           = currentApplications.FirstOrDefault(),
                        ObjectType       = typeof(AppInstance),
                        ObjectDefinition = appModel,
                        ModelHost        = modelHost
                    });
                }
            }
        }
コード例 #20
0
 public static ModelNode AddApp(this ModelNode model, AppDefinition definition)
 {
     return(AddApp(model, definition, null));
 }
コード例 #21
0
 /// <summary>
 /// Get the page label text.
 /// </summary>
 public string GetPageLabelText()
 {
     return(AppDefinition.PAGE_LABEL_TEXT + AppDefinition.GetHumanIndex(_currentProductPageIndex) + AppDefinition.PAGE_LABEL_DELIMITER + _model.GetTabPageProductPagesCount(_currentTabPageIndex));
 }
コード例 #22
0
 public static TModelNode AddApp <TModelNode>(this TModelNode model, AppDefinition definition,
                                              Action <AppModelNode> action)
     where TModelNode : ModelNode, IWebHostModelNode, new()
 {
     return(model.AddTypedDefinitionNode(definition, action));
 }
コード例 #23
0
 public void TestGetHumanIndex()
 {
     Assert.ThrowsException <ArgumentException>(() => AppDefinition.GetHumanIndex(-1));
     Assert.AreEqual(AppDefinition.GetHumanIndex(0), 1);
     Assert.AreEqual(AppDefinition.GetHumanIndex(5), 6);
 }
コード例 #24
0
 public void TestIsInIntervalRange()
 {
     Assert.IsTrue(AppDefinition.IsInIntervalRange(5, 4, 6));
     Assert.IsFalse(AppDefinition.IsInIntervalRange(3, 4, 6));
     Assert.IsFalse(AppDefinition.IsInIntervalRange(5, 6, 4));
 }
コード例 #25
0
 public static ModelNode AddApp(this ModelNode model, AppDefinition definition, Action <ModelNode> action)
 {
     return(model.AddDefinitionNode(definition, action));
 }
コード例 #26
0
 /// <summary>
 /// Update current product page.
 /// </summary>
 private void UpdateCurrentProductPage()
 {
     _pageLabel.Text = AppDefinition.PAGE_LABEL_TEXT + AppDefinition.GetHumanIndex(_currentProductPageIndex) + AppDefinition.PAGE_LABEL_DELIMITER + _orderModel.GetTabPageProductPagesCount(_currentTabPageIndex);
     UpdatePageNavigationButtons();
     SelectNoProduct();
 }
コード例 #27
0
        /// <summary>
        /// Get product by storageDataGridViewRowIndex.
        /// </summary>
        public Product GetProduct(int storageDataGridViewRowIndex)
        {
            int productId = AppDefinition.GetHumanIndex(storageDataGridViewRowIndex);

            return(_model.GetProduct(productId));
        }
コード例 #28
0
        private bool TrySaveAppInfo()
        {
            //Make sure we have a valid App ID
            if (!int.TryParse(txtAppId.Text, out int appIdInt))
            {
                MessageBox.Show("The App ID does not parse to an integer and cannot be used.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                txtAppId.Focus();
                return(false);
            }
            else
            {
                string saveFileId = Path.GetFileNameWithoutExtension(txtFilename.Text);
                if (txtAppId.Text != saveFileId)
                {
                    MessageBoxResult confirm = MessageBox.Show("Filename App ID and Catalog App ID do not match. Are you sure you wish to save?", "Caution", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (confirm == MessageBoxResult.No)
                    {
                        return(false);
                    }
                }
            }

            //Make fields into valid AppDefinition Object
            AppDefinition appUpdate = new AppDefinition();

            try
            {
                appUpdate.id                 = appIdInt;
                appUpdate.title              = txtTitle.Text;
                appUpdate.summary            = txtSummary.Text;
                appUpdate.author             = txtAuthor.Text;
                appUpdate.vendorId           = txtVendorID.Text;
                appUpdate.category           = comboCategory.Text;
                appUpdate.appIcon            = txtAppIcon.Text;
                appUpdate.appIconBig         = txtAppIconBig.Text;
                appUpdate.Adult              = (bool)checkAdult.IsChecked;
                appUpdate.touchpad_exclusive = (bool)radioTouchPad.IsChecked;
                appUpdate.TouchPad           = (bool)checkTouchPad.IsChecked;
                appUpdate.LuneOS             = (bool)checkLuneOS.IsChecked;
                appUpdate.Pre3               = (bool)checkPre3.IsChecked;
                appUpdate.Pre2               = (bool)checkPre2.IsChecked;
                appUpdate.Pre                = (bool)checkPre.IsChecked;
                appUpdate.Veer               = (bool)checkVeer.IsChecked;
                appUpdate.Pixi               = (bool)checkPixi.IsChecked;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error mapping catalog fields: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            //Try to write catalog files
            bool catalogWriteFailure = true;
            List <AppDefinition> masterAppCatalog = ReadCatalogFile(Path.Combine(appCatalogDir, "masterAppData.json"));

            if (TryReplaceAppInCatalog(appUpdate, masterAppCatalog, out masterAppCatalog))
            {
                if (!WriteCatalogFile("master", masterAppCatalog))
                {
                    return(false);
                }
                else
                {
                    List <AppDefinition> extantAppCatalog = ReadCatalogFile(Path.Combine(appCatalogDir, "extantAppData.json"));
                    if (!TryReplaceAppInCatalog(appUpdate, extantAppCatalog, out extantAppCatalog))
                    {
                        List <AppDefinition> missingAppCatalog = ReadCatalogFile(Path.Combine(appCatalogDir, "missingAppData.json"));
                        if (!TryReplaceAppInCatalog(appUpdate, missingAppCatalog, out missingAppCatalog))
                        {
                            MessageBox.Show("Although the app was updated in the masterAppCatalog, it could not be updated in the extant/missing catalogs", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return(false);
                        }
                        else
                        {
                            if (WriteCatalogFile("missing", missingAppCatalog))
                            {
                                catalogWriteFailure = false;
                            }
                        }
                    }
                    else
                    {
                        if (WriteCatalogFile("extant", extantAppCatalog))
                        {
                            catalogWriteFailure = false;
                        }
                    }
                    catalogWriteFailure = false;
                }
            }
            else
            {
                MessageBox.Show("The app could not be updated in the masterAppCatalog, so it was not updated in the extant/missing catalogs either.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }

            if (catalogWriteFailure)
            {
                return(false);
            }
            else
            {
                //Finally actually update the metadata JSON
                try
                {
                    File.WriteAllText(txtFilename.Text, txtMetaJson.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occured saving metadata file: " + txtFilename.Text + "-test" + "\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            return(true);
        }
コード例 #29
0
        protected ClientObjectList <AppInstance> FindExistingApps(WebModelHost webHost, AppDefinition appModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindExistingApps() - finding app by productId: [{0}]", appModel.ProductId);

            var context = webHost.HostWeb.Context;
            var result  = webHost.HostWeb.GetAppInstancesByProductId(appModel.ProductId);

            context.Load(result);
            context.ExecuteQueryWithTrace();

            return(result);
        }
コード例 #30
0
 /// <summary>
 /// Return true if the index is in the order items index range.
 /// </summary>
 private bool IsInOrderItemsIndexRange(int index)
 {
     return(AppDefinition.IsInIntervalRange(index, 0, _orderItems.Count - 1));
 }