Exemplo n.º 1
0
        public void ProcessFile()
        {
            _log = new LoggerConfiguration()
                   .WriteTo.File($"logs\\{DateTime.UtcNow.ToString("yyyyMMdd-HHmm")}-{_inputVideoFileName}.log")
                   .WriteTo.Console()
                   .CreateLogger();

            _attributes = GetAttributes();
            _log.Information("Media attributes:{@attributes}", _attributes);

            _metadata = GetMetadata();
            _log.Information("Media tags:{@metadata}", _metadata.Text);

            _episode = new TvEpisode()
                       .Defaults()
                       .FromFileName(_inputVideoFileName)
                       .FromJsonMetadata(_metadata)
                       .FromMediaCenterAttributes(_attributes)
                       .FromDescription()
                       .FixTitleAndShowName()
                       .MapShowName(_appContext.ShowNameMap)
                       .SetSafeShowName().Log(_log, "Episode");

            _outputFileName = _episode.GetOutputFileName();
            _log.Information("Output file name:\"{OutputFileName}\"", _outputFileName);

            var outputFile = GetOutputFile(_inputVideoFileExtension);

            _log.Information("Output file:\"{OutputFile}\"", outputFile);

            if (File.Exists(outputFile) == false)
            {
                _log.Information("Copying input file \"{Input}\" to \"{Output}\"", _inputVideoFile, outputFile);

                if (_appContext.WhatIf == false)
                {
                    if (_appContext.CreateSymbolicLink)
                    {
                        NativeHelpers.CreateSymbolicFileLink(_inputVideoFile, outputFile);
                    }
                    else
                    {
                        File.Copy(_inputVideoFile, outputFile);
                    }
                    _log.Information("Finished copying input file \"{Input}\" to \"{Output}\"", _inputVideoFile, outputFile);
                }

                var thumbnailFile = GetOutputFile(".jpg");
                if (TryCreateThumbnailFile(thumbnailFile))
                {
                    _episode.ThumbnailFile = thumbnailFile;
                }

                NfoFileHandler();
            }
            else
            {
                _log.Information("Not processing input file because the output file already exists");
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Converts a content type to a jsonPayload object
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="isDeleted">if the item was deleted</param>
        /// <returns></returns>
        internal static JsonPayload FromContentType(IContentTypeBase contentType, bool isDeleted = false)
        {
            var contentTypeService = (ContentTypeService)ApplicationContext.Current.Services.ContentTypeService;
            var payload            = new JsonPayload
            {
                Alias           = contentType.Alias,
                Id              = contentType.Id,
                PropertyTypeIds = contentType.PropertyTypes.Select(x => x.Id).ToArray(),
                //either IContentType or IMediaType or IMemberType
                Type = (contentType is IContentType)
                    ? typeof(IContentType).Name
                    : (contentType is IMediaType)
                        ? typeof(IMediaType).Name
                        : typeof(IMemberType).Name,
                DescendantPayloads       = contentTypeService.GetDescendants(contentType).Select(x => FromContentType(x)).ToArray(),
                WasDeleted               = isDeleted,
                PropertyRemoved          = contentType.WasPropertyDirty("HasPropertyTypeBeenRemoved"),
                AliasChanged             = contentType.WasPropertyDirty("Alias"),
                PropertyTypeAliasChanged = contentType.PropertyTypes.Any(x => x.WasPropertyDirty("Alias")),
                IsNew = contentType.WasPropertyDirty("HasIdentity")
            };


            return(payload);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Dynamically retrieves deserialized object data, either from the remote URL or local cache
        /// </summary>
        /// <param name="remote_retrieval">Output variable specifying whether the data was retrieved from a remote source</param>
        /// <returns>Deserialized object data</returns>
        public T Get(out bool remote_retrieval)
        {
            this.Validate();
            JsonPayload <T> payload = new JsonPayload <T>(this.URL, this.LocalFileName, this.RootToken);

            return(payload.Get(out remote_retrieval));
        }
        /// <summary>
        /// Converts a content type to a jsonPayload object
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="isDeleted">if the item was deleted</param>
        /// <returns></returns>
        private static JsonPayload FromContentType(IContentTypeBase contentType, bool isDeleted = false)
        {
            var payload = new JsonPayload
            {
                Alias           = contentType.Alias,
                Id              = contentType.Id,
                PropertyTypeIds = contentType.PropertyTypes.Select(x => x.Id).ToArray(),
                //either IContentType or IMediaType or IMemberType
                Type = (contentType is IContentType)
                        ? typeof(IContentType).Name
                        : (contentType is IMediaType)
                        ? typeof(IMediaType).Name
                        : typeof(IMemberType).Name,
                DescendantPayloads = contentType.Descendants().Select(x => FromContentType(x)).ToArray(),
                WasDeleted         = isDeleted
            };
            //here we need to check if the alias of the content type changed or if one of the properties was removed.
            var dirty = contentType as IRememberBeingDirty;

            if (dirty != null)
            {
                payload.PropertyRemoved = dirty.WasPropertyDirty("HasPropertyTypeBeenRemoved");
                payload.AliasChanged    = dirty.WasPropertyDirty("Alias");
                payload.IsNew           = dirty.WasPropertyDirty("HasIdentity");
            }
            return(payload);
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (resultCase_ == ResultOneofCase.ParseError)
            {
                hash ^= ParseError.GetHashCode();
            }
            if (resultCase_ == ResultOneofCase.SerializeError)
            {
                hash ^= SerializeError.GetHashCode();
            }
            if (resultCase_ == ResultOneofCase.RuntimeError)
            {
                hash ^= RuntimeError.GetHashCode();
            }
            if (resultCase_ == ResultOneofCase.ProtobufPayload)
            {
                hash ^= ProtobufPayload.GetHashCode();
            }
            if (resultCase_ == ResultOneofCase.JsonPayload)
            {
                hash ^= JsonPayload.GetHashCode();
            }
            if (resultCase_ == ResultOneofCase.Skipped)
            {
                hash ^= Skipped.GetHashCode();
            }
            hash ^= (int)resultCase_;
            return(hash);
        }
        public async Task <IActionResult> Validate([FromBody] ValidationItem validationItem)
        {
            if (string.IsNullOrEmpty(validationItem.YAML))
            {
                return(BadRequest("YAML Required"));
            }

            var escapedYaml = validationItem.YAML.Replace('"', '\"');

            var personalaccesstoken = !string.IsNullOrEmpty(validationItem.PAT) ? validationItem.PAT : Environment.GetEnvironmentVariable("PAT");

            var client = _clientFactory.CreateClient();

            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                       Convert.ToBase64String(
                                                                                           Encoding.ASCII.GetBytes(
                                                                                               string.Format("{0}:{1}", "", personalaccesstoken))));

            JsonPayload payload = new JsonPayload();

            payload.YamlOverride = escapedYaml;


            if (!string.IsNullOrEmpty(validationItem.ProjectUrl) && !validationItem.ProjectUrl.EndsWith("/"))
            {
                validationItem.ProjectUrl = validationItem.ProjectUrl + "/";
            }

            var pipelineUrl = !string.IsNullOrEmpty(validationItem.ProjectUrl) && !string.IsNullOrEmpty(validationItem.BuildDefinitionId) ?
                              validationItem.ProjectUrl + "_apis/pipelines/" + validationItem.BuildDefinitionId + "/runs?api-version=5.1-preview" :
                              Environment.GetEnvironmentVariable("PIPELINE_URL");

            using (var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"))
                using (HttpResponseMessage response = await client.PostAsync(pipelineUrl, content))
                {
                    string responseBody = await response.Content.ReadAsStringAsync();

                    if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(responseBody);
                        return(BadRequest(errorResponse.Message.Replace("/Pipelines/azure-pipeline.yaml:", "").Replace("/Pipelines/azure-pipeline.yaml", "")));
                    }

                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        return(BadRequest("Unable to find specified pipeline. Check that your project url, build definition id and PAT are valid and try again."));
                    }

                    if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation)
                    {
                        return(BadRequest("Invalid PAT or PAT not specified"));
                    }
                }


            return(Ok("Valid YAML Pipeline"));
        }
Exemplo n.º 7
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (payloadCase_ == PayloadOneofCase.ProtobufPayload)
            {
                hash ^= ProtobufPayload.GetHashCode();
            }
            if (payloadCase_ == PayloadOneofCase.JsonPayload)
            {
                hash ^= JsonPayload.GetHashCode();
            }
            if (RequestedOutputFormat != 0)
            {
                hash ^= RequestedOutputFormat.GetHashCode();
            }
            if (MessageType.Length != 0)
            {
                hash ^= MessageType.GetHashCode();
            }
            if (TestCategory != 0)
            {
                hash ^= TestCategory.GetHashCode();
            }
            hash ^= (int)payloadCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemplo n.º 8
0
        public string BaseLineWithJson([FromBody] JsonPayload payload)
        {
            string apiRequestStartTime = "";

            apiRequestStartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff");

            try
            {
                string strDockerName     = System.Environment.MachineName;
                string dtApiResponseTime = string.Empty;
                try
                {
                    DBUtility.WriteData(Guid.NewGuid().ToString(), "Hello-World", strDockerName, DateTime.Now.ToShortDateString(), apiRequestStartTime);
                }
                catch (Exception)
                {
                    throw;
                }

                return("Insert Successfull");
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 9
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (LogName.Length != 0)
            {
                hash ^= LogName.GetHashCode();
            }
            if (resource_ != null)
            {
                hash ^= Resource.GetHashCode();
            }
            if (payloadCase_ == PayloadOneofCase.ProtoPayload)
            {
                hash ^= ProtoPayload.GetHashCode();
            }
            if (payloadCase_ == PayloadOneofCase.TextPayload)
            {
                hash ^= TextPayload.GetHashCode();
            }
            if (payloadCase_ == PayloadOneofCase.JsonPayload)
            {
                hash ^= JsonPayload.GetHashCode();
            }
            if (timestamp_ != null)
            {
                hash ^= Timestamp.GetHashCode();
            }
            if (Severity != 0)
            {
                hash ^= Severity.GetHashCode();
            }
            if (InsertId.Length != 0)
            {
                hash ^= InsertId.GetHashCode();
            }
            if (httpRequest_ != null)
            {
                hash ^= HttpRequest.GetHashCode();
            }
            hash ^= Labels.GetHashCode();
            if (operation_ != null)
            {
                hash ^= Operation.GetHashCode();
            }
            if (Trace.Length != 0)
            {
                hash ^= Trace.GetHashCode();
            }
            if (sourceLocation_ != null)
            {
                hash ^= SourceLocation.GetHashCode();
            }
            hash ^= (int)payloadCase_;
            return(hash);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Converts a macro to a jsonPayload object
        /// </summary>
        /// <param name="macro"></param>
        /// <returns></returns>
        private static JsonPayload FromMacro(Macro macro)
        {
            var payload = new JsonPayload
            {
                Alias = macro.Alias,
                Id    = macro.Id
            };

            return(payload);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Converts a macro to a jsonPayload object
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        private static JsonPayload FromDataTypeDefinition(global::umbraco.cms.businesslogic.datatype.DataTypeDefinition dataType)
        {
            var payload = new JsonPayload
            {
                UniqueId = dataType.UniqueId,
                Id       = dataType.Id
            };

            return(payload);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Converts a macro to a jsonPayload object
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        private static JsonPayload FromDataTypeDefinition(IDataTypeDefinition dataType)
        {
            var payload = new JsonPayload
            {
                UniqueId = dataType.Key,
                Id       = dataType.Id
            };

            return(payload);
        }
Exemplo n.º 13
0
        public async void getMessage()
        {
            MessageQueue previousMq = new MessageQueue();

            while (true)
            {
                while (true)
                {
                    // gets a waitting messagequeue
                    _mq = await _http.getMessageQueue($"MessageQueues");

                    if (_mq != null && _mq.MessageId != previousMq.MessageId)
                    {
                        break;
                    }

                    Thread.Sleep(2000);
                }

                previousMq = _mq;
                JsonPayload jsonMessage = JsonConvert.DeserializeObject <JsonPayload>(_mq.DataObject);

                if (_mq.Function.Equals("pinCheck"))
                {
                    jsonMessage.Amount = 0;
                }

                String sMsg = JsonConvert.SerializeObject(jsonMessage);

                // replace all the characters because the central bank is too **** to handle
                // normal Json -.-
                sMsg = sMsg.Replace("\"", "\'");
                sMsg = sMsg.Replace("{", "\"{");
                sMsg = sMsg.Replace("}", "}\"");

                if (_mq != null)
                {
                    String msgToSend = $"[\"{jsonMessage.IDRecBank}\", {sMsg}]";

                    msgToSend = Regex.Replace(msgToSend, @"\t|\n|\r", "");

                    try
                    {
                        writeToFile($"Message sent: {msgToSend}");
                        // sends the message to the central bank
                        _master.Send(msgToSend);
                    }
                    catch (Exception ex)
                    {
                        // onerror
                        Helper.showMessage(ex.Message);
                    }
                }
            }
        }
Exemplo n.º 14
0
        public JsonResponse Post([FromBody] JsonPayload payload, [FromUri] string q)
        {
            if (payload == null)
            {
                return(new JsonResponse());
            }

            return(new JsonResponse
            {
                NoMarkup = payload.NoMarkup,
                WithMarkup = payload.WithMarkup,
                UrlParam = q
            });
        }
Exemplo n.º 15
0
        private JsonPayload GetMetadata()
        {
            if (_metadata is null)
            {
                _appContext.FfprobeCommand.GetMetadataAsJson(_inputVideoFile);

                if (String.IsNullOrEmpty(_appContext.FfprobeCommand.StandardOutput) == false)
                {
                    _metadata = new JsonPayload(_appContext.FfprobeCommand.StandardOutput);
                }
            }

            return(_metadata);
        }
Exemplo n.º 16
0
    void Start()
    {
        uiText = GameObject.Find("Text").GetComponent <Text>();
        DisplayMessage(statusText);

        var handlers = new List <string>()
        {
            HANDLER_A, HANDLER_B
        };
        var srLib = new SignalRLib(signalRHubURL, handlers, true);

        srLib.ConnectionStarted += (object sender, ConnectionEventArgs e) =>
        {
            Debug.Log(e.ConnectionId);
            DisplayMessage(connectedText);

            var json1 = new JsonPayload
            {
                message = messageToSendA
            };
            srLib.SendToHub(hubMethodA, JsonUtility.ToJson(json1));

            var json2 = new JsonPayload
            {
                message = messageToSendB
            };
            srLib.SendToHub(hubMethodB, JsonUtility.ToJson(json2));
        };

        srLib.HandlerInvoked += (object sender, HandlerEventArgs e) =>
        {
            var json = JsonUtility.FromJson <JsonPayload>(e.Payload);

            switch (e.HandlerName)
            {
            case HANDLER_A:
                DisplayMessage($"{HANDLER_A}: {json.message}");
                break;

            case HANDLER_B:
                DisplayMessage($"{HANDLER_B}: {json.message}");
                break;

            default:
                Debug.Log($"Handler: '{e.HandlerName}' not defined");
                break;
            }
        };
    }
Exemplo n.º 17
0
 private void WriteEvent(string eventName, EventMetadata metadata, ref EventSourceOptions options)
 {
     if (metadata != null)
     {
         JsonPayload payload = new JsonPayload(metadata);
         EventSource.SetCurrentThreadActivityId(this.activityId);
         this.EvtSource.Write(eventName, ref options, ref this.activityId, ref this.parentActivityId, ref payload);
     }
     else
     {
         EmptyStruct payload = new EmptyStruct();
         EventSource.SetCurrentThreadActivityId(this.activityId);
         this.EvtSource.Write(eventName, ref options, ref this.activityId, ref this.parentActivityId, ref payload);
     }
 }
Exemplo n.º 18
0
        /// <summary>
        /// Converts a macro to a jsonPayload object
        /// </summary>
        /// <param name="media"></param>
        /// <returns></returns>
        private static JsonPayload FromMedia(IMedia media)
        {
            if (media == null)
            {
                return(null);
            }

            var payload = new JsonPayload
            {
                Id   = media.Id,
                Path = media.Path
            };

            return(payload);
        }
        /// <summary>
        /// Converts a macro to a jsonPayload object
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        private static JsonPayload FromMemberGroup(IMemberGroup group)
        {
            if (group == null)
            {
                return(null);
            }

            var payload = new JsonPayload
            {
                Id   = group.Id,
                Name = group.Name
            };

            return(payload);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Converts a macro to a jsonPayload object
        /// </summary>
        /// <param name="media"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        internal static JsonPayload FromMedia(IMedia media, OperationType operation)
        {
            if (media == null)
            {
                return(null);
            }

            var payload = new JsonPayload
            {
                Id        = media.Id,
                Path      = media.Path,
                Operation = operation
            };

            return(payload);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Clears cache for an individual IContentTypeBase object
        /// </summary>
        /// <param name="payload"></param>
        /// <remarks>
        /// See notes for the other overloaded ClearContentTypeCache for
        /// full details on clearing cache.
        /// </remarks>
        /// <returns>
        /// Return true if the alias of the content type changed
        /// </returns>
        private static void ClearContentTypeCache(JsonPayload payload)
        {
            //clears the cache associated with the Content type itself
            ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(string.Format("{0}{1}", CacheKeys.ContentTypeCacheKey, payload.Id));
            //clears the cache associated with the content type properties collection
            ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheItem(CacheKeys.ContentTypePropertiesCacheKey + payload.Id);

            //clears the dictionary object cache of the legacy ContentType
            global::umbraco.cms.businesslogic.ContentType.RemoveFromDataTypeCache(payload.Alias);

            PublishedContentType.ClearContentType(payload.Id);

            //need to recursively clear the cache for each child content type
            foreach (var descendant in payload.DescendantPayloads)
            {
                ClearContentTypeCache(descendant);
            }
        }
Exemplo n.º 22
0
        public void LocalRetrieval()
        {
            // create dummy json file
            Directory.CreateDirectory("json");
            File.WriteAllText("json/PseudoChampion.json", TestJsonPayload.JSON_CHAMP);
            Assert.IsTrue(File.Exists("json/PseudoChampion.json"), "Missing JSON file");
            // instantiate json payload object
            JsonPayload <PseudoChampionInfo> payload = new JsonPayload <PseudoChampionInfo>(null, "PseudoChampion.json");
            // retrieve
            bool remote_retrieval       = false;
            PseudoChampionInfo champion = payload.Get(out remote_retrieval);

            // verify
            Assert.IsNotNull(champion, "Retrieval failed");
            Assert.IsFalse(remote_retrieval, "Remote retrieval detected (only local retrieval should be possible)");
            Assert.AreEqual(champion.Name, "Tristana", "Unexpected champion name");
            return;
        }
Exemplo n.º 23
0
    void Start()
    {
        uiText = GameObject.Find("Text").GetComponent <Text>();
        DisplayMessage(statusText);

        var signalR = new SignalR();

        signalR.Init(signalRHubURL);

        signalR.On(HANDLER_A, (string payload) =>
        {
            var json = JsonUtility.FromJson <JsonPayload>(payload);
            DisplayMessage($"{HANDLER_A}: {json.message}");
        });
        signalR.On(HANDLER_B, (string payload) =>
        {
            var json = JsonUtility.FromJson <JsonPayload>(payload);
            DisplayMessage($"{HANDLER_B}: {json.message}");
        });

        signalR.ConnectionStarted += (object sender, ConnectionEventArgs e) =>
        {
            Debug.Log($"Connected: {e.ConnectionId}");
            DisplayMessage(connectedText);

            var json1 = new JsonPayload
            {
                message = messageToSendA
            };
            signalR.Invoke(hubMethodA, JsonUtility.ToJson(json1));
            var json2 = new JsonPayload
            {
                message = messageToSendB
            };
            signalR.Invoke(hubMethodB, JsonUtility.ToJson(json2));
        };
        signalR.ConnectionClosed += (object sender, ConnectionEventArgs e) =>
        {
            Debug.Log($"Disconnected: {e.ConnectionId}");
            DisplayMessage(disconnectedText);
        };

        signalR.Connect();
    }
Exemplo n.º 24
0
        static async void handleCommand(WebSocket pSocket, String pCommand)
        {
            // handles the incoming commands
            writeToFile($"Message received: {pCommand}");

            // because the central bank is retarted i have to replace all characters....
            pCommand = pCommand.Replace("[", "");
            pCommand = pCommand.Replace("]", "");

            pCommand = pCommand.Replace("\'", "\"");
            pCommand = pCommand.Replace("\"{", "{");
            pCommand = pCommand.Replace("}\"", "}");

            pCommand = pCommand.Replace(",\"Amount\":null", "");
            pCommand = pCommand.Replace("\\", "");

            // converts the incoming json to usefull info
            JsonPayload recieveCommand = JsonConvert.DeserializeObject <JsonPayload>(pCommand);

            // checks if the credentials are valid
            int valid = await _http.httpGetRequest($"Authentication/{recieveCommand.PIN}/{recieveCommand.IBAN}");

            // the client wants to withdraw
            if (recieveCommand.Func.Equals("withdraw") && valid == 1)
            {
                int amount = Convert.ToInt32(recieveCommand.Amount);
                await _http.httpGetRequest($"Withdraw/{recieveCommand.IBAN}/ATM/{amount}/{recieveCommand.PIN}");

                writeToFile("Sent: [\"true\"]");
                pSocket.Send("[\"true\"]");
            }
            else if (recieveCommand.Func.Equals("pinCheck") && valid == 1)
            {
                // just login
                writeToFile("Sent: [\"true\"]");
                pSocket.Send("[\"true\"]");
            }
            else
            {
                writeToFile("Sent: [\"false\"]");
                pSocket.Send("[\"false\"]");
            }
        }
Exemplo n.º 25
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (payloadCase_ == PayloadOneofCase.ProtobufPayload)
            {
                hash ^= ProtobufPayload.GetHashCode();
            }
            if (payloadCase_ == PayloadOneofCase.JsonPayload)
            {
                hash ^= JsonPayload.GetHashCode();
            }
            if (RequestedOutputFormat != 0)
            {
                hash ^= RequestedOutputFormat.GetHashCode();
            }
            hash ^= (int)payloadCase_;
            return(hash);
        }
Exemplo n.º 26
0
        public void TestWriteIReadOnlyDictionary()
        {
            JsonSerializerOptions options = new JsonSerializerOptions().SetupExtensions();

            JsonPayload obj = new JsonPayload
            {
                Application = "MyApp",
                Details     = new Dictionary <string, string>
                {
                    ["Foo"] = "foo",
                    ["Bar"] = "bar"
                },
                Message = "MyMessage"
            };

            const string expectedJson = @"{""Application"":""MyApp"",""Details"":{""Foo"":""foo"",""Bar"":""bar""},""Message"":""MyMessage""}";
            string       actualJson   = JsonSerializer.Serialize(obj, options);

            Assert.Equal(expectedJson, actualJson);
        }
Exemplo n.º 27
0
        protected override void RecordMessageInternal(
            string eventName,
            Guid activityId,
            Guid parentActivityId,
            EventLevel level,
            Keywords keywords,
            EventOpcode opcode,
            string jsonPayload)
        {
            EventSourceOptions options = this.CreateOptions(level, keywords, opcode);

            EventSource.SetCurrentThreadActivityId(activityId);

            if (jsonPayload != null)
            {
                JsonPayload payload = new JsonPayload(jsonPayload);
                this.eventSource.Write(eventName, ref options, ref activityId, ref parentActivityId, ref payload);
            }
            else
            {
                EmptyStruct payload = new EmptyStruct();
                this.eventSource.Write(eventName, ref options, ref activityId, ref parentActivityId, ref payload);
            }
        }
    static void Main(string[] args)
    {
        JsonPayload payload = new JsonPayload
        {
            Item1  = "Value1",
            Item2  = "Value2",
            Fields = new List <JsonField>
            {
                new JsonField {
                    Key = "Key1", Value = "Value1", OtherParam = "other1"
                },
                new JsonField {
                    Key = "Key2", Value = 42, OtherParam = "other2"
                },
            }
        };
        JsonSerializerSettings settings = new JsonSerializerSettings();

        settings.Converters.Add(new JsonFieldListConverter());
        settings.Formatting = Formatting.Indented;
        string json = JsonConvert.SerializeObject(payload, settings);

        Console.WriteLine(json);
    }
Exemplo n.º 29
0
        public void ProcessFile()
        {
            _log = new LoggerConfiguration()
                   .WriteTo.File($"logs\\{DateTime.UtcNow.ToString("yyyyMMdd-HHmm")}-{_inputVideoFileName}.log")
                   .WriteTo.Console()
                   .CreateLogger();

            _attributes = GetAttributes();
            _log.Information("Media attributes:{@attributes}", _attributes);

            _metadata = GetMetadata();
            _log.Information("Media tags:{@metadata}", _metadata.Text);

            _episode = new TvEpisode()
                       .Defaults()
                       .FromFileName(_inputVideoFileName)
                       .FromJsonMetadata(_metadata)
                       .FromMediaCenterAttributes(_attributes)
                       .FromDescription()
                       .FixTitleAndShowName()
                       .SetSafeShowName().Log(_log, "Episode");

            _outputFileName = _episode.GetOutputFileName();
            _log.Information("Output file name:\"{OutputFileName}\"", _outputFileName);

            var outputFile = GetOutputFile(".mp4");

            _log.Information("Output file:\"{OutputFile}\"", outputFile);

            if (File.Exists(outputFile) == false)
            {
                var tempFile = GetTemporaryFile();
                _log.Information("Temporary file:\"{TempFile}\"", tempFile);

                bool tempFileCreated = false;
                bool tempFileExists  = File.Exists(tempFile);

                if (tempFileExists == false)
                {
                    tempFileCreated = tempFileExists = _appContext.WhatIf;

                    if (_appContext.WhatIf == false)
                    {
                        _appContext.FfmpegCommand.ConvertWtvToMp4File(_inputVideoFile, tempFile);
                        _log.Information("ConvertWtvToMp4File:{@ffmpeg}", _appContext.FfmpegCommand);

                        tempFileCreated = tempFileExists = _appContext.FfmpegCommand.ExitCode == 0 && File.Exists(tempFile);
                    }
                }
                else
                {
                    _log.Information("Not converting input file because the converted file already exists");
                }

                if (tempFileExists)
                {
                    var thumbnailFile = GetOutputFile(".jpg");
                    if (TryCreateThumbnailFile(thumbnailFile))
                    {
                        _episode.ThumbnailFile = thumbnailFile;
                    }

                    if (_appContext.WhatIf == false)
                    {
                        _appContext.AtomicParsleyCommand.SetMp4FileMetadata(_episode, tempFile, outputFile);
                        _log.Information("SetMp4FileMetadata:{@AtomicParsley}", _appContext.AtomicParsleyCommand);
                    }

                    NfoFileHandler();

                    if (_appContext.DeleteTempFile && tempFileCreated)
                    {
                        if (_appContext.WhatIf == false)
                        {
                            _log.Information("Deleting temporary file:\"{TempFile}\"", tempFile);
                            File.Delete(tempFile);
                        }
                    }
                }
            }
            else
            {
                _log.Information("Not processing input file because the output file already exists");
            }
        }