JsonConvert 的摘要说明,easyui中使用
Ejemplo n.º 1
0
        protected override async Task OnRequestAsync(StratumClient client,
            Timestamped<JsonRpcRequest> tsRequest, CancellationToken ct)
        {
            var request = tsRequest.Value;

            try
            {
                switch(request.Method)
                {
                    case BitcoinStratumMethods.Subscribe:
                        await OnSubscribeAsync(client, tsRequest);
                        break;

                    case BitcoinStratumMethods.Authorize:
                        await OnAuthorizeAsync(client, tsRequest, ct);
                        break;

                    case BitcoinStratumMethods.SubmitShare:
                        await OnSubmitAsync(client, tsRequest, ct);
                        break;

                    case BitcoinStratumMethods.SuggestDifficulty:
                        await OnSuggestDifficultyAsync(client, tsRequest);
                        break;

                    case BitcoinStratumMethods.MiningConfigure:
                        await OnConfigureMiningAsync(client, tsRequest);
                        // ignored
                        break;

                    case BitcoinStratumMethods.GetTransactions:
                        // ignored
                        break;

                    case BitcoinStratumMethods.ExtraNonceSubscribe:
                        // ignored
                        break;

                    case BitcoinStratumMethods.MiningMultiVersion:
                        // ignored
                        break;

                    default:
                        logger.Debug(() => $"[{client.ConnectionId}] Unsupported RPC request: {JsonConvert.SerializeObject(request, serializerSettings)}");

                        await client.RespondErrorAsync(StratumError.Other, $"Unsupported request {request.Method}", request.Id);
                        break;
                }
            }

            catch(StratumException ex)
            {
                await client.RespondErrorAsync(ex.Code, ex.Message, request.Id, false);
            }
        }
Ejemplo n.º 2
0
        public BundleContainer Load()
        {
            var b = JsonConvert.DeserializeObject <BundleContainer>(System.IO.File.ReadAllText(HostingEnvironment.MapPath("~/bundles/bundles.json")));

            return(b);
        }
Ejemplo n.º 3
0
 public static T AsModel<T>(this string input)
 {
     return JsonConvert.DeserializeObject<T>(input);
 }
        private void OnContext(IAsyncResult ar)
        {
            var context = _httpListener.EndGetContext(ar);

            _httpListener.BeginGetContext(OnContext, null);
            var request = context.Request;

            var requestUrl = new Uri(context.Request.Url.ToString().ToLower());
            var list       = requestUrl.LocalPath.Split("/").Where(s => !string.IsNullOrEmpty(s))
                             .Take(2)
                             .ToList();

            var readingResource = request.HttpMethod == "GET";

            if (list.Count == 2)
            {
                if (!readingResource)
                {
                    var resource = list[0] + "/" + list[1];
                    RemoveCacheByPattern("*" + resource + "*");
                    Console.WriteLine("Invalidating cache for " + resource + " because of method : " + request.HttpMethod);
                }
            }

            var redisKey = requestUrl.PathAndQuery;

            if (readingResource &&
                _connectionMultiplexer.GetDatabase(0).KeyExists(redisKey))
            {
                Console.WriteLine("Returning cached request.");
                var content        = _connectionMultiplexer.GetDatabase(0).StringGet(redisKey);
                var cachedResponse = JsonConvert.DeserializeObject <CachedResponse>(content);

                CopyHelper.CopyHeaders(CopyHelper.ToNameValueCollection(cachedResponse.Headers), context.Response.Headers);
                CopyHelper.CopyResponse(context.Response, cachedResponse.Body, cachedResponse.Body.Length);
            }
            else
            {
                var uri = GetRedirectUri(request);

                Console.WriteLine($"Received a request. Redirecting to {uri}");
                var webRequest = WebRequest.Create(uri);
                CopyHelper.CopyRequestDetails(webRequest, request);
                CopyHelper.CopyHeaders(request.Headers, webRequest.Headers);
                CopyHelper.CopyInputStream(webRequest, request);

                var webResponse = webRequest.GetResponse();


                byte[] buffer = new byte[CopyHelper.BufferSize];
                var    read   = webResponse.GetResponseStream().Read(buffer, 0, buffer.Length);

                CopyHelper.CopyHeaders(webResponse.Headers, context.Response.Headers);
                CopyHelper.CopyResponse(context.Response, buffer, read);

                if (readingResource)
                {
                    var serializeObject = JsonConvert.SerializeObject(new CachedResponse
                    {
                        Body    = buffer.Take(read).ToArray(),
                        Headers = CopyHelper.ToDictionary(webResponse.Headers)
                    });
                    _connectionMultiplexer.GetDatabase(0).StringSet(redisKey, serializeObject);
                }
            }
        }
Ejemplo n.º 5
0
 public static void Set<T>(this ISession session, string key, T value)
 {
     session.SetString(key, JsonConvert.SerializeObject(value));
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Returns the JSON string presentation of the object
 /// </summary>
 /// <returns>JSON string presentation of the object</returns>
 public string ToJson()
 {
     return(JsonConvert.SerializeObject(this, Formatting.Indented));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// 权限管理-保存角色和授权菜单以及功能
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<string>> SaveAuthorization(List<SysMenuDto> list, string roleGuid)
        {
            var res = new ApiResult<string>() { statusCode = (int)ApiEnum.Error };
            try
            {
                if (list.Count == 0 && string.IsNullOrEmpty(roleGuid))
                {
                    res.message = ApiEnum.ParameterError.GetEnumText();
                    return res;
                }
                //查询有有数据的菜单
                var newList = new List<SysMenuDto>();
                foreach (var item in list)
                {
                    if (item.isChecked)
                    {
                        newList.Add(item);
                    }
                }
                if (newList.Count == 0)
                {
                    res.message = ApiEnum.ParameterError.GetEnumText();
                    return res;
                }
                //构建新的保存数组
                var dbList = new List<SysPermissions>();
                foreach (var item in newList)
                {
                    var btnFun = "";
                    if (item.btnFun != null && item.btnFun.Count > 0)
                    {
                        //查询授权status=true
                        var btnList = item.btnFun.Where(m => m.status).Select(m => m.guid).ToList();
                        if (btnList.Count > 0)
                        {
                            btnFun = JsonConvert.SerializeObject(btnList);
                        }
                    }
                    dbList.Add(new SysPermissions()
                    {
                        RoleGuid = roleGuid,
                        MenuGuid = item.guid,
                        BtnFunJson = btnFun,
                        Types = 1
                    });
                }

                using var tran = new System.Transactions.TransactionScope();

                //根据角色删除已有的,添加新的
                var count_delete = await Db.Deleteable<SysPermissions>().Where(m => m.RoleGuid == roleGuid && m.Types == 1).ExecuteCommandAsync();
                //增加新的
                var count_insert = await Db.Insertable(dbList).ExecuteCommandAsync();

                tran.Complete();

                res.statusCode = (int)ApiEnum.Status;
            }
            catch (Exception ex)
            {
                res.message = ex.Message;
                Logger.Default.ProcessError((int)ApiEnum.Error, ex.Message);
            }
            return res;
        }
        /// <summary>
        /// 登录获取 Cookie
        /// </summary>
        /// <param name="email"></param>
        /// <param name="passWord"></param>
        /// <param name="host"></param>
        public static DataResult <CookieContainer> Login(string email, string passWord, string host)
        {
            var cookie = new CookieContainer();

            var result = new DataResult <CookieContainer>();

            var jumpsTimes = 0;

Jumps:

            var param = $"userName={email}&password={passWord}&code=&clientNo=&userToken=&clientType=2";

            var dataResult = RequestFactory.QueryRequest("http://qiye.zhaopingou.com/zhaopingou_interface/security_login?timestamp=" + BaseFanctory.GetUnixTimestamp(), param, RequestEnum.POST, cookie, host: host);

            if (!dataResult.IsSuccess)
            {
                result.IsSuccess = false;

                result.ErrorMsg = $"用户登录异常!异常用户:{email}";

                return(result);
            }

            var jObject = JsonConvert.DeserializeObject(dataResult.Data) as JObject;

            if (jObject != null)
            {
                if ((int)jObject["errorCode"] != 1)
                {
                    ++jumpsTimes;

                    if (jumpsTimes > 1)
                    {
                        if (((string)jObject["message"]).Contains("用户不存在"))
                        {
                            using (var db = new ResumeMatchDBEntities())
                            {
                                var user = db.User.FirstOrDefault(f => f.Email == email);

                                if (user != null)
                                {
                                    user.IsEnable = false;

                                    db.TransactionSaveChanges();
                                }
                            }
                        }

                        result.IsSuccess = false;

                        result.ErrorMsg = $"用户登录异常!异常用户:{email},异常信息:{(string)jObject["message"]}";

                        return(result);
                    }

                    goto Jumps;
                }

                cookie.Add(new Cookie {
                    Name = "hrkeepToken", Value = jObject["user"]?["user_token"].ToString(), Domain = ".zhaopingou.com"
                });

                cookie.Add(new Cookie {
                    Name = "zhaopingou_select_city", Value = "-1", Domain = ".zhaopingou.com"
                });

                result.Data = cookie;

                var retryCount = 0;

Retry:

                try
                {
                    RefreshFreeDownloadNumber(email, cookie, host);
                }
                catch (Exception ex)
                {
                    retryCount++;

                    if (retryCount < 2)
                    {
                        goto Retry;
                    }

                    LogFactory.Error($"刷新简历下载数异常!异常信息:{ex.Message} 堆栈信息:{ex.TargetSite}", MessageSubjectEnum.ZhaoPinGou);
                }


                return(result);
            }

            return(result);
        }
Ejemplo n.º 9
0
 private Response.Vault LoadVaultFixture()
 {
     return(JsonConvert.DeserializeObject <Response.Vault>(GetFixture("vault")));
 }
 public DeserializedObject Deserialize(byte[] buffer)
 {
     string ascii = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
     JObject jObject = JsonConvert.DeserializeObject<JObject>(ascii);
     return new NewtonsoftJsonObject(jObject);
 }
 public T Deserialize<T>(string json)
 {
     return JsonConvert.DeserializeObject<T>(json);
 }
 public byte[] Serialize<T>(T obj)
 {
     string json = JsonConvert.SerializeObject(obj);
     return Encoding.ASCII.GetBytes(json);
 }
Ejemplo n.º 13
0
        private void DoClient(TcpClient socket)
        {
            using (StreamReader sr = new StreamReader(socket.GetStream(), Encoding.GetEncoding("ISO-8859-1")))
                using (StreamWriter sw = new StreamWriter(socket.GetStream(), Encoding.GetEncoding("ISO-8859-1")))
                {
                    bool stop = false;

                    while (!stop)
                    {
                        string kommando = sr.ReadLine();
                        string kommando2;

                        if (kommando.Equals("HentAlle"))
                        {
                            foreach (var bog in bogList)
                            {
                                sw.WriteLine(JsonConvert.SerializeObject(bog));
                            }
                        }
                        else if (kommando.Equals("Hent"))
                        {
                            kommando2 = sr.ReadLine();

                            if (kommando2.Length == 13)
                            {
                                sw.WriteLine(bogList.Find(i => i.Isbn13 == kommando2));
                            }
                            else
                            {
                                sw.WriteLine("Forkert syntaks. Skriv /h for hjælp!");
                            }
                        }
                        else if (kommando.Equals("Gem"))
                        {
                            kommando2 = sr.ReadLine();

                            try
                            {
                                bogList.Add(JsonConvert.DeserializeObject <Bog>(kommando2));
                            }
                            catch (Exception e)
                            {
                                sw.WriteLine("Forkert syntaks. Skriv /h for hjælp!");
                            }
                        }
                        else if (kommando.Equals("STOP"))
                        {
                            stop = true;
                            socket.Close();
                            Environment.Exit(1);
                        }
                        else if (kommando.Equals("/h"))
                        {
                            sw.WriteLine("Mulige kommandoer:");
                            sw.WriteLine("HentAlle");
                            sw.WriteLine("- Henter alle bøger.");
                            sw.WriteLine("Hent");
                            sw.WriteLine("<<ISBN13>>");
                            sw.WriteLine("- Henter alle bestemt bog ud fra ISBN13.");
                            sw.WriteLine("Gem");
                            sw.WriteLine("<<bog som json>>");
                            sw.WriteLine("- Tilføjer/gemmer en bog, som skal formuleres i JSON format.");
                            sw.WriteLine("  Eksempel på JSON format:");
                            sw.WriteLine("  {\"Titel\":\"UML\",\"Forfatter\":\"Larman\",\"Sidetal\":654,\"Isbn13\":\"9780133594140\"}\r");
                        }
                        else
                        {
                            sw.WriteLine("Forkert syntaks. Skriv /h for hjælp!");
                        }

                        sw.Flush();
                    }
                }

            socket?.Close();
        }
Ejemplo n.º 14
0
        public async Task <AsyncJobState> CreateAsyncJobState(AsyncJob job)
        {
            AsyncJobState state = new AsyncJobState()
            {
                success = false,
                wait    = job.wait
            };

            if (state.wait <= 0)
            {
                state.wait = 5;
            }
            switch (job.type.ToLower())
            {
            case "athena":
            {
                state.type = "Athena";
                string sql = job.query;
                state.id = await awsAthenaAPI.StartQuery(sql);

                Console.WriteLine($"Athena Query:\n" + sql);
            }
            break;

            case "batch":
            {
                state.type = "Batch";
                string       json    = job.query;
                BatchPayload payload = JsonConvert.DeserializeObject <BatchPayload>(json);
                state.id = await awsBatchAPI.SubmitJobAndGetID(payload.name, payload.job, payload.queue, payload.parameters);

                Console.WriteLine($"Batch Job(Name -> {payload.name}, Job -> {payload.job}, Queue -> {payload.queue}\n" + JsonConvert.SerializeObject(payload.parameters));
            }
            break;
            }
            return(state);
        }
Ejemplo n.º 15
0
 public TestDoc CreateDocument <TestDoc>(string json) where TestDoc : IDocument
 {
     return(JsonConvert.DeserializeObject <TestDoc>(json));
 }
Ejemplo n.º 16
0
 public Task<string> SerializeToText(ICircuitDto circuitDto) {
     return Task.FromResult(JsonConvert.SerializeObject(circuitDto));
 }
Ejemplo n.º 17
0
        public IActionResult Verwijderd()
        {
            var bier = JsonConvert.DeserializeObject <Bier>((string)this.TempData["bier"]);

            return(View(bier));
        }
Ejemplo n.º 18
0
 public int GetHashCode(PatientViewModel obj)
 {
     return JsonConvert.SerializeObject(obj).GetHashCode();
 }
Ejemplo n.º 19
0
    protected override void Render(HtmlTextWriter writer)
    {
        if (OverrideRender)
        {
            StringBuilder sbOut = new StringBuilder();

            using (StringWriter swOut = new StringWriter(sbOut, CultureInfo.InvariantCulture))
            {
                UTF8Encoding enc = new UTF8Encoding(true);
                swOut.Write(Encoding.UTF8.GetString(enc.GetPreamble()));
                HtmlTextWriter htwOut = new HtmlTextWriter(swOut);
                base.Render(htwOut);
                string sOut = sbOut.ToString();

                string szTempPath  = Path.GetTempPath();
                string szFileRoot  = Guid.NewGuid().ToString();
                string szOutputHtm = szTempPath + szFileRoot + ".htm";
                string szOutputPDF = szTempPath + szFileRoot + ".pdf";

                File.WriteAllText(szOutputHtm, sbOut.ToString());

                const string szWkTextApp = "c:\\program files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";  // TODO: this needs to be in a config file
                string       szArgs      = PageOptions.WKHtmlToPDFArguments(szOutputHtm, szOutputPDF);

                Process p = null;
                using (p = new Process())
                {
                    try
                    {
                        p.StartInfo = new ProcessStartInfo(szWkTextApp, szArgs)
                        {
                            UseShellExecute = true
                        };                                                                                  // for some reason, wkhtmltopdf runs better in shell exec than without.

                        p.Start();

                        bool fResult = p.WaitForExit(120000);   // wait up to 2 minutes

                        if (!fResult || !File.Exists(szOutputPDF))
                        {
                            util.NotifyAdminEvent("Error saving PDF", String.Format(CultureInfo.CurrentCulture, "User: {0}\r\nOptions:\r\n{1}\r\n\r\nQuery:{2}\r\n",
                                                                                    CurrentUser.UserName,
                                                                                    JsonConvert.SerializeObject(PageOptions),
                                                                                    JsonConvert.SerializeObject(PrintOptions1.Options)), ProfileRoles.maskSiteAdminOnly);

                            Response.Redirect(Request.Url.PathAndQuery + (Request.Url.PathAndQuery.Contains("?") ? "&" : "?") + "pdfErr=1");
                        }
                        else
                        {
                            Page.Response.Clear();
                            Page.Response.ContentType = "application/pdf";
                            Response.AddHeader("content-disposition", String.Format(CultureInfo.CurrentCulture, @"attachment;filename=""{0}.pdf""", CurrentUser.UserFullName));
                            Response.WriteFile(szOutputPDF);
                            Page.Response.Flush();

                            // See http://stackoverflow.com/questions/20988445/how-to-avoid-response-end-thread-was-being-aborted-exception-during-the-exce for the reason for the next two lines.
                            Page.Response.SuppressContent = true;                      // Gets or sets a value indicating whether to send HTTP content to the client.
                            HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
                        }
                    }
                    catch (MyFlightbookException) { throw; }
                    finally
                    {
                        File.Delete(szOutputHtm);
                        File.Delete(szOutputPDF);

                        if (p != null && !p.HasExited)
                        {
                            p.Kill();
                        }
                    }
                }
            }
        }
        else
        {
            base.Render(writer);
        }
    }
Ejemplo n.º 20
0
 public bool Equals(PatientViewModel x, PatientViewModel y)
 {
     return JsonConvert.SerializeObject(x).Equals(JsonConvert.SerializeObject(y));
 }
Ejemplo n.º 21
0
        /// <summary>
        /// 用户授权角色
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> ToRoleAsync(SysPermissions parm, bool status)
        {
            var res = new ApiResult<string>
            {
                statusCode = 200,
                data = "1"
            };
            try
            {
                //处理用户授权
                var adminModel = new SysAdmin();
                if (parm.Types == 2)
                {
                    //处理用户授权
                    adminModel = await Db.Queryable<SysAdmin>().FirstAsync(m => m.Guid == parm.AdminGuid);
                }
                if (status)
                {
                    if (parm.Types == 2)
                    {
                        var roleModel = await Db.Queryable<SysRole>().FirstAsync(m => m.Guid == parm.RoleGuid);
                        var adminRoleList = adminModel.RoleList;
                        adminRoleList.Add(new AdminToRoleList()
                        {
                            guid = parm.RoleGuid,
                            name = roleModel.Name
                        });
                        var adminRole = JsonConvert.SerializeObject(adminRoleList.CurDistinct(p => p.guid));
                        //更新用户信息
                        await Db.Updateable<SysAdmin>().SetColumns(m => new SysAdmin()
                        {
                            RoleGuid = adminRole
                        }).Where(m => m.Guid == parm.AdminGuid).ExecuteCommandAsync();
                    }
                    //授权
                    var dbres = await Db.Insertable(new SysPermissions()
                    {
                        RoleGuid = parm.RoleGuid,
                        AdminGuid = parm.AdminGuid,
                        MenuGuid = parm.MenuGuid,
                        BtnFunJson = parm.BtnFunJson,
                        Types = parm.Types
                    }).ExecuteCommandAsync();

                    if (dbres == 0)
                    {
                        res.statusCode = (int)ApiEnum.Error;
                        res.message = "插入数据失败~";
                    }
                }
                else
                {
                    //取消授权
                    if (parm.Types == 2)
                    {
                        var adminRoleList = adminModel.RoleList;
                        //删除用户授权的角色
                        for (int i = 0; i < adminRoleList.Count; i++)
                        {
                            if (adminRoleList[i].guid == parm.RoleGuid)
                            {
                                adminRoleList.Remove(adminRoleList[i]);
                            }
                        }
                        //更新新的用户角色
                        var adminRole = JsonConvert.SerializeObject(adminRoleList);
                        await Db.Updateable<SysAdmin>().SetColumns(m => new SysAdmin()
                        {
                            RoleGuid = adminRole
                        }).Where(m => m.Guid == parm.AdminGuid).ExecuteCommandAsync();
                        //删除
                        await Db.Deleteable<SysPermissions>().Where(m => m.AdminGuid == parm.AdminGuid && m.RoleGuid == parm.RoleGuid && m.Types == 2).ExecuteCommandAsync();
                    }
                    if (parm.Types == 3)
                    {
                        //角色-菜单-按钮功能
                        await Db.Deleteable<SysPermissions>().Where(m => m.BtnFunJson == parm.BtnFunJson && m.RoleGuid == parm.RoleGuid && m.MenuGuid == parm.MenuGuid && m.Types == 3).ExecuteCommandAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                res.statusCode = (int)ApiEnum.Error;
                res.message = ApiEnum.Error.GetEnumText() + ex.Message;
                Logger.Default.ProcessError((int)ApiEnum.Error, ex.Message);
            }
            return res;
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Deserializza il JSON nello specifico .NET type
 /// </summary>
 /// <typeparam name="T">Classe dell'oggetto</typeparam>
 /// <param name="txt">Valore oggetto da serializzare</param>
 /// <returns></returns>
 public static T DeserializeObjectByText <T>(string txt)
 {
     return(JsonConvert.DeserializeObject <T>(txt));
 }
        public async Task<ActionResult> GetAuthorization(AuthorizationParameter parameter, string issuerName, string authenticatedSubject = null, double? authInstant = null)
        {
            var processId = Guid.NewGuid().ToString();
            _eventPublisher.Publish(new AuthorizationRequestReceived(Guid.NewGuid().ToString(), processId,  _payloadSerializer.GetPayload(parameter), 0));
            try
            {
                var client = await _authorizationCodeGrantTypeParameterValidator.ValidateAsync(parameter);
                ActionResult actionResult = null;
                _oauthEventSource.StartAuthorization(parameter.ClientId,
                    parameter.ResponseType,
                    parameter.Scope,
                    parameter.Claims == null ? string.Empty : parameter.Claims.ToString());
                if (client.RequirePkce)
                {
                    if (string.IsNullOrWhiteSpace(parameter.CodeChallenge) || parameter.CodeChallengeMethod == null)
                    {
                        throw new IdentityServerExceptionWithState(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheClientRequiresPkce, parameter.ClientId), parameter.State);
                    }
                }

                var responseTypes = _parameterParserHelper.ParseResponseTypes(parameter.ResponseType);
                var authorizationFlow = _authorizationFlowHelper.GetAuthorizationFlow(responseTypes, parameter.State);
                switch (authorizationFlow)
                {
                    case AuthorizationFlow.AuthorizationCodeFlow:
                        actionResult = await _getAuthorizationCodeOperation.Execute(parameter, client, issuerName, authenticatedSubject, authInstant);
                        break;
                    case AuthorizationFlow.ImplicitFlow:
                        actionResult = await _getTokenViaImplicitWorkflowOperation.Execute(parameter, client, issuerName, authenticatedSubject, authInstant);
                        break;
                    case AuthorizationFlow.HybridFlow:
                        actionResult = await _getAuthorizationCodeAndTokenViaHybridWorkflowOperation.Execute(parameter, client, issuerName, authenticatedSubject, authInstant);
                        break;
                }

                if (actionResult != null)
                {
                    var actionTypeName = Enum.GetName(typeof(TypeActionResult), actionResult.Type);
                    var actionName = string.Empty;
                    if (actionResult.Type == TypeActionResult.RedirectToAction)
                    {
                        var actionEnum = actionResult.RedirectInstruction.Action;
                        actionName = Enum.GetName(typeof(IdentityServerEndPoints), actionEnum);
                    }

                    var serializedParameters = actionResult.RedirectInstruction == null || actionResult.RedirectInstruction.Parameters == null ? String.Empty :
                        JsonConvert.SerializeObject(actionResult.RedirectInstruction.Parameters);
                    _oauthEventSource.EndAuthorization(actionTypeName,
                        actionName,
                        serializedParameters);
                }

                _eventPublisher.Publish(new AuthorizationGranted(Guid.NewGuid().ToString(), processId, _payloadSerializer.GetPayload(actionResult), 1));
                actionResult.ProcessId = processId;
                return actionResult;
            }
            catch(IdentityServerException ex)
            {
                _eventPublisher.Publish(new OAuthErrorReceived(Guid.NewGuid().ToString(), processId, ex.Code, ex.Message, 1));
                throw;
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Serializza l'oggetto in una stringa JSON
 /// </summary>
 /// <typeparam name="T">.NET type</typeparam>
 /// <param name="obj">Valore oggetto da serializzare</param>
 /// <returns></returns>
 public static string SerializeObject <T>(T obj)
 {
     return(JsonConvert.SerializeObject(obj));
 }
Ejemplo n.º 25
0
 public static T Get<T>(this ISession session, string key)
 {
     string value = session.GetString(key);
     return value == null ? default(T) :
         JsonConvert.DeserializeObject<T>(value);
 }
Ejemplo n.º 26
0
 public static string ToJson(this OpenDoTaModel self) => JsonConvert.SerializeObject(self, Converter.Settings);
 /// <summary>
 /// Returns the JSON string presentation of the object
 /// </summary>
 /// <returns>JSON string presentation of the object</returns>
 public virtual string ToJson()
 {
     return JsonConvert.SerializeObject(this, Formatting.Indented);
 }
Ejemplo n.º 28
0
 public string ToJson()
 {
     return(JsonConvert.SerializeObject(this));
 }
Ejemplo n.º 29
0
 public static IEnumerable<T> AsListModel<T>(this string input)
 {
     return JsonConvert.DeserializeObject<IEnumerable<T>>(input);
 }
        public static async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            var log = executionContext.GetLogger("SubmitEncodingJob");
            log.LogInformation("C# HTTP trigger function processed a request.");

            // Get request body data.
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var data = (RequestBodyModel)JsonConvert.DeserializeObject(requestBody, typeof(RequestBodyModel));

            // Return bad request if input asset name is not passed in
            if (data.InputAssetName == null && data.InputUrl == null)
            {
                return ResponseBadRequest(req, "Please pass asset name or input Url in the request body");
            }

            // Return bad request if input asset name is not passed in
            if (data.TransformName == null)
            {
                return ResponseBadRequest(req, "Please pass the transform name in the request body");
            }

            ConfigWrapper config = new(new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables() // parses the values from the optional .env file at the solution root
                .Build());

            IAzureMediaServicesClient client;
            try
            {
                client = await CreateMediaServicesClientAsync(config);
                log.LogInformation("AMS Client created.");
            }
            catch (Exception e)
            {
                if (e.Source.Contains("ActiveDirectory"))
                {
                    log.LogError("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
                }
                log.LogError($"{e.Message}");
                return ResponseBadRequest(req, e.Message);
            }

            // Set the polling interval for long running operations to 2 seconds.
            // The default value is 30 seconds for the .NET client SDK
            client.LongRunningOperationRetryTimeout = 2;

            // Creating a unique suffix so that we don't have name collisions if you run the sample
            // multiple times without cleaning up.
            string uniqueness = Guid.NewGuid().ToString().Substring(0, 13);
            string jobName = $"job-{uniqueness}";
            string outputAssetName = $"output-{uniqueness}";

            Transform transform;
            try
            {
                // Ensure that you have the encoding Transform.  This is really a one time setup operation.
                transform = await CreateEncodingTransform(client, log, config.ResourceGroup, config.AccountName, data.TransformName, data.BuiltInPreset);
                log.LogInformation("Transform retrieved.");
            }
            catch (Exception e)
            {
                log.LogError("Error when creating/getting the transform.");
                log.LogError($"{e.Message}");
                return ResponseBadRequest(req, e.Message);
            }

            Asset outputAsset;
            try
            {
                // Output from the job must be written to an Asset, so let's create one
                outputAsset = await CreateOutputAssetAsync(client, log, config.ResourceGroup, config.AccountName, outputAssetName, data.OutputAssetStorageAccount);
                log.LogInformation($"Output asset '{outputAssetName}' created.");
            }
            catch (Exception e)
            {
                log.LogError("Error when creating the output asset.");
                log.LogError($"{e.Message}");
                return ResponseBadRequest(req, e.Message);
            }

            // Job input prepration : asset or url
            JobInput jobInput;
            if (data.InputUrl != null)
            {
                jobInput = new JobInputHttp(files: new[] { data.InputUrl });
                log.LogInformation("Input is a Url.");
            }
            else
            {
                jobInput = new JobInputAsset(assetName: data.InputAssetName);
                log.LogInformation($"Input is asset '{data.InputAssetName}'.");
            }

            Job job;
            try
            {
                // Job submission to Azure Media Services
                job = await SubmitJobAsync(
                                           client,
                                           log,
                                           config.ResourceGroup,
                                           config.AccountName,
                                           data.TransformName,
                                           jobName,
                                           jobInput,
                                           outputAssetName
                                           );
                log.LogInformation($"Job '{jobName}' submitted.");
            }
            catch (Exception e)
            {
                log.LogError("Error when submitting the job.");
                log.LogError($"{e.Message}");
                return ResponseBadRequest(req, e.Message);
            }

            AnswerBodyModel dataOk = new()
            {
                OutputAssetName = outputAsset.Name,
                JobName = job.Name
            };
            return ResponseOk(req, dataOk);
        }