示例#1
0
        protected override void LoadData(IZip zip)
        {
            if (string.IsNullOrWhiteSpace(Manifest.Application.Filename))
                throw new InvalidOperationException("Bundle does not contain pebble app");

            using (Stream binStream = zip.OpenEntryStream(Manifest.Application.Filename))
            {
                if (binStream == null)
                    throw new Exception(string.Format("App file {0} not found in archive", Manifest.Application.Filename));

                App = Util.GetBytes(binStream);

                AppMetadata = BinarySerializer.ReadObject<ApplicationMetadata>(App);
            }
        }
    /// <summary>
    /// Sends a speech recognition request to the speech service
    /// </summary>
    /// <param name="audioFile">The audio file.</param>
    /// <param name="locale">The locale.</param>
    /// <param name="serviceUrl">The service URL.</param>
    /// <param name="subscriptionKey">The subscription key.</param>
    /// <returns>
    /// A task
    /// </returns>
    public async Task Run()
    {
        // create the preferences object
        var preferences = new Preferences("en-US", LongDictationUrl, new CognitiveServicesAuthorizationProvider("c26f94bbc00e4c98a0ee0cde5833506a"));

        // Create a a speech client
        using (var speechClient = new SpeechClient(preferences))
        {
            //speechClient.SubscribeToPartialResult(this.OnPartialResult);
            speechClient.SubscribeToRecognitionResult(this.OnRecognitionResult);

            // create an audio content and pass it a stream.
            using (var audio = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                var deviceMetadata      = new DeviceMetadata(DeviceType.Near, DeviceFamily.Desktop, NetworkType.Ethernet, OsName.Windows, "1607", "Dell", "T3600");
                var applicationMetadata = new ApplicationMetadata("SampleApp", "1.0.0");
                var requestMetadata     = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "SampleAppService");

                await speechClient.RecognizeAsync(new SpeechInput(audio, requestMetadata), this.cts.Token).ConfigureAwait(false);
            }
        }
        // Create a client.
        ITextAnalyticsAPI client = new TextAnalyticsAPI();

        client.AzureRegion     = AzureRegions.Westcentralus;
        client.SubscriptionKey = "922da2349b3f4d5f8d30cf175347ce7b";
        SentimentBatchResult result3 = client.Sentiment(
            new MultiLanguageBatchInput(
                new List <MultiLanguageInput>()
        {
            new MultiLanguageInput("en", "0", Msg),
        }));


        // Printing sentiment results
        var           document = result3.Documents[result3.Documents.Count() - 1];
        StringBuilder sb       = new StringBuilder();

        sb.AppendFormat("Sentiment Score: {0:0.00}", document.Score);

        //Save to DB
        string sql = "update [CaseConversation] set [ConversationTranscript] = '" + Msg + "',";

        sql += "[SentimentScore] = " + document.Score + " where id = " + sqlInt + ";";
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnectionString"]))
        {
            // 1. declare command object with parameter
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            // 2. define parameters used in command object
            //SqlParameter param = new SqlParameter();
            //param.ParameterName = "@qkid";
            //param.Value = "''";

            // 3. add new parameter to command object
            //cmd.Parameters.Add(param);
            int sqlInt2 = cmd.ExecuteNonQuery();

            cmd.Dispose();
            conn.Close();
        }
        Msg += "<br /> <br />" + sb.ToString();
    }
 public void DidReceiveStatus(DeviceManager deviceManager, ApplicationMetadata applicationMetadata)
 {
     viewCtrl.AppMetadata = applicationMetadata;
 }
示例#4
0
 public static UpdateInfo?GetUpdateInfo(this FileInfo fileInfo, ApplicationMetadata metadata, bool grabDeltaUpdates, object?tag = null, string?folderLocation = null)
 {
     return(GetUpdateInfo(fileInfo.FullName, metadata, grabDeltaUpdates, tag, folderLocation));
 }
示例#5
0
 protected MaximoOperationExecutionContext GetContext(ApplicationMetadata applicationMetadata, EntityMetadata entityMetadata, OperationType operationType, string id = null)
 {
     return(MaximoOperationExecutionContext.GetInstance(new BaseOperationData(entityMetadata, applicationMetadata, operationType, id), null));
 }
示例#6
0
        private void HandleLongDescription(object integrationObject, CrudOperationData entity, ApplicationMetadata metadata)
        {
            var ld          = (CrudOperationData)entity.GetRelationship("longdescription");
            var association = entity.EntityMetadata.Associations.First(a => a.To == "longdescription");

            if (ld != null)
            {
                var originalLd      = (string)ld.GetAttribute("ldtext");
                var longDescription = ParseSchemaBasedLD(originalLd, entity, metadata.Schema.SchemaId);
                w.SetValue(integrationObject, "DESCRIPTION_LONGDESCRIPTION", longDescription);
            }
        }
示例#7
0
        public ApplicationDetailResult GetMockedDataMap(string applicationName, ApplicationSchemaDefinition schema, ApplicationMetadata metadata) {
            var dictionary = new Dictionary<string, object>();




            var applicationDisplayables = schema.Displayables;
            var entity = MetadataProvider.Entity(metadata.Entity);

            var slicedMetadata = MetadataProvider.SlicedEntityMetadata(metadata);


            //forcing query to simulate some bugs, such as HAP-1161
            var randomEntity = _entityRepository.Get(slicedMetadata, "2");



            var attributes = entity.Attributes(Metadata.Entities.EntityMetadata.AttributesMode.NoCollections);
            var entityAttributes = attributes as IList<EntityAttribute> ?? attributes.ToList();
            int i = 1;
            foreach (var applicationDisplayable in applicationDisplayables) {
                var field = applicationDisplayable as BaseApplicationFieldDefinition;
                if (field != null && !dictionary.ContainsKey(field.Attribute)) {
                    var entityDeclaration = entityAttributes.FirstOrDefault(a => a.Name.EqualsIc(field.Attribute));
                    if (entityDeclaration != null && entityDeclaration.Type.Contains("int")) {
                        var random = new Random();
                        var randomNumber = random.Next(0, 1000);
                        dictionary.Add(field.Attribute, randomNumber);
                    } else {
                        dictionary.Add(field.Attribute, "mocked value " + i);
                    }
                }
                i++;
            }
            var dataMap = new DataMap(applicationName,metadata.IdFieldName, dictionary);
            return new ApplicationDetailResult(dataMap, null, schema,
                        CompositionBuilder.InitializeCompositionSchemas(metadata.Schema), "id");
        }
示例#8
0
 public void HandleAttachments(object maximoObj, string attachmentData, string attachmentPath, ApplicationMetadata applicationMetadata)
 {
     if (!String.IsNullOrWhiteSpace(attachmentData) && !String.IsNullOrWhiteSpace(attachmentPath))
     {
         var user = SecurityFacade.CurrentUser();
         if (String.IsNullOrEmpty(attachmentData))
         {
             return;
         }
         var docLink = ReflectionUtil.InstantiateSingleElementFromArray(maximoObj, "DOCLINKS");
         CommonCode(maximoObj, docLink, user, attachmentPath, attachmentData);
         HandleAttachmentDataAndPath(attachmentData, docLink, attachmentPath);
     }
 }
示例#9
0
 public override SynchronizationApplicationData Sync(ApplicationMetadata applicationMetadata, SynchronizationRequestDto.ApplicationSyncData applicationSyncData)
 {
     return(MaximoConnectorEngine.Sync(applicationMetadata, applicationSyncData, AttachmentSyncDelegate));
 }
示例#10
0
 public AssociationPreFilterFunctionParameters(ApplicationMetadata metadata, SearchRequestDto baseDto,
                                               ApplicationAssociationDefinition association, AttributeHolder originalEntity)
     : base(baseDto, association, originalEntity)
 {
     _metadata = metadata;
 }
示例#11
0
 public override void OnApplicationMetadataChanged (ApplicationMetadata applicationMetadata)
 {
     Console.WriteLine ("Metadata Changed");
 }
示例#12
0
        protected virtual void HandleLongDescription(ServiceIncident webServiceObject, CrudOperationData entity, ApplicationMetadata metadata, bool update)
        {
            var problem = webServiceObject.Problem;
            var ld      = (CrudOperationData)entity.GetRelationship("longdescription");

            if (ld != null)
            {
                problem.Description = (string)ld.GetAttribute("ldtext");
            }
        }
        protected virtual IDictionary <string, BaseAssociationUpdateResult> DoUpdateAssociation(ApplicationMetadata application, AssociationUpdateRequest request,
                                                                                                AttributeHolder cruddata)
        {
            var before = LoggingUtil.StartMeasuring(Log, "starting update association options fetching for application {0} schema {1}", application.Name, application.Schema.Name);
            IDictionary <string, BaseAssociationUpdateResult> resultObject =
                new Dictionary <string, BaseAssociationUpdateResult>();
            ISet <string> associationsToUpdate = null;

            // Check if 'self' (for lazy load) or 'dependant' (for dependant combos) association update
            if (!String.IsNullOrWhiteSpace(request.AssociationFieldName))
            {
                associationsToUpdate = new HashSet <String> {
                    request.AssociationFieldName
                };
            }
            else if (!String.IsNullOrWhiteSpace(request.TriggerFieldName))
            {
                var triggerFieldName = request.TriggerFieldName;
                if (!application.Schema.DependantFields.TryGetValue(triggerFieldName, out associationsToUpdate))
                {
                    throw new InvalidOperationException();
                }
            }

            if (associationsToUpdate == null)
            {
                return(resultObject);
            }

            var tasks = new List <Task>();
            var ctx   = ContextLookuper.LookupContext();

            //there might be some associations/optionfields to be updated after the first value is selected
            foreach (var associationToUpdate in associationsToUpdate)
            {
                var association = application.Schema.Associations.FirstOrDefault(f => (
                                                                                     EntityUtil.IsRelationshipNameEquals(f.AssociationKey, associationToUpdate)));
                if (association == null)
                {
                    var optionField = application.Schema.OptionFields.First(f => f.AssociationKey == associationToUpdate);
                    tasks.Add(Task.Factory.NewThread(c => {
                        Quartz.Util.LogicalThreadContext.SetData("context", c);
                        var data = _dynamicOptionFieldResolver.ResolveOptions(application, optionField, cruddata);
                        resultObject.Add(optionField.AssociationKey, new LookupAssociationUpdateResult(data, 100, PaginatedSearchRequestDto.DefaultPaginationOptions));
                    }, ctx));
                }
                else
                {
                    var associationApplicationMetadata =
                        ApplicationAssociationResolver.GetAssociationApplicationMetadata(association);

                    var searchRequest = BuildSearchDTO(request, association, cruddata);

                    if (searchRequest == null)
                    {
                        //this would only happen if association is lazy and there´s no default value
                        //(cause we´d need to fetch one-value list for displaying)
                        continue;
                    }
                    var threadSafeContext = new ContextHolderWithSearchDto(ctx, searchRequest);
                    tasks.Add(Task.Factory.NewThread(c => {
                        Quartz.Util.LogicalThreadContext.SetData("context", threadSafeContext.Context);
                        var options = _associationOptionResolver.ResolveOptions(application, cruddata, association,
                                                                                threadSafeContext.Dto);

                        resultObject.Add(association.AssociationKey,
                                         new LookupAssociationUpdateResult(searchRequest.TotalCount, searchRequest.PageNumber,
                                                                           searchRequest.PageSize, options, associationApplicationMetadata, PaginatedSearchRequestDto.DefaultPaginationOptions));
                    }, threadSafeContext));
                }
            }

            Task.WaitAll(tasks.ToArray());

            if (Log.IsDebugEnabled)
            {
                var keys = String.Join(",", resultObject.Keys.Where(k => resultObject[k].AssociationData != null));
                Log.Debug(LoggingUtil.BaseDurationMessageFormat(before,
                                                                "Finished execution of options fetching. Resolved collections: {0}", keys));
            }
            return(resultObject);
        }
        public GenericResponseResult <IDictionary <string, BaseAssociationUpdateResult> > UpdateAssociations(ApplicationMetadata application,
                                                                                                             AssociationUpdateRequest request, JObject currentData)
        {
            var entityMetadata = MetadataProvider.Entity(application.Entity);
            var cruddata       = EntityBuilder.BuildFromJson <CrudOperationData>(typeof(CrudOperationData), entityMetadata,
                                                                                 application, currentData, request.Id);

            if (EagerAssociationTrigger.Equals(request.TriggerFieldName))
            {
                request.AssociationsToFetch = AssociationHelper.AllButSchema;
                return(new GenericResponseResult <IDictionary <string, BaseAssociationUpdateResult> >(BuildAssociationOptions(cruddata, application, request)));
            }
            return(new GenericResponseResult <IDictionary <string, BaseAssociationUpdateResult> >(DoUpdateAssociation(application, request, cruddata)));
        }
示例#15
0
        private IEnumerable <IHlagLocation> DoFindLocationsOfCurrentUser(InMemoryUser user, ApplicationMetadata application)
        {
            var userLocation = user.Genericproperties[HapagPersonGroupConstants.HlagLocationProperty] as UserHlagLocation;

            if (userLocation == null)
            {
                return(null);
            }
            var context      = _contextLookuper.LookupContext();
            var allLocations = FindAllLocations();

            if (context.IsInModule(FunctionalRole.Tom) || context.IsInModule(FunctionalRole.Itom))
            {
                if (application.Name.Equals("imac") && application.Schema.SchemaId.Equals("decommission"))
                {
                    return(allLocations.Where(a => a.SubCustomer.EqualsAny(ISMConstants.DefaultCustomerName, ISMConstants.HamburgLocation2)));
                }

                return(allLocations);
            }

            if (context.IsInModule(FunctionalRole.XItc))
            {
                if (user.IsWWUser())
                {
                    return(allLocations);
                }
                return(userLocation.GroupedLocationsFromParent);
            }
            if (context.IsInModule(FunctionalRole.AssetControl))
            {
                return(allLocations);
            }
            if (context.IsInModule(FunctionalRole.AssetRamControl))
            {
                return(FindLocationsOfParentLocation(new PersonGroup {
                    Name = HapagPersonGroupConstants.HapagRegionAmerica
                }));
            }
            return(userLocation.DirectGroupedLocations);
        }
 public virtual SynchronizationApplicationData Sync(ApplicationMetadata applicationMetadata, SynchronizationRequestDto.ApplicationSyncData applicationSyncData)
 {
     return(_maximoConnectorEngine.Sync(applicationMetadata, applicationSyncData));
 }
 public static ApplicationCommand GetApplicationCommand(ApplicationMetadata applicationMetadata, string commandId)
 {
     return(applicationMetadata.Schema.CommandSchema.Commands.FirstOrDefault(x => x.Id == commandId));
 }
 public LookupAssociationUpdateResult(int totalCount, int pageNumber, int pageSize,
                                      IEnumerable <IAssociationOption> associationData, ApplicationMetadata associationMetadata, List <int> paginationOptions)
     : base(associationData)
 {
     _pageResultDto = new PaginatedSearchRequestDto(totalCount, pageNumber, pageSize, null, paginationOptions);
     if (associationMetadata != null)
     {
         _associationSchemaDefinition = associationMetadata.Schema;
     }
 }
示例#19
0
        private bool AddLoaderFile(
            TemporaryFolder temporaryFolder,
            ApplicationMetadata applicationMetadata,
            ZipArchive zipArchive,
            SemanticVersion newVersion,
            string applicationLocation,
            OSPlatform?intendedOs      = null,
            SemanticVersion?oldVersion = null,
            string?outputLocation      = null)
        {
            //TODO: See why this is making another .shasum file (but working)
            using var loaderLocation = temporaryFolder.CreateTemporaryFile(applicationMetadata.ApplicationName + ".exe");
            // ReSharper disable once LocalFunctionHidesMethod
            bool AddFile() => BinaryCreator.AddFile(
                zipArchive,
                loaderLocation.GetStream(FileMode.Open),
                applicationMetadata.ApplicationName + ".exe.load",
                false);

            //TODO: Grab metadata from .exe and drop it into Loader
            var iconLocation = Path.Combine(applicationLocation, "app.ico");

            iconLocation = File.Exists(iconLocation) ? iconLocation : null;

            var successful = LoaderCreator.CreateLoader(
                temporaryFolder,
                $"{newVersion.GetApplicationFolder()}\\{applicationMetadata.ApplicationName}.exe",
                iconLocation,
                loaderLocation.Location,
                applicationMetadata.ApplicationName,
                intendedOs);

            if (successful != LoadCreateStatus.Successful)
            {
                var canContinue = successful == LoadCreateStatus.UnableToCreate;
                _logger.Error("We wasn't able to create loader! (Going to fail file creation?: {0})", canContinue);
                return(canContinue);
            }
            if (oldVersion == null || !Directory.Exists(outputLocation))
            {
                return(AddFile());
            }

            //If we get here then we might also have the old loader, try to diff by using it
            foreach (var file in Directory.EnumerateFiles(outputLocation !, "*" + Extension))
            {
                if (string.IsNullOrWhiteSpace(file))
                {
                    _logger.Warning("We somehow got an entry for {0} which was nothing", outputLocation);
                    continue;
                }

                /*Don't try it with delta file, more then likely going to
                 * have diff loader itself and we can't work with that*/
                var fileName = Path.GetFileNameWithoutExtension(file);
                if (fileName.EndsWith("-delta") ||
                    fileName.ToVersion() != oldVersion)
                {
                    continue;
                }

                Stream?    stream = null;
                ZipArchive fileArch;
                try
                {
                    stream   = File.OpenRead(file);
                    fileArch = new ZipArchive(stream, ZipArchiveMode.Read);
                }
                catch (Exception e)
                {
                    stream?.Dispose();
                    _logger.Error(e);
                    continue;
                }

                //We want to grab the loader file
                var loaderFileIndex = fileArch.Entries.IndexOf(x => x?.Name == applicationMetadata.ApplicationName + ".exe.load");
                if (loaderFileIndex == -1)
                {
                    fileArch.Dispose();
                    continue;
                }

                var fileEntry = fileArch.Entries[loaderFileIndex];
                using var tmpFile = temporaryFolder.CreateTemporaryFile(Path.GetFileNameWithoutExtension(fileEntry.Name));
                fileEntry.ExtractToFile(tmpFile.Location, true);

                var deltaSuccessful =
                    AddDeltaFile(temporaryFolder,
                                 zipArchive,
                                 tmpFile.Location,
                                 loaderLocation.Location,
                                 extensionEnd: "load");
                if (!deltaSuccessful)
                {
                    _logger.Warning("Wasn't able to diff loader, just going to add the load in as normal");
                }
                fileArch.Dispose();
                return(deltaSuccessful || AddFile());
            }

            //If we get here then we can't do any kind of diff logic
            return(AddFile());
        }
        private async Task InstallAppLegacyV2(AppBundle bundle, IProgress <ProgressValue> progress = null)
        {
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            if (progress != null)
            {
                progress.Report(new ProgressValue("Removing previous install(s) of the app if they exist", 1));
            }
            ApplicationMetadata metaData = bundle.AppMetadata;
            UUID uuid = metaData.UUID;

            AppbankInstallResponse appbankInstallResponse = await RemoveAppByUUID(uuid);

            if (appbankInstallResponse.Success == false)
            {
                return;
            }

            if (progress != null)
            {
                progress.Report(new ProgressValue("Getting current apps", 20));
            }
            AppbankResponse appBankResult = await GetAppbankContentsAsync();

            if (appBankResult.Success == false)
            {
                throw new PebbleException("Could not obtain app list; try again");
            }
            AppBank appBank = appBankResult.AppBank;

            byte firstFreeIndex = 1;

            foreach (App app in appBank.Apps)
            {
                if (app.Index == firstFreeIndex)
                {
                    firstFreeIndex++;
                }
            }
            if (firstFreeIndex == appBank.Size)
            {
                throw new PebbleException("All app banks are full");
            }

            if (progress != null)
            {
                progress.Report(new ProgressValue("Transferring app to Pebble", 40));
            }

            if (await _pebble.PutBytesClient.PutBytes(bundle.App, TransferType.Binary, index: firstFreeIndex) == false)
            {
                throw new PebbleException("Failed to send application binary pebble-app.bin");
            }

            if (bundle.HasResources)
            {
                if (progress != null)
                {
                    progress.Report(new ProgressValue("Transferring app resources to Pebble", 60));
                }
                if (await _pebble.PutBytesClient.PutBytes(bundle.Resources, TransferType.Resources, index: firstFreeIndex) == false)
                {
                    throw new PebbleException("Failed to send application resources app_resources.pbpack");
                }
            }

            if (progress != null)
            {
                progress.Report(new ProgressValue("Adding app", 80));
            }
            await AddApp(firstFreeIndex);

            if (progress != null)
            {
                progress.Report(new ProgressValue("Done", 100));
            }
        }
示例#21
0
        public bool CreateDeltaPackage(
            ApplicationMetadata applicationMetadata,
            string newVersionLocation,
            SemanticVersion newVersion,
            string baseVersionLocation,
            SemanticVersion oldVersion,
            string outputFolder,
            string deltaUpdateLocation,
            OSPlatform?intendedOs    = null,
            Action <double>?progress = null)
        {
            if (!Directory.Exists(newVersionLocation) ||
                !Directory.Exists(baseVersionLocation))
            {
                _logger.Error("One of the folders don't exist, can't create delta update....");
                return(false);
            }

            _logger.Debug("Creating delta file");
            var zipArchive = CreateZipArchive(deltaUpdateLocation);
            var tempFolder = new TemporaryFolder(applicationMetadata.TempFolder);

            void Cleanup()
            {
                lock (zipArchive)
                {
                    zipArchive.Dispose();
                }
                tempFolder.Dispose();
                progress?.Invoke(1);
            }

            //Get all the files that are in the new version (Removing the Path so we only have the relative path of the file)
            var newVersionFiles = Directory.EnumerateFiles(newVersionLocation, "*", SearchOption.AllDirectories)
                                  .RemovePath(newVersionLocation).ToArray();

            //and get the files from the old version
            var baseVersionFiles = Directory.EnumerateFiles(baseVersionLocation, "*", SearchOption.AllDirectories)
                                   .RemovePath(baseVersionLocation).ToArray();

            //Find any files that are in both version and process them based on if they had any changes
            var sameFiles = newVersionFiles.Where(x => baseVersionFiles.Contains(x)).ToArray();
            var newFiles  = newVersionFiles.Where(x => !sameFiles.Contains(x)).ToArray();

            var progressReport = new ProgressReport(newFiles.Length + sameFiles.Length, progress);
            var deltaFiles     = new List <string>(sameFiles.Length);

            //First process any files that didn't change, don't even count them in the progress as it will be quick af
            _logger.Information("Processing files that are in both versions");
            foreach (var maybeDeltaFile in sameFiles)
            {
                _logger.Debug("Processing possible delta file {0}", maybeDeltaFile);
                var newFileLocation = Path.Combine(newVersionLocation, maybeDeltaFile);

                /*See if we got a delta file, if so then store it for
                 * processing after files that haven't changed*/
                if (IsDeltaFile(Path.Combine(baseVersionLocation, maybeDeltaFile),
                                newFileLocation))
                {
                    deltaFiles.Add(maybeDeltaFile);
                    continue;
                }

                //Add a pointer to the file that hasn't changed
                _logger.Debug("{0} hasn't changed, processing as unchanged file", maybeDeltaFile);

                using var fileStream = File.OpenRead(newFileLocation);
                if (AddSameFile(zipArchive, maybeDeltaFile, SHA256Util.CreateSHA256Hash(fileStream)))
                {
                    progressReport.ProcessedFile();
                    continue;
                }
                _logger.Warning("We wasn't able to add {0} as a file that was unchanged, adding as a \"new\" file",
                                maybeDeltaFile);

                //We wasn't able to add the file as a pointer, try to add it as a new file
                if (!AddNewFile(zipArchive, fileStream, maybeDeltaFile))
                {
                    //Hard bail if we can't even do that
                    _logger.Error("Wasn't able to process {0} as a new file as well, bailing", maybeDeltaFile);
                    Cleanup();
                    return(false);
                }
                progressReport.ProcessedFile();
            }

            //TODO: add "moved files"
            //Now process files that was added into the new version
            _logger.Information("Processing files that only exist in the new version");
            foreach (var newFile in newFiles)
            {
                _logger.Debug("Processing new file {0}", newFile);

                //Process new file
                using var fileStream = File.OpenRead(Path.Combine(newVersionLocation, newFile));
                if (AddNewFile(zipArchive, fileStream, newFile))
                {
                    progressReport.ProcessedFile();
                    continue;
                }

                //if we can't add it then hard fail, can't do anything to save this
                _logger.Error("Wasn't able to process new file, bailing");
                Cleanup();
                return(false);
            }

            //Now process files that changed
            var result = Parallel.ForEach(deltaFiles, (deltaFile, state) =>
            {
                var deltaFileLocation = Path.Combine(newVersionLocation, deltaFile);
                _logger.Debug("Processing changed file {0}", deltaFile);

                //Try to add the file as a delta file
                if (AddDeltaFile(tempFolder,
                                 zipArchive,
                                 Path.Combine(baseVersionLocation, deltaFile),
                                 deltaFileLocation,
                                 intendedOs,
                                 (pro) => progressReport.PartialProcessedFile(pro)))
                {
                    progressReport.ProcessedFile();
                    return;
                }

                //If we can't make the file as a delta file try to create it as a "new" file
                _logger.Warning("Wasn't able to make delta file, adding file as \"new\" file");
                using var fileStream = File.OpenRead(Path.Combine(newVersionLocation, deltaFileLocation));
                if (AddNewFile(zipArchive, fileStream, deltaFile))
                {
                    progressReport.ProcessedFile();
                    return;
                }

                //Hard bail if we can't even do that
                _logger.Error("Wasn't able to process file as a new file, bailing");
                Cleanup();
                state.Break();
            });

            //This will return false if something failed
            if (!result.IsCompleted)
            {
                return(false);
            }

            if (ShouldMakeLoader &&
                !AddLoaderFile(
                    tempFolder,
                    applicationMetadata,
                    zipArchive,
                    newVersion,
                    newVersionLocation,
                    intendedOs,
                    oldVersion,
                    outputFolder))
            {
                _logger.Error("Wasn't able to create loader for this application");
                Cleanup();
                return(false);
            }
            progressReport.ProcessedFile();

            //We have created the delta file if we get here, do cleanup and then report as success!
            _logger.Information("We are done with creating the delta file, cleaning up");
            Cleanup();
            return(true);
        }
示例#22
0
 public SynchronizationApplicationData Sync(ApplicationMetadata appMetadata, SynchronizationRequestDto.ApplicationSyncData applicationSyncData, SyncItemHandler.SyncedItemHandlerDelegate syncItemHandlerDelegate = null)
 {
     return(_syncHandler.Sync(appMetadata, applicationSyncData, syncItemHandlerDelegate));
 }
示例#23
0
        private async Task OnBinaryMessageReceived(WebSocketHandler handler, byte[] bytes, string conversationId, string watermark)
        {
            string replyMessage = null;

            // Convert speech to text
            try
            {
                using (var speechClient = new SpeechClient(this.speechPreference))
                {
                    speechClient.SubscribeToRecognitionResult(this.OnRecognitionResult);

                    // create an audio content and pass it a stream.
                    using (MemoryStream audioStream = new MemoryStream(bytes))
                    {
                        var deviceMetadata      = new DeviceMetadata(DeviceType.Near, DeviceFamily.Desktop, NetworkType.Wifi, OsName.Windows, "1607", "Dell", "T3600");
                        var applicationMetadata = new ApplicationMetadata("SampleApp", "1.0.0");
                        var requestMetadata     = new RequestMetadata(Guid.NewGuid(), deviceMetadata, applicationMetadata, "SampleAppService");

                        await speechClient.RecognizeAsync(new SpeechInput(PCMToWAV(audioStream), requestMetadata), this.cts.Token).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                //throw new DemoBotServiceException($"Convert text to speech failed: {e.Message}");
            }

            // await handler.SendMessage($"You said: {this.speechText}");

            if (!string.IsNullOrEmpty(speechText))
            {
                // Send text message to Bot Service
                await BotClientHelper.SendBotMessageAsync(this.directLineClient, conversationId, FromUserId, speechText);

                BotMessage botResponse = await BotClientHelper.ReceiveBotMessagesAsync(this.directLineClient, conversationId, watermark);

                replyMessage = botResponse.Text;
            }
            else
            {
                replyMessage = "Sorry, I don't understand.";
            }

            // Convert text to speech
            byte[] totalBytes;
            if (replyMessage.Contains("Music.Play"))
            {
                totalBytes = ((MemoryStream)SampleMusic.GetStream()).ToArray();
                await handler.SendBinary(totalBytes);
            }
            else
            {
                try
                {
                    var    authorizationProvider = new CognitiveServicesAuthorizationProvider(CognitiveSubscriptionKey);
                    string accessToken           = await authorizationProvider.GetAuthorizationTokenAsync();

                    var cortana = new Synthesize();
                    totalBytes = await cortana.Speak(CancellationToken.None, new Synthesize.InputOptions()
                    {
                        RequestUri = new Uri(Constants.SpeechSynthesisUrl),
                        Text       = replyMessage,
                        VoiceType  = Gender.Female,
                        Locale     = "en-US",
                        VoiceName  = "Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)",

                        // Service can return audio in different output format.
                        OutputFormat       = AudioOutputFormat.Riff16Khz16BitMonoPcm,
                        AuthorizationToken = "Bearer " + accessToken,
                    });

                    // convert the audio format and send back to client
                    WaveFormat   target    = new WaveFormat(8000, 16, 2);
                    MemoryStream outStream = new MemoryStream();
                    using (WaveFormatConversionStream conversionStream = new WaveFormatConversionStream(target, new WaveFileReader(new MemoryStream(totalBytes))))
                    {
                        WaveFileWriter.WriteWavFileToStream(outStream, conversionStream);
                        outStream.Position = 0;
                    }

                    handler.SendBinary(outStream.ToArray()).Wait();
                    outStream.Dispose();
                }
                catch (Exception e)
                {
                    throw new DemoBotServiceException($"Convert text to speech failed: {e.Message}");
                }
            }
        }
示例#24
0
 public override void OnApplicationMetadataChanged(ApplicationMetadata applicationMetadata)
 {
     Console.WriteLine("Metadata Changed");
 }
示例#25
0
        public async Task <IActionResult> CreateAndUploadData(int instanceOwnerId, Guid instanceId, string formId)
        {
            if (instanceOwnerId == 0 || instanceId == null || string.IsNullOrEmpty(formId) || Request.Body == null)
            {
                return(BadRequest("Missing parameter values: instanceOwnerId, instanceId, formId or file content cannot be null"));
            }

            // check if instance id exist and user is allowed to change the instance data
            Instance instance = await _instanceRepository.GetOneAsync(instanceId, instanceOwnerId);

            if (instance == null)
            {
                return(NotFound("Provided instanceId is unknown to platform storage service"));
            }

            // check metadata
            ApplicationMetadata appInfo = GetApplicationInformation(instance.ApplicationId);

            if (appInfo == null || !appInfo.Forms.Exists(f => f.Id.Equals(formId)))
            {
                if (appInfo == null)
                {
                    return(Forbid("Application Metadata is not registered for this applicationId"));
                }

                return(Forbid("Application metadata has not registered a form definition with this formId"));
            }

            DateTime creationTime = DateTime.UtcNow;

            Stream theStream       = null;
            string contentType     = null;
            string contentFileName = null;
            long   fileSize        = 0;

            if (MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                // Only read the first section of the mulitpart message.
                MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse(Request.ContentType);
                string boundary = MultipartRequestHelper.GetBoundary(mediaType, _defaultFormOptions.MultipartBoundaryLengthLimit);

                MultipartReader  reader  = new MultipartReader(boundary, Request.Body);
                MultipartSection section = await reader.ReadNextSectionAsync();

                theStream   = section.Body;
                contentType = section.ContentType;

                bool hasContentDisposition = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition);

                if (hasContentDisposition)
                {
                    contentFileName = contentDisposition.FileName.ToString();
                    fileSize        = contentDisposition.Size ?? 0;
                }
            }
            else
            {
                theStream   = Request.Body;
                contentType = Request.ContentType;
            }

            if (theStream == null)
            {
                return(BadRequest("No data attachements found"));
            }

            string dataId = Guid.NewGuid().ToString();

            string dataLink = $"{prefix}/instances/{instanceId}/data/{dataId}";

            // create new data element, store data in blob
            Data newData = new Data
            {
                // update data record
                Id                  = dataId,
                FormId              = formId,
                ContentType         = contentType,
                CreatedBy           = User.Identity.Name,
                CreatedDateTime     = creationTime,
                FileName            = contentFileName ?? $"{dataId}.xml",
                LastChangedBy       = User.Identity.Name,
                LastChangedDateTime = creationTime,
                Link                = dataLink,
                FileSize            = fileSize
            };

            string filePath = DataFileName(instance.ApplicationId, instanceId.ToString(), newData.Id.ToString());

            newData.StorageUrl = filePath;

            if (instance.Data == null)
            {
                instance.Data = new List <Data>();
            }

            instance.Data.Add(newData);

            try
            {
                // store file as blob
                await _dataRepository.CreateDataInStorage(theStream, filePath);
            }
            catch (Exception e)
            {
                return(StatusCode(500, $"Unable to create instance data in storage: {e}"));
            }

            try
            {
                // update instance
                Instance result = await _instanceRepository.UpdateInstanceInCollectionAsync(instanceId, instance);

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(StatusCode(500, $"Unable to store instance in storage: {e}"));
            }
        }
示例#26
0
 public CrudOperationData([CanBeNull] string id, [NotNull] IDictionary <string, object> attributes,
                          [NotNull] IDictionary <string, object> associationAttributes, EntityMetadata metadata, ApplicationMetadata applicationMetadata)
     : base(id, attributes, associationAttributes, metadata)
 {
     Id                  = id;
     EntityMetadata      = metadata;
     ApplicationMetadata = applicationMetadata;
 }
        private void HandleAttachmentAndScreenshot(CrudOperationData data, object maximoObj, ApplicationMetadata applicationMetadata)
        {
            // Check if Attachment is present
            var attachmentString = data.GetUnMappedAttribute("newattachment");
            var attachmentPath   = data.GetUnMappedAttribute("newattachment_path");

            _attachmentHandler.HandleAttachments(maximoObj, attachmentString, attachmentPath, applicationMetadata);

            // Check if Screenshot is present
            var screenshotString = data.GetUnMappedAttribute("newscreenshot");
            var screenshotName   = data.GetUnMappedAttribute("newscreenshot_path");

            _screenshotHandler.HandleScreenshot(maximoObj, screenshotString, screenshotName, applicationMetadata);
        }
示例#28
0
        public ApplicationMetadata GetApplicationMetadata()
        {
            string KeePassVersion;
            bool IsMono = false;
            string NETCLR;
            string NETversion;
            string MonoVersion = "unknown";
            // No point in outputting KeePassRPC version here since we know it has
            // to match in order to be able to call this function

            NETCLR = Environment.Version.Major.ToString();
            KeePassVersion = PwDefs.VersionString;

            Type type = Type.GetType("Mono.Runtime");
            if (type != null)
            {
                IsMono = true;
                NETversion = "";
                try
                {
                    MethodInfo displayName = type.GetMethod("GetDisplayName",
                        BindingFlags.NonPublic | BindingFlags.Static);
                    if (displayName != null)
                        MonoVersion = (string)displayName.Invoke(null, null);
                }
                catch (Exception)
                {
                    MonoVersion = "unknown";
                }
            }
            else
            {
                // Normally looking in the registry is the thing to try here but that means pulling
                // in lots of Win32 libraries into Mono so this alternative gets us some useful,
                // albeit incomplete, information. There shouldn't be any need to call this service
                // on a regular basis so it shouldn't matter that the use of reflection is a little inefficient

                // v3.0 is of no interest to us and difficult to detect so we ignore
                // it and bundle those users in the v2 group
                NETversion =
                    IsNet451OrNewer() ? "4.5.1" :
                    IsNet45OrNewer() ? "4.5" :
                    NETCLR == "4" ? "4.0" :
                    IsNet35OrNewer() ? "3.5" :
                    NETCLR == "2" ? "2.0" :
                    "unknown";
            }

            ApplicationMetadata appMetadata = new ApplicationMetadata(KeePassVersion, IsMono, NETCLR, NETversion, MonoVersion);
            return appMetadata;
        }
 protected override void HandleLongDescription(ServiceIncident webServiceObject, CrudOperationData entity, ApplicationMetadata metadata, bool update)
 {
     base.HandleLongDescription(webServiceObject, entity, metadata, update);
     if (!update)
     {
         webServiceObject.Problem.Description = ImacDescriptionHandler.BuildDescription(entity, metadata);
         if (metadata.Schema.SchemaId.StartsWith("install"))
         {
             var costcenter = entity.GetAttribute("costcenter") as string;
             if (costcenter != null)
             {
                 webServiceObject.Problem.Abstract += ("//" + costcenter.Split('/')[1]);
             }
         }
     }
     else
     {
         webServiceObject.Problem.Abstract = entity.GetAttribute("description") as string;
     }
 }
        protected override void HandleLongDescription(ServiceIncident webServiceObject, CrudOperationData entity, ApplicationMetadata metadata, bool update)
        {
            var problem = webServiceObject.Problem;

            problem.Description = HapagChangeHandler.ParseSchemaBasedLongDescription(entity, metadata.Schema.SchemaId);
        }
示例#31
0
 protected UpdateClient(IUpdateApplier updateApplier)
 {
     UpdateApplier = updateApplier;
     AppMetadata   = new ApplicationMetadata();
     Logger        = LoggingCreator.CreateLogger(GetType().Name);
 }
示例#32
0
 public HelpTextWriter(ApplicationMetadata metadata, IConsole console)
 {
     _metadata = metadata;
     _console  = console;
 }
        //TODO: add locale,and format options
        public IDictionary <string, BaseAssociationUpdateResult> BuildAssociationOptions(AttributeHolder dataMap, ApplicationMetadata application, IAssociationPrefetcherRequest request)
        {
            var associationsToFetch = AssociationHelper.BuildAssociationsToPrefetch(request, application.Schema);

            if (associationsToFetch.IsNone)
            {
                return(new Dictionary <string, BaseAssociationUpdateResult>());
            }


            IDictionary <string, BaseAssociationUpdateResult> associationOptionsDictionary = new ConcurrentDictionary <string, BaseAssociationUpdateResult>();
            var before = LoggingUtil.StartMeasuring(Log, "starting association options fetching for application {0} schema {1}", application.Name, application.Schema.Name);

            var associations = application.Schema.Associations;
            var tasks        = new List <Task>();
            var ctx          = ContextLookuper.LookupContext();

            #region associations

            foreach (var applicationAssociation in associations)
            {
                if (!associationsToFetch.ShouldResolve(applicationAssociation.AssociationKey))
                {
                    Log.Debug("ignoring association fetching: {0}".Fmt(applicationAssociation.AssociationKey));
                    continue;
                }

                //only resolve the association options for non lazy associations or lazy loaded with value set.
                SearchRequestDto search;
                if (!applicationAssociation.IsLazyLoaded())
                {
                    search = new SearchRequestDto();
                }
                else if (dataMap != null && dataMap.GetAttribute(applicationAssociation.Target) != null)
                {
                    //if the field has a value, fetch only this single element, for showing eventual extra label fields... ==> lookup with a selected value
                    search = new SearchRequestDto();
                    var toAttribute    = applicationAssociation.EntityAssociation.PrimaryAttribute().To;
                    var prefilledValue = dataMap.GetAttribute(applicationAssociation.Target).ToString();
                    search.AppendSearchEntry(toAttribute, prefilledValue);
                }
                else
                {
                    //lazy association with no default value
                    continue;
                }
                var association = applicationAssociation;

                tasks.Add(Task.Factory.NewThread(c => {
                    //this will avoid that one thread impacts any other, for ex: changing metadataid of the query
                    var perThreadContext = ctx.ShallowCopy();
                    Quartz.Util.LogicalThreadContext.SetData("context", perThreadContext);
                    var associationOptions = _associationOptionResolver.ResolveOptions(application, dataMap, association, search);
                    associationOptionsDictionary.Add(association.AssociationKey, new BaseAssociationUpdateResult(associationOptions));
                }, ctx));
            }
            #endregion

            #region optionfields
            foreach (var optionField in application.Schema.OptionFields)
            {
                if (!associationsToFetch.ShouldResolve(optionField.AssociationKey))
                {
                    Log.Debug("ignoring association fetching: {0}".Fmt(optionField.AssociationKey));
                    continue;
                }

                if (optionField.ProviderAttribute == null)
                {
                    //if there´s no provider, there´s nothing to do --> static list
                    continue;
                }
                var field = optionField;
                tasks.Add(Task.Factory.NewThread(c => {
                    Quartz.Util.LogicalThreadContext.SetData("context", c);
                    var associationOptions = _dynamicOptionFieldResolver.ResolveOptions(application, field, dataMap);
                    if (associationOptionsDictionary.ContainsKey(field.AssociationKey))
                    {
                        associationOptionsDictionary.Remove(field.AssociationKey);
                    }
                    associationOptionsDictionary.Add(field.AssociationKey, new BaseAssociationUpdateResult(associationOptions));
                }, ctx));
            }
            #endregion

            Task.WaitAll(tasks.ToArray());
            if (Log.IsDebugEnabled)
            {
                var keys = String.Join(",", associationOptionsDictionary.Keys.Where(k => associationOptionsDictionary[k].AssociationData != null));
                Log.Debug(LoggingUtil.BaseDurationMessageFormat(before, "Finished execution of options fetching. Resolved collections: {0}", keys));
            }


            return(associationOptionsDictionary);
        }