public async Task <_ <string> > CreateAuthCodeByOneTimeCode(string client_id, List <string> scope, string phone, string sms) { var data = new _ <string>(); var response = await client.PostAsJsonAsync(this._server.CreateCodeByOneTimeCode(), new { client_id = client_id, scope = scope?.ToJson(), phone = phone, sms = sms }); using (response) { var json = await response.Content.ReadAsStringAsync(); var code = json.JsonToEntity <_ <string> >(); if (!code.success || !ValidateHelper.IsPlumpString(code.data)) { data.SetErrorMsg(code.msg); return(data); } data.SetSuccessData(code.data); } return(data); }
/// <summary> /// 一致性hash /// </summary> /// <param name="nodes"></param> /// <param name="key"></param> /// <returns></returns> public static string GetConsistentHash(List<string> nodes, string key) { if (nodes.Count.Equals(0)) return string.Empty; var cacheKey = Sha1(nodes.ToJson()); var circle = LocalCache.Get<IDictionary<string, string>>(cacheKey); if (Equals(circle, null)) { circle = new Dictionary<string, string>(); const int virtualNodeCount = 150; foreach (var t in nodes) { for (var j = 0; j < virtualNodeCount; j++) { circle[Sha1(t + "_clone_" + j)] = t; } } LocalCache.Set(cacheKey, circle, DateTime.Now.AddDays(1)); } var order = circle.OrderBy(p => p.Key); var sha1 = Sha1(key); foreach (var item in order.Where(item => string.Compare(sha1, item.Key, StringComparison.Ordinal) <= 0)) { return item.Value; } return order.FirstOrDefault().Value; }
protected void buttonOk_Click(object sender, EventArgs e) { var id = Guid.Parse(v.Value); var list = new List<AssessItem>(); foreach (RepeaterItem item in repeater.Items) { var name = ((RadTextBox) item.FindControl("in_name")).Text; var value = ((RadNumericTextBox) item.FindControl("in_value")).Value; if (!string.IsNullOrWhiteSpace(name) && value.HasValue) { list.Add(new AssessItem { Name = name, Score = (decimal)value.Value }); } } var content = list.ToJson(); HomoryContext.Value.AssessTable.Where(o => o.Id == id).Update(o => new AssessTable { Content = content }); HomoryContext.Value.SaveChanges(); LogOp(OperationType.编辑); v.Value = string.Empty; items.Visible = false; grid.Rebind(); Notify(panel, "操作成功", "success"); }
/// <summary> /// 导出到JSON /// </summary> /// <param name="dataList"></param> /// <param name="filename"></param> /// <param name="settings"></param> private static void ExportToJson(List<BsonDocument> dataList, string filename, JsonWriterSettings settings) { var file = new FileStream(filename, FileMode.Create); var sw = new StreamWriter(file); sw.Write(dataList.ToJson(settings)); sw.Flush(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { time.SelectedDate = DateTime.Today; people.Items.Clear(); people.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem { Text = "", Value = "", Selected = true }); people.DataSource = DataContext.DepotUserLoad(Depot.CampusId).ToList(); people.DataBind(); counter.Value = "1"; if (!"ObjectId".Query().None()) { var objId = "ObjectId".Query().GlobalId(); var obj = DataContext.DepotObject.Single(o => o.Id == objId); var isVirtual = Depot.Featured(DepotType.固定资产库); var catalogId = DataContext.DepotObjectCatalog.Single(o => o.ObjectId == objId && o.IsLeaf == true && o.IsVirtual == isVirtual).CatalogId; var list = new List<InMemoryIn>(); list.Add(new InMemoryIn { Time = time.SelectedDate.HasValue ? time.SelectedDate.Value.Date : DateTime.Today, CatalogId = catalogId, ObjectId = objId }); x.Value = list.ToJson(); x1.Visible = x2.Visible= false; plus.Visible = false; back.Visible = true; } else { plus.Visible = true; back.Visible = false; } Detect(); } }
static void Main(string[] args) { Console.WriteLine(YF.Common.Tools.Sys.SysEnvironment.ReadOSVersion()); List<Person> jsonList = new List<Person>(); for (int i = 0; i < 10; i++) { Person person = new Person() { Name = "Name" + i, Age = i, IsMan = Convert.ToBoolean(i % 2), }; for (int j = 0; j < 10; j++) { Person children = new Person() { Name = "ChildName" + j, Age = i, IsMan = Convert.ToBoolean(i % 2), }; person.Children.Add(children); } jsonList.Add(person); } var json = jsonList.ToJson(); Console.WriteLine(json); List<Person> testList = json.JsonParseObject<List<Person>>(); Console.Write(testList.Count); Console.ReadLine(); }
private string ToJson(List<string> list) { if(list == null) { return null; } else { return list.ToJson(); } }
public HeartbeatEvent(List<HeartbeatBody> heartbeatBodies, Guid machId) { Area = "Architecture"; Action = "Collect"; Controller = "Heartbeat"; Param.Add("heartbeatBodys", heartbeatBodies.ToJson()); Param.Add("machineId", machId.ToString()); //HttpUrl = string.Format("http://{0}/Architecture/Heartbeat/Collect", SystemConst.PirateAddress); }
protected void view_NeedDataSource(object sender, Telerik.Web.UI.RadListViewNeedDataSourceEventArgs e) { var id = "BatchId".Query().GlobalId(); var items = DataContext.DepotCheck.Where(o => o.State == 1 && o.BatchId == id).ToList(); var checks = new List<InMemoryCheck>(); foreach (var item in items) { checks.AddRange(item.CodeJson.FromJson<List<InMemoryCheck>>()); } name.InnerText = "{0} 未盘列表({1})".Formatted(items[0].Name, checks.Count(o => o.In == false));// Formatted(items[0].Name, checks.Count, checks.Count(o => o.In == true), checks.Count(o => o.In == false)); view.DataSource = checks.Where(o => o.In == false).ToList(); h.Value = checks.ToJson(); }
public HttpResponseMessage Add( AddPostData postData ) { List<DiscountCode> discountCodes = new List<DiscountCode>(); foreach ( string code in postData.Codes.Split( new[] { "\n" }, StringSplitOptions.None ) ) { DiscountCode discountCode = new DiscountCode( postData.RuleId, code ) { MaxUses = postData.MaxUses }; discountCode.Save(); discountCodes.Add( discountCode ); } HttpResponseMessage response = Request.CreateResponse( HttpStatusCode.OK ); response.Content = new StringContent( discountCodes.ToJson(), Encoding.UTF8, "application/json" ); return response; }
private void ConvertSeasons(IDbConnection conn, IDbTransaction tran) { using (IDbCommand allSeriesCmd = conn.CreateCommand()) { allSeriesCmd.Transaction = tran; allSeriesCmd.CommandText = @"SELECT Id FROM Series"; using (IDataReader allSeriesReader = allSeriesCmd.ExecuteReader()) { while (allSeriesReader.Read()) { int seriesId = allSeriesReader.GetInt32(0); var seasons = new List<dynamic>(); using (IDbCommand seasonsCmd = conn.CreateCommand()) { seasonsCmd.Transaction = tran; seasonsCmd.CommandText = string.Format(@"SELECT SeasonNumber, Monitored FROM Seasons WHERE SeriesId = {0}", seriesId); using (IDataReader seasonReader = seasonsCmd.ExecuteReader()) { while (seasonReader.Read()) { int seasonNumber = seasonReader.GetInt32(0); bool monitored = seasonReader.GetBoolean(1); if (seasonNumber == 0) { monitored = false; } seasons.Add(new { seasonNumber, monitored }); } } } using (IDbCommand updateCmd = conn.CreateCommand()) { var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson() , seriesId); updateCmd.Transaction = tran; updateCmd.CommandText = text; updateCmd.ExecuteNonQuery(); } } } } }
// GET: WorkContent/WorkGroup public ActionResult Index(Guid? depId, DateTime? selectTime) { var departmentServices = ServiceLocator.Instance.GetService<IDepartmentServices>(); var departments = new List<ShowDepartment>(); departments.Add(new ShowDepartment() { Name = "全部" }); departments.AddRange(departmentServices.Get()); ViewBag.Department = new HtmlString(departments.ToJson()); var workRecordServices = ServiceLocator.Instance.GetService<IWorkRecordServices>(); if (selectTime.Null()) { selectTime = DateTime.Now; } var showWorkRecords = workRecordServices.GetAllRecords(selectTime.GetValueOrDefault(), depId.GetValueOrDefault()); ViewBag.DepId = depId.GetValueOrDefault(); ViewBag.selectTime = selectTime; return PartialView(new HtmlString(showWorkRecords.ToJson())); }
// GET: Manage/Department/Create public ActionResult Create(Guid? id) { var departmentServices = ServiceLocator.Instance.GetService<IDepartmentServices>(); var updateDepartment = new ShowDepartment(); var accounts = new List<ShowAccount>(); var ownerId = Guid.Empty; if (id.HasValue) { updateDepartment = departmentServices.Get(id.Value); var accountServices = ServiceLocator.Instance.GetService<IAccountServices>(); accounts = accountServices.GetAccountsByDepartment(id.Value); updateDepartment.OwnerId = departmentServices.GetOwner(id.Value); } ViewBag.ShowAccounts = new HtmlString(accounts.ToJson()); ViewBag.updateDepartment = new HtmlString(updateDepartment.ToJson()); return PartialView(); }
private static void TagTracks() { var trackTagger = new TrackTagger(); trackTagger.PrepareTrackMapping(BeforeFolderPath); var propertyApplier = new PropertyApplier(); var songPropertyCollection = new List<SongProperties>(); foreach (var songPath in trackTagger.PropertyMapper.Keys) { var songProperties = trackTagger.PropertyMapper[songPath]; songPropertyCollection.Add(songProperties); if (string.IsNullOrWhiteSpace(songProperties.Artist)) continue; Console.WriteLine("Copying {0} to {1}", songPath, AfterFolderPath); bool rename = false; string afterFilePath = Path.Combine(AfterFolderPath, Path.GetFileName(songPath)); if (rename) { afterFilePath = Path.Combine(AfterFolderPath, songProperties.Title + " - " + songProperties.Part + Path.GetExtension(songPath)); } File.Copy(songPath, afterFilePath, true); var afterFile = new FileInfo(afterFilePath); Console.WriteLine("Applying properties to {0}", afterFile.FullName); propertyApplier.ApplyMetadata(afterFile, songProperties); } using (var output = new StreamWriter(@"c:\temp\serialized.txt", true)) { output.Write(songPropertyCollection.ToJson()); } }
public void AddStepDataViews() { var dataContext = new RockContext(); // Add Data View Category "Steps". const string categoryDataViewStepsName = "Steps"; Debug.Print($"Adding Data View Category \"{ categoryDataViewStepsName }\"..."); var entityTypeId = EntityTypeCache.Get(typeof(Rock.Model.DataView)).Id; var stepsCategory = CreateCategory(categoryDataViewStepsName, Constants.CategoryStepsGuid, entityTypeId); AddOrUpdateCategory(dataContext, stepsCategory); dataContext.SaveChanges(); // Create Data View: Steps Completed const string dataViewStepsCompleted2001Name = "Steps Completed in 2001"; Debug.Print($"Adding Data View \"{ dataViewStepsCompleted2001Name }\"..."); DataView dataView = new DataView(); dataView.IsSystem = false; var service = new DataViewService(dataContext); int categoryId = CategoryCache.GetId(Constants.CategoryStepsGuid) ?? 0; dataView.Name = dataViewStepsCompleted2001Name; dataView.Description = "Steps that have a completion in the year 2001."; dataView.EntityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.Step)); dataView.CategoryId = categoryId; dataView.Guid = Constants.DataViewStepsCompleted2001Guid; dataView.ForeignKey = _SampleDataForeignKey; var rootFilter = new DataViewFilter(); rootFilter.ExpressionType = FilterExpressionType.GroupAll; dataView.DataViewFilter = rootFilter; // Add filter for Step Type var dateCompletedFilter = new DataViewFilter(); dateCompletedFilter.ExpressionType = FilterExpressionType.Filter; dateCompletedFilter.EntityTypeId = EntityTypeCache.GetId(typeof(Rock.Reporting.DataFilter.PropertyFilter)); var dateFilterSettings = new List <string> { "Property_CompletedDateTime", "4096", "\tDateRange|||1/01/2001 12:00:00 AM|31/12/2001 12:00:00 AM" }; dateCompletedFilter.Selection = dateFilterSettings.ToJson(); rootFilter.ChildFilters.Add(dateCompletedFilter); service.Add(dataView); dataContext.SaveChanges(); }
public String GetRowsReportObjectFields(Dictionary <string, string> fields, List <string> movement = null, List <string> objs = null, List <string> locations = null, List <string> users = null, Int64 start = 0, Int64 end = 0) { var orderfield = "folio"; try { List <string> cols = new List <string>(); foreach (var x in fields) { cols.Add(x.Key); } cols.Add("CreatedTimeStamp"); string[] arrayfields = cols.ToArray(); string[] arraymov = movement.ToArray(); string[] arrayobjs = objs.ToArray(); string[] arraylocations = locations.ToArray(); string[] arrayusers = users.ToArray(); BsonArray bsonarraymov = new BsonArray(); BsonArray bsonarrayobjs = new BsonArray(); BsonArray bsonarrayloc = new BsonArray(); BsonArray bsonarrayusers = new BsonArray(); for (int i = 0; i < arraymov.Length; i++) { bsonarraymov.Add(arraymov[i]); } for (int i = 0; i < arrayobjs.Length; i++) { bsonarrayobjs.Add(arrayobjs[i]); } for (int i = 0; i < arraylocations.Length; i++) { bsonarrayloc.Add(arraylocations[i]); } for (int i = 0; i < arrayusers.Length; i++) { bsonarrayusers.Add(arrayusers[i]); } List <BsonDocument> documents = new List <BsonDocument>(); if (movement != null && movement.Count > 0) { var query = Query.And(Query.In("movement", bsonarraymov), Query.In("object", bsonarrayobjs), Query.In("location", bsonarrayloc), Query.In("Creator", bsonarrayusers), Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end)); var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); foreach (BsonDocument document in cursor) { document.Set("_id", document.GetElement("_id").Value.ToString()); try { document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); } catch (Exception ex) { } documents.Add(document); } } else { var query = Query.And(Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end)); var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); foreach (BsonDocument document in cursor) { document.Set("_id", document.GetElement("_id").Value.ToString()); try { document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); } catch (Exception ex) { } documents.Add(document); } } return(documents.ToJson()); } catch (Exception e) { // System.Windows.Forms.MessageBox.Show(e.ToString()); return(null); } }
public HttpResponseMessage GetListOfUsers() { try { var portalId = PortalSettings.PortalId; var groups = Controllers.RoleController.GetRoleGroups(portalId); var returnGroups = new List<RoleGroupsInListDTO>(); if (groups != null && groups.Count > 0) { foreach (var group in groups) { var roles = Controllers.RoleController.GetRolesByRoleGroupID(portalId, group.RoleGroupID); if (roles != null && roles.Count > 0) { var returnRoles = new List<RolesInListDTO>(); foreach (var role in roles) { var users = Controllers.RoleController.GetUsersByRole(portalId, role.RoleName); if (users != null && users.Count > 0) { var returnUsers = new List<UsersInRoleDTO>(); foreach (var user in users) { returnUsers.Add(new UsersInRoleDTO() { FirstName = user.FirstName, LastName = user.LastName, DisplayName = user.DisplayName, Email = user.Email, Videos = user.Profile.GetPropertyValue("videosComplete") }); } returnRoles.Add(new RolesInListDTO() { Name = role.RoleName, Id = role.RoleID, Users = returnUsers }); } else if (users != null && users.Count == 0) { returnRoles.Add(new RolesInListDTO() { Name = role.RoleName, Id = role.RoleID }); } } returnGroups.Add(new RoleGroupsInListDTO() { Name = group.RoleGroupName, Id = group.RoleGroupID, Roles = returnRoles }); } } } return Request.CreateResponse(HttpStatusCode.OK, returnGroups.ToJson()); } catch (Exception exc) { Exceptions.LogException(exc); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } }
public InterviewInfo TestExcelInterviewInfoData() { InterviewInfo interviewInfo = new InterviewInfo { Image = @".\images\member.jpg", Vacancies = "軟體工程師", Name = "賴志維", Married = "未婚", Adress = "雲林縣斗六市八德里文化路690-29號", Urgent_Contact_Person = "賴雲慈", Interview_Date = "2017/07/20", Sex = "男", Mail = "*****@*****.**", Urgent_Relationship = "父子", Birthday = "1995/06/16", CellPhone = "0978535528", Urgent_CellPhone = "0965438536" }; ////學歷 List <Education> educationList = new List <Education>(); Education education = new Education() { School = "國立屏東科技大學", Department = "資訊管理系", Start_End_Date = "102/09~106/06", Is_Graduation = "畢業", Remark = "校內專題競賽第二名\n全國專題競賽佳作" }; educationList.Add(education); Education education1 = new Education() { School = "國立斗六高級家事商業職業學校", Department = "資料處理科", Start_End_Date = "99/09~102/06", Is_Graduation = "畢業", Remark = string.Empty }; educationList.Add(education1); interviewInfo.Education = educationList.ToJson(); ////工作經驗 List <WorkExperience> workExperienceList = new List <WorkExperience>(); WorkExperience workExperience = new WorkExperience { Institution_name = "屏東科技大學", Position = "學生", Start_End_Date = "102/09~106/06", Start_Salary = "0", End_Salary = "0", Leaving_Reason = "畢業" }; workExperienceList.Add(workExperience); interviewInfo.Work_Experience = workExperienceList.ToJson(); //interviewInfo.Work_Experience = "[]"; ////兵役 interviewInfo.During_Service = string.Empty; interviewInfo.Exemption_Reason = "體重過輕"; ////語言能力 List <Language> languageList = new List <Language>(); Language language = new Language { Language_Name = "英文", Listen = "平", Speak = "略", Read = "平", Write = "略" }; languageList.Add(language); interviewInfo.Language = languageList.ToJson(); ////專長 interviewInfo.Expertise_Language = "C#,R,Android"; interviewInfo.Expertise_Tools = "Visual Studio,Eclipse,R Studio,Framwork:ASP.NET"; interviewInfo.Expertise_Devops = "Git"; interviewInfo.Expertise_OS = "Windows,Android"; interviewInfo.Expertise_BigData = string.Empty; interviewInfo.Expertise_DataBase = "Oracle,MS SQL,QQ"; interviewInfo.Expertise_Certification = string.Empty; ////問題 interviewInfo.IsStudy = "無"; interviewInfo.IsService = "無"; interviewInfo.Relatives_Relationship = "無"; interviewInfo.Relatives_Name = "無"; interviewInfo.Care_Work = "無"; interviewInfo.Hope_Salary = "無"; interviewInfo.When_Report = "無"; interviewInfo.Advantage = "無"; interviewInfo.Disadvantages = "無"; interviewInfo.Hobby = "無"; interviewInfo.Attract_Reason = "無"; interviewInfo.Future_Goal = "無"; interviewInfo.Hope_Supervisor = "無"; interviewInfo.Hope_Promise = "無"; interviewInfo.Introduction = "無"; return(interviewInfo); }
public ActionResult Chart(ChartRequest request) { if (request.StartDate == null) { request.StartDate = DateTime.Now.AddDays(-30); } if (request.EndDate == null) { request.EndDate = DateTime.Now; } if (request.Type != null && request.Type == 2) { return BarChartR(request); } else { request.Type = 1; } if (request.BillType == BillType.None) { request.BillType = BillType.Revenue; } var rest = this._repository.Get( v => v.Status == (int)DataStatus.Normal && v.DataDateTime >= request.StartDate && v.DataDateTime <= request.EndDate && v.User_Id == CurrentUser.CustomerId && v.Type == (int)request.BillType); var g = rest.GroupBy(v => v.Tag_Id); var list = new List<List<object>>(); foreach (var item in g) { var l = new List<object>(2); var sum = item.Sum(v => v.Amount); var t = item.FirstOrDefault(); l.Add(t.Tag.Name); l.Add(sum); list.Add(l); } var r = new List<List<List<object>>>(); r.Add(list); var dto = new ChartDto(); dto.StartDate = request.StartDate.Value; dto.EndDate = request.EndDate.Value; dto.PieVal = list.Count == 0 ? "[[[]]]" : r.ToJson(); dto.Request = request; return View("View2", dto); }
public IActionResult KeyValues() { string cmd = RouteData.Values["id"]?.ToString(); if (cmd != null) { string result = string.Empty; var rt = new List <object> { 0, "fail" }; try { switch (cmd) { case "grab": { string key = Request.Form["Key"].ToString(); string api = $"https://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key={key.ToEncode()}&bk_length=600"; string apirt = Core.HttpTo.Get(api); if (apirt.Length > 100) { using (var db = new ContextBase()) { var kvMo = db.KeyValues.Where(x => x.KeyName == key).FirstOrDefault(); if (kvMo == null) { kvMo = new Domain.KeyValues { KeyId = Guid.NewGuid().ToString(), KeyName = key.ToLower(), KeyValue = apirt }; db.KeyValues.Add(kvMo); } else { kvMo.KeyValue = apirt; db.KeyValues.Update(kvMo); } rt[0] = db.SaveChanges(); rt[1] = kvMo; } } else { rt[0] = 0; rt[1] = apirt; } } break; case "synonym": { var keys = Request.Form["keys"].ToString().Split(',').ToList(); string mainKey = keys.First().ToLower(); keys.RemoveAt(0); var listkvs = new List <Domain.KeyValueSynonym>(); foreach (var key in keys) { var kvs = new Domain.KeyValueSynonym { KsId = Guid.NewGuid().ToString(), KeyName = mainKey, KsName = key.ToLower() }; listkvs.Add(kvs); } using (var db = new ContextBase()) { var mo = db.KeyValueSynonym.Where(x => x.KeyName == mainKey).FirstOrDefault(); if (mo != null) { db.KeyValueSynonym.Remove(mo); } db.KeyValueSynonym.AddRange(listkvs); int oldrow = db.SaveChanges(); rt[0] = 1; rt[1] = " 受影响 " + oldrow + " 行"; } } break; case "addtag": { var tags = Request.Form["tags"].ToString().Split(',').ToList(); if (tags.Count > 0) { using (var db = new ContextBase()) { var mt = db.Tags.Where(x => tags.Contains(x.TagName)).ToList(); if (mt.Count == 0) { var listMo = new List <Domain.Tags>(); var tagHs = new HashSet <string>(); foreach (var tag in tags) { if (tagHs.Add(tag)) { var mo = new Domain.Tags { TagName = tag.ToLower(), TagStatus = 1, TagHot = 0 }; listMo.Add(mo); } } tagHs.Clear(); //新增&刷新缓存 db.Tags.AddRange(listMo); rt[0] = db.SaveChanges(); Func.Common.TagsQuery(false); rt[1] = "操作成功"; } else { rt[0] = 0; rt[1] = "标签已存在:" + mt.ToJson(); } } } else { rt[0] = 0; rt[1] = "新增标签不能为空"; } } break; } } catch (Exception ex) { rt[1] = ex.Message; rt.Add(ex.StackTrace); } result = rt.ToJson(); return(Content(result)); } return(View()); }
private async Task <TResponse> Monitor <TRequest, TResponse>(object request, ServerCallContext context, Delegate continuation, object response = null) { var trace = context.RequestHeaders.FirstOrDefault(q => q.Key == Consts.TraceId); if (trace == null) { trace = new Metadata.Entry(Consts.TraceId, Guid.NewGuid().ToString()); context.RequestHeaders.Add(trace); } var model = new MonitorModel { ClientIp = context.Peer, RequestUrl = context.Method, //RequestData = request?.ToJson(), TraceId = trace.Value }; if (request is TRequest) { model.RequestData = request?.ToJson(); } else if (request is IAsyncStreamReader <TRequest> ) { var requests = new List <TRequest>(); //await requestStream.ForEachAsync(req=> { // requests.Add(req); // return Task.CompletedTask; //}); model.RequestData = requests?.ToJson(); } try { if (response == null) { var result = await(continuation.DynamicInvoke(request, context) as Task <TResponse>); model.Status = "ok"; model.ResponseData = MonitorManager.Instance.SaveResponseMethodEnable(context.Method) ? result?.ToJson() : Consts.NotResponseMsg; return(result); } else { await(continuation.DynamicInvoke(request, context) as Task); return(default(TResponse)); } } catch (Exception ex) { if (ex is AggregateException aex) { foreach (var e in aex.Flatten().InnerExceptions) { model.Exception += e?.ToString() + Environment.NewLine; } } else { model.Exception = ex?.ToString(); } model.Status = "error"; LoggerAccessor.Instance.LoggerError?.Invoke(new Exception(model.Exception)); throw CommonError.BuildRpcException(ex); } finally { model.ResponseTime = DateTime.Now; LoggerAccessor.Instance.LoggerMonitor?.Invoke(model.ToJson()); } }
private string StringifyDocuments(List <BsonDocument> documents) => documents.ToJson(_jsonWriterSettings);
public InvokeResult PushJuDouCourse(JuDouCourse judouCourse) { InvokeResult result = new InvokeResult { Success = true }; if (judouCourse != null && !string.IsNullOrEmpty(judouCourse.RemoteUrl)) { try { //点播 string strSql = string.Format("select a.BeginTime,DATEADD(S,a.CourseDuration,a.BeginTime) EndTime,a.CourseFlag," + " a.CourseInfo,c.DeviceCode From Pam_CourseSchedule a inner join Pam_Device b on a.DeviceId=b.DeviceId and " + " a.StationId=b.StationId and b.Status=1 inner join Pub_Device c on b.DeviceId=c.DeviceId and c.Status=1 " + " where a.Status=1 and a.StationId='{0}' and a.DeviceId in('{1}') and a.BeginTime>= '{2}' and BeginTime<='{3}'" + " and CourseFlag=3 order by a.DeviceId,a.BeginTime asc", judouCourse.StationId, string.Join("','", judouCourse.DeviceIds.Split(',')), judouCourse.CourseBeginTime, judouCourse.CourseEndTime); IList <StringObjectDictionary> dibbleCourseList = BuilderFactory.DefaultBulder().ExecuteNativeSqlForQuery(strSql); //直播 strSql = string.Format("select a.BeginTime,DATEADD(S,a.CourseDuration,a.BeginTime) EndTime,a.CourseFlag,a.CourseInfo,c.DeviceCode" + " From (select MAX(Id) Id,BeginTime From Pam_CourseSchedule " + " where Status=1 and StationId='{0}' and CourseFlag=2 and BeginTime>= '{1}' and BeginTime<='{2}' " + " group by BeginTime) x inner join Pam_CourseSchedule a on x.Id=a.Id inner join Pam_Device b on a.DeviceId=b.DeviceId and " + " a.StationId=b.StationId and b.Status=1 inner join Pub_Device c on b.DeviceId=c.DeviceId and c.Status=1 " + " order by a.BeginTime asc", judouCourse.StationId, judouCourse.CourseBeginTime, judouCourse.CourseEndTime); IList <StringObjectDictionary> liveCourseList = BuilderFactory.DefaultBulder().ExecuteNativeSqlForQuery(strSql); IList <object> pushCourse = new List <object>(); string[] stationDevices, courseInfo; string beginTime, endTime; //点播 foreach (var item in dibbleCourseList) { stationDevices = ((string)item["DeviceCode"] ?? "").Split('-'); courseInfo = ((string)(item["CourseInfo"] ?? "")).Split('|'); beginTime = ((DateTime)item["BeginTime"]).ToString("s", System.Globalization.DateTimeFormatInfo.InvariantInfo) + "+08:00"; endTime = ((DateTime)item["EndTime"]).ToString("s", System.Globalization.DateTimeFormatInfo.InvariantInfo) + "+08:00"; pushCourse.Add(new { begin = beginTime, end = endTime, bindId = stationDevices[0], uuid = new string[] { stationDevices[2] }, vod_url = new string[] { courseInfo[2] }, live_type = 3 }.ToStringObjectDictionary()); } //直播 foreach (var item in liveCourseList) { stationDevices = ((string)item["DeviceCode"] ?? "").Split('-'); courseInfo = ((string)(item["CourseInfo"] ?? "")).Split('|'); beginTime = ((DateTime)item["BeginTime"]).ToString("s", System.Globalization.DateTimeFormatInfo.InvariantInfo) + "+08:00"; endTime = ((DateTime)item["EndTime"]).ToString("s", System.Globalization.DateTimeFormatInfo.InvariantInfo) + "+08:00"; pushCourse.Add(new { begin = beginTime, end = endTime, bindId = stationDevices[0], uuid = new string[] { "all" }, vod_url = new string[] { courseInfo[2] }, live_type = 2 }.ToStringObjectDictionary()); } HttpAdapter.postSyncStr(judouCourse.RemoteUrl, pushCourse.ToJson(), (ret, res) => { if (string.IsNullOrEmpty((string)ret)) { result.Success = false; result.ErrorMessage = (string)ret; } }, (he) => { result.ErrorCode = he.ErrorCode; result.ErrorMessage = he.Message; }); } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.ToString(); } } return(result); }
public ActionResult GetAllKPIResult() { try { var CatNameCache = GetCatNameCache(); var result = new List <ALL_KPI_RESULT_VIEWMODEL>(); //数据体 var kpis = _kpiService.GetManayByOrder(r => r.SD_ID == ProjectProvider.Instance.Current.SD_ID && r.VALUE_TABLE_ID == 1, m => m.ORDER_NO); kpis.ForEach(r => { if (r.SD_EKPI_ID == 10366) { var a = 1; } var kpiname = _kpiService.Get(k => k.SD_EKPI_ID == r.SD_EKPI_ID).SD_EKPI_NAME; var pageData = _kpiService.GetKpiResult(new KPI_EXCUTE_VIEWMODEL() { primaryKey = r.SD_EKPI_ID.ToString() }); //百分比 var fenmu = pageData.Count; // r.SD_EKPI_NAME.Contains("平均") ? pageData.Where(z => z.DOUBLE_VALUE != 0.0000).Count() : pageData.Count; var fenzi = 0.00; // r.SD_EKPI_TYPE != 0 ? pageData.Where(z => z.VALUE !="0.0000").ToList().Count : pageData?.Count; if (r.SD_EKPI_CONVER == 0) { fenzi = pageData.Select(f => f.DOUBLE_VALUE).Sum(); } else { fenzi = pageData.Where(z => z.VALUE != "0.0000").ToList().Count; } double percent = 0; var percentoravg = string.Empty; if (pageData.Count != 0) { if (kpiname.Contains("平均")) { var sum = pageData.Select(s => s.DOUBLE_VALUE).Sum(); percent = Math.Round(sum / fenmu, 4); percentoravg = percent.ToString("0.00"); } else { percent = Math.Round((double)fenzi / (double)pageData.Count, 4); percentoravg = $"{(percent * 100).ToString("0.00")}%"; } } result.Add(new ALL_KPI_RESULT_VIEWMODEL() { 序号 = r.ORDER_NO.ToString(), 编码 = r.SD_EKPI_CODE, 针对群体的指标名称 = r.SD_EKPI_NAME, 针对个体的质控点名称 = r.SD_EKPI_ALIAS, 指标类别 = CatNameCache.FirstOrDefault(cr => cr.CAT_ID == r.SD_EKPI_CAT).CAT_NAME, 是否为统计指标 = r.SD_EKPI_TYPE == 1 ? "非统计类" : "统计类", 指标正负向 = r.IS_POSITIVE == 1 ? "正向" : (r.IS_POSITIVE == 0 ? "负向" : "其他"), 数据范围 = r.SD_EKPI_CONVER == 1 ? "百分比" : (r.SD_EKPI_CONVER == 2 ? "千分比" : "正常模式"), 单位 = r.SD_EKPI_UNIT, 是否开启趋势 = r.IS_TREND == 1 ? "是" : "否", 是否开启科室 = r.IS_DISTRIBUTION == 1 ? "是" : "否", 是否开启原因分析 = r.IS_RSN == 1 ? "是" : "否", 分母是否为一 = r.IS_NUM == 1 ? "是" : "否", 动态基线 = r.IS_DYNAMIC == 1 ? "是" : "否", 分子 = fenzi.ToString("0.00"), 分母 = fenmu.ToString(),// pageData?.Count.ToString(), 比率或值 = percentoravg }); }); return(Content(result.ToJson())); } catch (Exception e) { return(Error(e.ToString())); } }
public async Task <int> CreateProduct(string storeId, string name, string sku, int isInStock, string productType, Mark markForLog) { var stockItem = new CreatteProductModel(name, sku, isInStock, productType); var methodParameters = stockItem.ToJson(); try { const int maxCheckCount = 2; const int delayBeforeCheck = 1800000; var privateClient = this._clientFactory.CreateMagentoCatalogProductRepositoryServiceClient(); var res = new List <UpdateRessult <CreatteProductModel> >(); var stockItems = new List <CreatteProductModel> { stockItem }; await stockItems.DoInBatchAsync(10, async x => { await ActionPolicies.GetAsync.Do(async() => { var statusChecker = new StatusChecker(maxCheckCount); TimerCallback tcb = statusChecker.CheckStatus; privateClient = this._clientFactory.RefreshMagentoCatalogProductRepositoryServiceClient(privateClient); var updateResult = new UpdateRessult <CreatteProductModel>(x, 0); res.Add(updateResult); using (var stateTimer = new Timer(tcb, privateClient, 1000, delayBeforeCheck)) { MagentoLogger.LogTraceStarted(this.CreateMethodCallInfo(methodParameters, mark: markForLog)); var catalogInventoryDataStockItemInterface = new CatalogDataProductInterface() { sku = x.Sku, name = x.Name, price = "1", priceSpecified = true, status = 1, statusSpecified = true, typeId = productType, attributeSetId = 4, attributeSetIdSpecified = true, weight = "1", weightSpecified = true, }; if (productType == "bundle") { catalogInventoryDataStockItemInterface.customAttributes = new[] { new FrameworkAttributeInterface { value = "1", attributeCode = "price_view" }, new FrameworkAttributeInterface { value = "1", attributeCode = "price_type" } }; } var catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest = new CatalogProductRepositoryV1SaveRequest() { product = catalogInventoryDataStockItemInterface }; var temp = await privateClient.catalogProductRepositoryV1SaveAsync(catalogInventoryStockRegistryV1UpdateStockItemBySkuRequest).ConfigureAwait(false); updateResult.ErrorCode = temp.catalogProductRepositoryV1SaveResponse.result.id; } }).ConfigureAwait(false); }).ConfigureAwait(false); MagentoLogger.LogTraceEnded(this.CreateMethodCallInfo(methodParameters, mark: markForLog, methodResult: res.ToJson())); return(res.First().ErrorCode); } catch (Exception exc) { throw new MagentoSoapException($"An error occured during PutStockItemsAsync({methodParameters})", exc); } }
public ActionResult GetAllKPIValueUnion() { try { var pageData = new List <dynamic>(); var sdId = ProjectProvider.Instance.Current.SD_ID; var kpiValueCache = _unitKpiValueService.GetManay(r => r.SD_ID == sdId).ToList(); //表头 var kpis = _kpiService.GetManayByOrder(r => r.SD_ID == sdId && r.VALUE_TABLE_ID == 1, m => m.ORDER_NO); Dictionary <Tuple <string, int>, object> temp = new Dictionary <Tuple <string, int>, object>(); kpis.ForEach(r => { temp.Add(new Tuple <string, int>($"{r.SD_EKPI_CODE}分子", r.SD_EKPI_ID), r.SD_EKPI_CODE); temp.Add(new Tuple <string, int>($"{r.SD_EKPI_CODE}分母", r.SD_EKPI_ID), r.SD_EKPI_CODE); }); dynamic title = new ExpandoObject(); //((IDictionary<string, object>)title).Add("PNO", "PNO"); foreach (KeyValuePair <Tuple <string, int>, object> item in temp) { ((IDictionary <string, object>)title).Add(item.Key.Item1, item.Value); } //二级标题 //dynamic head2 = new ExpandoObject(); //foreach (KeyValuePair<Tuple<string, int>, object> item in temp) //{ // if (item.Key.Item1.Contains("分子")) // { // ((IDictionary<string, object>)head2).Add(item.Key.Item1, "分子"); // } // else // { // ((IDictionary<string, object>)head2).Add(item.Key.Item1, "分母"); // } //} //pageData.Add(head2); //三级标题 dynamic head3 = new ExpandoObject(); foreach (KeyValuePair <Tuple <string, int>, object> item in temp) { var conver = kpis.FirstOrDefault(k => k.SD_EKPI_ID == item.Key.Item2).SD_EKPI_CONVER; if (conver == 0) { if (item.Key.Item1.Contains("分子")) { ((IDictionary <string, object>)head3).Add(item.Key.Item1, kpiValueCache.Where(h3 => h3.SD_EKPI_ID == item.Key.Item2).Count()); } else { ((IDictionary <string, object>)head3).Add(item.Key.Item1, kpiValueCache.Where(h3 => h3.SD_EKPI_ID == item.Key.Item2).Count()); } } else { if (item.Key.Item1.Contains("分子")) { ((IDictionary <string, object>)head3).Add(item.Key.Item1, kpiValueCache.Where(h3 => h3.SD_EKPI_ID == item.Key.Item2 && h3.INDEX_VALUE == 1).Count()); } else { ((IDictionary <string, object>)head3).Add(item.Key.Item1, kpiValueCache.Where(h3 => h3.SD_EKPI_ID == item.Key.Item2).Count()); } } } pageData.Add(head3); //数据体 var cpats = _unitCpatDetailService.GetManay(r => r.SD_ID == sdId && r.IN_FLAG == "I"); for (var i = 0; i < cpats.Count; i++) { dynamic value = new ExpandoObject(); foreach (KeyValuePair <Tuple <string, int>, object> item in temp) { var conver = kpis.FirstOrDefault(k => k.SD_EKPI_ID == item.Key.Item2).SD_EKPI_CONVER; if (conver == 0) { if (item.Key.Item1.Contains("分子")) { var z = kpiValueCache.Where(v => v.SD_EKPI_ID == item.Key.Item2).Skip(i).Take(1).FirstOrDefault(); if (z?.INDEX_VALUE != null) { ((IDictionary <string, object>)value).Add(item.Key.Item1, z.SD_CPAT_NO); } else { ((IDictionary <string, object>)value).Add(item.Key.Item1, null); } } else { var m = kpiValueCache.Where(v => v.SD_EKPI_ID == item.Key.Item2).Skip(i).Take(1).FirstOrDefault(); if (m == null) { ((IDictionary <string, object>)value).Add(item.Key.Item1, null); } else { ((IDictionary <string, object>)value).Add(item.Key.Item1, m.SD_CPAT_NO); } } } else { if (item.Key.Item1.Contains("分子")) { var z = kpiValueCache.Where(v => v.SD_EKPI_ID == item.Key.Item2 && v.INDEX_VALUE == 1).Skip(i).Take(1).FirstOrDefault(); if (z?.INDEX_VALUE == 1) { ((IDictionary <string, object>)value).Add(item.Key.Item1, z.SD_CPAT_NO); } else { ((IDictionary <string, object>)value).Add(item.Key.Item1, null); } } else { var m = kpiValueCache.Where(v => v.SD_EKPI_ID == item.Key.Item2 && (v.INDEX_VALUE == 1 || v.INDEX_VALUE == 0)).Skip(i).Take(1).FirstOrDefault(); if (m == null) { ((IDictionary <string, object>)value).Add(item.Key.Item1, null); } else { ((IDictionary <string, object>)value).Add(item.Key.Item1, m.SD_CPAT_NO); } } } } pageData.Add(value); } //var cpats = _unitCpatDetailService.GetManay(r => r.SD_ID == sdId && r.IN_FLAG == "I"); //cpats.ForEach( // r => // { // dynamic value = new ExpandoObject(); // foreach (KeyValuePair<Tuple<string, int>, object> item in temp) // { // var k = kpiValueCache.FirstOrDefault(v => v.SD_CPAT_NO == r.SD_CPAT_NO && v.SD_EKPI_ID == item.Key.Item2)?.INDEX_VALUE; // if (item.Key.Item1.Contains("分子")) // { // if (k == 1) // { // ((IDictionary<string, object>)value).Add(item.Key.Item1, r.SD_CPAT_NO); // } // else // { // ((IDictionary<string, object>)value).Add(item.Key.Item1, null); // } // } // else // { // if (k == null) // { // ((IDictionary<string, object>)value).Add(item.Key.Item1, null); // } // else // { // ((IDictionary<string, object>)value).Add(item.Key.Item1, r.SD_CPAT_NO); // } // } // } // pageData.Add(value); // } //); var data = new Dictionary <string, List <dynamic> >(); data.Add("title", new List <dynamic>() { title }); data.Add("data", pageData); return(Content(pageData.ToJson())); } catch (Exception e) { return(Error(e.ToString())); } }
/// <summary> /// Gets the chart data (ajax call from Chart) /// </summary> private void GetChartData() { try { var sql = this.GetAttributeValue("SQL"); if (string.IsNullOrWhiteSpace(sql)) { // } else { var mergeFields = GetDynamicDataMergeFields(); sql = sql.ResolveMergeFields(mergeFields); var parameters = GetParameters(); DataSet dataSet = DbService.GetDataSet(sql, System.Data.CommandType.Text, parameters); List <DynamicChartData> chartDataList = new List <DynamicChartData>(); foreach (var row in dataSet.Tables[0].Rows.OfType <DataRow>()) { var chartData = new DynamicChartData(); if (row.Table.Columns.Contains("SeriesName")) { chartData.SeriesName = Convert.ToString(row["SeriesName"]); } else if (row.Table.Columns.Contains("SeriesID")) { // backwards compatibility chartData.SeriesName = Convert.ToString(row["SeriesID"]); } if (row.Table.Columns.Contains("YValue")) { chartData.YValue = Convert.ToDecimal(row["YValue"]); } if (row.Table.Columns.Contains("MetricTitle")) { chartData.MetricTitle = Convert.ToString(row["MetricTitle"]); } else { chartData.MetricTitle = chartData.SeriesName; } if (row.Table.Columns.Contains("YValueTotal")) { chartData.YValueTotal = Convert.ToDecimal(row["YValueTotal"]); } else { chartData.YValueTotal = chartData.YValue; } if (row.Table.Columns.Contains("YValueFormatted")) { chartData.YValueFormatted = Convert.ToString(row["YValueFormatted"]); } else { chartData.YValueFormatted = chartData.YValue.HasValue ? chartData.YValue.Value.ToString("G29") : string.Empty; } if (row.Table.Columns.Contains("DateTime")) { chartData.DateTimeStamp = (row["DateTime"] as DateTime? ).Value.ToJavascriptMilliseconds(); } else if (row.Table.Columns.Contains("XValue")) { chartData.DateTimeStamp = (row["XValue"] as int?).Value; } chartDataList.Add(chartData); } chartDataList = chartDataList.OrderBy(a => a.SeriesName).ThenBy(a => a.DateTimeStamp).ToList(); Response.Clear(); Response.Write(chartDataList.ToJson()); Response.End(); } } catch (System.Threading.ThreadAbortException) { // ignore the ThreadAbort exception from Response.End(); } catch (Exception ex) { LogException(ex); throw; } }
private void Set(Context context, DataRow dataRow, string tableAlias = null) { AccessStatus = Databases.AccessStatuses.Selected; foreach (DataColumn dataColumn in dataRow.Table.Columns) { var column = new ColumnNameInfo(dataColumn.ColumnName); if (column.TableAlias == tableAlias) { switch (column.Name) { case "ReferenceId": if (dataRow[column.ColumnName] != DBNull.Value) { ReferenceId = dataRow[column.ColumnName].ToLong(); SavedReferenceId = ReferenceId; } break; case "ReferenceType": if (dataRow[column.ColumnName] != DBNull.Value) { ReferenceType = dataRow[column.ColumnName].ToString(); SavedReferenceType = ReferenceType; } break; case "OwnerId": if (dataRow[column.ColumnName] != DBNull.Value) { OwnerId = dataRow[column.ColumnName].ToInt(); SavedOwnerId = OwnerId; } break; case "Ver": Ver = dataRow[column.ColumnName].ToInt(); SavedVer = Ver; break; case "Data": Data = dataRow[column.ColumnName].ToString().Deserialize <List <long> >() ?? new List <long>(); SavedData = Data.ToJson(); break; case "Comments": Comments = dataRow[column.ColumnName].ToString().Deserialize <Comments>() ?? new Comments(); SavedComments = Comments.ToJson(); break; case "Creator": Creator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); SavedCreator = Creator.Id; break; case "Updator": Updator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); SavedUpdator = Updator.Id; break; case "CreatedTime": CreatedTime = new Time(context, dataRow, column.ColumnName); SavedCreatedTime = CreatedTime.Value; break; case "UpdatedTime": UpdatedTime = new Time(context, dataRow, column.ColumnName); Timestamp = dataRow.Field <DateTime>(column.ColumnName).ToString("yyyy/M/d H:m:s.fff"); SavedUpdatedTime = UpdatedTime.Value; break; case "IsHistory": VerType = dataRow.Bool(column.ColumnName) ? Versions.VerTypes.History : Versions.VerTypes.Latest; break; default: switch (Def.ExtendedColumnTypes.Get(column.Name)) { case "Class": Class( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); SavedClass( columnName: column.Name, value: Class(columnName: column.Name)); break; case "Num": Num( columnName: column.Name, value: dataRow[column.ColumnName].ToDecimal()); SavedNum( columnName: column.Name, value: Num(columnName: column.Name)); break; case "Date": Date( columnName: column.Name, value: dataRow[column.ColumnName].ToDateTime()); SavedDate( columnName: column.Name, value: Date(columnName: column.Name)); break; case "Description": Description( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); SavedDescription( columnName: column.Name, value: Description(columnName: column.Name)); break; case "Check": Check( columnName: column.Name, value: dataRow[column.ColumnName].ToBool()); SavedCheck( columnName: column.Name, value: Check(columnName: column.Name)); break; case "Attachments": Attachments( columnName: column.Name, value: dataRow[column.ColumnName].ToString() .Deserialize <Attachments>() ?? new Attachments()); SavedAttachments( columnName: column.Name, value: Attachments(columnName: column.Name).ToJson()); break; } break; } } } }
private static void WriteJson() { _json = _favorites.ToJson(); File.WriteAllText("favorites.json", _json); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (CurrentWorkflow == null || CurrentCheckInState == null) { NavigateToHomePage(); } else { if (!Page.IsPostBack) { try { lTitle.Text = GetAttributeValue("Title"); string detailMsg = GetAttributeValue("DetailMessage"); var printFromClient = new List <CheckInLabel>(); var printFromServer = new List <CheckInLabel>(); // Print the labels foreach (var family in CurrentCheckInState.CheckIn.Families.Where(f => f.Selected)) { lbAnother.Visible = CurrentCheckInState.CheckInType.TypeOfCheckin == TypeOfCheckin.Individual && family.People.Count > 1; foreach (var person in family.GetPeople(true)) { foreach (var groupType in person.GetGroupTypes(true)) { foreach (var group in groupType.GetGroups(true)) { foreach (var location in group.GetLocations(true)) { foreach (var schedule in location.GetSchedules(true)) { var li = new HtmlGenericControl("li"); li.InnerText = string.Format(detailMsg, person.ToString(), group.ToString(), location.Location.Name, schedule.ToString(), person.SecurityCode); phResults.Controls.Add(li); } } } if (groupType.Labels != null && groupType.Labels.Any()) { printFromClient.AddRange(groupType.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Client)); printFromServer.AddRange(groupType.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Server)); } } } } if (printFromClient.Any()) { var urlRoot = string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority); printFromClient .OrderBy(l => l.PersonId) .ThenBy(l => l.Order) .ToList().ForEach(l => l.LabelFile = urlRoot + l.LabelFile.Replace("GetFile.ashx", "NP_GetCheckinLabel.ashx")); printFromClient.Take(printFromClient.Count() - 1).ToList().ForEach(l => { l.LabelFile += "&delaycut=T"; l.LabelKey += "-nocut"; }); AddLabelScript(printFromClient.ToJson()); } if (printFromServer.Any()) { var messages = new List <string>(); Socket socket = null; string currentIp = string.Empty; foreach (var label in printFromServer .OrderBy(l => l.PersonId) .ThenBy(l => l.Order)) { var labelCache = KioskLabel.Get(label.FileGuid); if (labelCache != null) { if (!string.IsNullOrWhiteSpace(label.PrinterAddress)) { if (label.PrinterAddress != currentIp) { if (socket != null && socket.Connected) { socket.Shutdown(SocketShutdown.Both); socket.Close(); } int printerPort = 9100; var printerIpAddress = label.PrinterAddress; // If the user specified in 0.0.0.0:1234 syntax then pull our the IP and port numbers. if (printerIpAddress.Contains(":")) { var segments = printerIpAddress.Split(':'); printerIpAddress = segments[0]; printerPort = segments[1].AsInteger(); } var printerEndpoint = new IPEndPoint(IPAddress.Parse(printerIpAddress), printerPort); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = socket.BeginConnect(printerEndpoint, null, null); bool success = result.AsyncWaitHandle.WaitOne(5000, true); } string printContent = labelCache.FileContent; foreach (var mergeField in label.MergeFields) { if (!string.IsNullOrWhiteSpace(mergeField.Value)) { printContent = Regex.Replace(printContent, string.Format(@"(?<=\^FD){0}(?=\^FS)", mergeField.Key), mergeField.Value); } else { // Remove the box preceding merge field printContent = Regex.Replace(printContent, string.Format(@"\^FO.*\^FS\s*(?=\^FT.*\^FD{0}\^FS)", mergeField.Key), string.Empty); // Remove the merge field printContent = Regex.Replace(printContent, string.Format(@"\^FD{0}\^FS", mergeField.Key), "^FD^FS"); } } if (label != printFromServer.OrderBy(l => l.Order).LastOrDefault()) { printContent = printContent.Replace("^PQ1,1,1,Y", ""); printContent = printContent.Replace("^XZ", "^XB^XZ"); } if (socket.Connected) { if (socket.Connected) { var ns = new NetworkStream(socket); //var encoder = System.Text.Encoding.GetEncoding( "ISO-8859-1" ); var encoder = System.Text.Encoding.UTF8; byte[] toSend = encoder.GetBytes(printContent); ns.Write(toSend, 0, toSend.Length); } } else { messages.Add("NOTE: Could not connect to printer!"); } } } } // Close the socket if (socket != null && socket.Connected) { socket.Shutdown(SocketShutdown.Both); socket.Close(); } foreach (var message in messages) { phResults.Controls.Add(new LiteralControl(string.Format("<br/>{0}", message))); } } } catch (Exception ex) { LogException(ex); } } } }
private void Set(DataRow dataRow) { AccessStatus = Databases.AccessStatuses.Selected; foreach (DataColumn dataColumn in dataRow.Table.Columns) { var name = dataColumn.ColumnName; switch (name) { case "ReferenceId": if (dataRow[name] != DBNull.Value) { ReferenceId = dataRow[name].ToLong(); SavedReferenceId = ReferenceId; } break; case "ReferenceType": if (dataRow[name] != DBNull.Value) { ReferenceType = dataRow[name].ToString(); SavedReferenceType = ReferenceType; } break; case "OwnerId": if (dataRow[name] != DBNull.Value) { OwnerId = dataRow[name].ToInt(); SavedOwnerId = OwnerId; } break; case "Ver": Ver = dataRow[name].ToInt(); SavedVer = Ver; break; case "Data": Data = dataRow.String("Data").Deserialize <List <long> >() ?? new List <long>(); SavedData = Data.ToJson(); break; case "Comments": Comments = dataRow["Comments"].ToString().Deserialize <Comments>() ?? new Comments(); SavedComments = Comments.ToJson(); break; case "Creator": Creator = SiteInfo.User(dataRow.Int(name)); SavedCreator = Creator.Id; break; case "Updator": Updator = SiteInfo.User(dataRow.Int(name)); SavedUpdator = Updator.Id; break; case "CreatedTime": CreatedTime = new Time(dataRow, "CreatedTime"); SavedCreatedTime = CreatedTime.Value; break; case "UpdatedTime": UpdatedTime = new Time(dataRow, "UpdatedTime"); Timestamp = dataRow.Field <DateTime>("UpdatedTime").ToString("yyyy/M/d H:m:s.fff"); SavedUpdatedTime = UpdatedTime.Value; break; case "IsHistory": VerType = dataRow[name].ToBool() ? Versions.VerTypes.History : Versions.VerTypes.Latest; break; } } }
public void map_spotify_releases_should_map_artist_id_for_artist() { var data = new List <SpotifyImportListItemInfo> { new SpotifyImportListItemInfo { Artist = "Adele", ArtistSpotifyId = "4dpARuHxo51G3z768sgnrY" } }; var map = new List <SpotifyMap> { new SpotifyMap { SpotifyId = "7uwTHXmFa1Ebi5flqBosig", MusicbrainzId = "5537624c-3d2f-4f5c-8099-df916082c85c" }, new SpotifyMap { SpotifyId = "4dpARuHxo51G3z768sgnrY", MusicbrainzId = "cc2c9c3c-b7bc-4b8b-84d8-4fbd8779e493" } }; Mocker.GetMock <IHttpClient>() .Setup(x => x.Post <List <SpotifyMap> >(It.IsAny <HttpRequest>())) .Returns <HttpRequest>(r => new HttpResponse <List <SpotifyMap> >(new HttpResponse(r, new HttpHeader(), map.ToJson()))); var result = Subject.MapSpotifyReleases(data); result[0].ArtistMusicBrainzId.Should().Be("cc2c9c3c-b7bc-4b8b-84d8-4fbd8779e493"); }
// GET: api/UserProfiles public async Task <HttpResponseMessage> Get( [FromUri] string repository, [FromUri] string display_name, [FromUri] List <string> months ) { EasyAnalysis.Framework.ConnectionStringProviders.IConnectionStringProvider mongoDBCSProvider = EasyAnalysis.Framework.ConnectionStringProviders.ConnectionStringProvider.CreateConnectionStringProvider(EasyAnalysis.Framework.ConnectionStringProviders.ConnectionStringProvider.ConnectionStringProviderType.MongoDBConnectionStringProvider); var client = new MongoClient(mongoDBCSProvider.GetConnectionString(repository)); var database = client.GetDatabase(repository); var userProfiles = database.GetCollection <BsonDocument>("asker_activities"); var builder = Builders <BsonDocument> .Filter; FilterDefinition <BsonDocument> filter = "{}"; if (months.Count > 0) { filter = filter & builder.In("month", months); } if (!string.IsNullOrEmpty(display_name)) { filter = filter & builder.Regex("display_name", BsonRegularExpression.Create(new Regex("^" + display_name, RegexOptions.IgnoreCase))); } IList <BsonDocument> result = new List <BsonDocument>(); var cursor = await userProfiles.Aggregate() .Match(filter) .Group("{_id: '$id', asked: {$sum:'$total'}, answered: {$sum:'$answered'}, marked: {$sum: '$marked'}, months:{$push:'$month' }}") .Project("{_id: 0, id: '$_id', asked: 1, answered: 1, marked: 1, months:1}") //.Match("{asked: {$gte:7}") .Sort("{ asked: -1 }") .ToListAsync(); foreach (var data in cursor) { //BsonArray _tags = new BsonArray(); BsonArray _platform_tags = new BsonArray(); BsonArray _language_tags = new BsonArray(); BsonArray _other_tags = new BsonArray(); BsonArray _threads = new BsonArray(); BsonArray _marked_threads = new BsonArray(); FilterDefinition <BsonDocument> filterid = filter & builder.Eq("id", data.GetValue("id").AsString); var op = await userProfiles .Find(filterid) .ToListAsync(); foreach (var item in op) { data["display_name"] = item.GetValue("display_name").AsString; // Unpacking Tags foreach (var tag in item.GetValue("tags").AsBsonArray) { if (wellKnownPlatformTags.Contains(tag["name"].AsString.ToLower())) { _platform_tags.Add(tag); } else if (wellKnownLanguageTags.Contains(tag["name"].AsString.ToLower())) { _language_tags.Add(tag); } else { _other_tags.Add(tag); } //_tags.Add(tag); } data["platform_tags"] = MergeAndCleanArray(_platform_tags); data["language_tags"] = MergeAndCleanArray(_language_tags); data["other_tags"] = MergeAndCleanArray(_other_tags); //data["tags"] = _tags; ////Unpacking Threads //foreach (var thread in item.GetValue("threads").AsBsonArray) //{ // _threads.Add(thread); //} ////Unpacking Marked Threads //if (item.GetValue("marked_threads")!=null) //{ // foreach (var thread in item.GetValue("marked_threads").AsBsonArray) // { // _marked_threads.Add(thread); // } //} //data["threads"] = _threads; //data["marked_threads"] = _marked_threads; } result.Add(data); } var response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.OK; var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; response.Content = new StringContent(result.ToJson(jsonWriterSettings), Encoding.UTF8, "application/json"); return(response); }
static void AddRowsFromClass() { //Get dataset id from a table name string datasetId = GetAllDatasets().Datasets.GetDataset(datasetName).First().Id; //In a production application, use more specific exception handling. try { HttpWebRequest request = DatasetRequest(String.Format("{0}/{1}/tables/{2}/rows", datasetsUri, datasetId, tableName), "POST", AccessToken()); //Create a list of Product List<Product> products = new List<Product> { new Product{ProductID = 1, Name="Adjustable Race", Category="Components", IsCompete = true, ManufacturedOn = new DateTime(2014, 7, 30)}, new Product{ProductID = 2, Name="LL Crankarm", Category="Components", IsCompete = true, ManufacturedOn = new DateTime(2014, 7, 30)}, new Product{ProductID = 3, Name="HL Mountain Frame - Silver", Category="Bikes", IsCompete = true, ManufacturedOn = new DateTime(2014, 7, 30)}, }; //POST request using the json from a list of Product //NOTE: Posting rows to a model that is not created through the Power BI API is not currently supported. // Please create a dataset by posting it through the API following the instructions on http://dev.powerbi.com. Console.WriteLine(PostRequest(request, products.ToJson(JavaScriptConverter<Product>.GetSerializer()))); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void btnKomutlariKaydet_Click(object sender, EventArgs e) => File.WriteAllText(CommandFilePath, Commands.ToJson(), new System.Text.UTF8Encoding(false));
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); if ( !Page.IsPostBack ) { // Options for Chart var chartOptions = ChartOptions.Default; chartOptions.vAxis.title = this.Title; if ( !string.IsNullOrWhiteSpace( this.Subtitle ) ) { chartOptions.vAxis.title += Environment.NewLine + this.Subtitle; } hfOptions.Value = ( chartOptions as object ).ToJson(); List<ColumnDefinition> columnDefinitions = new List<ColumnDefinition>(); columnDefinitions.Add( new ColumnDefinition( "Date", ColumnDataType.date ) ); columnDefinitions.Add( new ColumnDefinition( "Attendance", ColumnDataType.number ) ); columnDefinitions.Add( new ChartTooltip() ); hfColumns.Value = columnDefinitions.ToJson(); // Data for Chart Guid attendanceMetricGuid = new Guid( "D4752628-DFC9-4681-ADB3-01936B8F38CA" ); int metricId = new MetricService( new RockContext()).Get(attendanceMetricGuid).Id; DateTime? startDate = new DateTime( 2013, 1, 1 ); DateTime? endDate = new DateTime( 2014, 1, 1 ); int? entityId = null; hfRestUrlParams.Value = string.Format( "{0}?startDate={1}&endDate={2}", metricId, startDate ?? DateTime.MinValue, endDate ?? DateTime.MaxValue); if (entityId.HasValue) { hfRestUrlParams.Value += string.Format( "&entityId={0}", entityId ); } } }
/// <summary> /// Filters the results. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="service">The service.</param> /// <param name="itemQry">The item qry.</param> /// <returns></returns> private IQueryable <ContentChannelItem> FilterResults(RockContext rockContext, ContentChannelItemService service, IQueryable <ContentChannelItem> itemQry) { var contentChannelId = GetAttributeValue(AttributeKeys.ContentChannel).AsInteger(); var itemType = typeof(Rock.Model.ContentChannelItem); var paramExpression = service.ParameterExpression; // // Apply Data Filter. // int?dataFilterId = GetAttributeValue(AttributeKeys.FilterId).AsIntegerOrNull(); if (dataFilterId.HasValue) { var dataFilterService = new DataViewFilterService(rockContext); var dataFilter = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value); var errorMessages = new List <string>(); Expression whereExpression = dataFilter?.GetExpression(itemType, service, paramExpression, errorMessages); itemQry = itemQry.Where(paramExpression, whereExpression, null); } // // Apply page parameter filtering. // var pageParameters = RequestContext.GetPageParameters(); if (GetAttributeValue(AttributeKeys.QueryParameterFiltering).AsBoolean() && pageParameters.Count > 0) { var propertyFilter = new Rock.Reporting.DataFilter.PropertyFilter(); foreach (var kvp in pageParameters) { var selection = new List <string>(); // Since there could be many matches by the key name for an attribute we have to construct the unique name used by EntityHelper.FindFromFilterSelection and use that var attributeService = new AttributeService(rockContext); var attributeGuid = attributeService .Queryable() .Where(a => a.EntityTypeQualifierColumn == "ContentChannelId") .Where(a => a.EntityTypeQualifierValue == contentChannelId.ToString()) .Where(a => a.Key == kvp.Key) .Select(a => a.Guid) .FirstOrDefault(); string uniqueName = kvp.Key; if (attributeGuid != null) { uniqueName = string.Format("Attribute_{0}_{1}", kvp.Key, attributeGuid.ToString().Replace("-", string.Empty)); } // Keep using uniquename for attributes since common keys (e.g. "category")will return mutliple values selection.Add(uniqueName); var entityField = Rock.Reporting.EntityHelper.FindFromFilterSelection(itemType, uniqueName, false, false); if (entityField != null) { string value = kvp.Value; switch (entityField.FieldType.Guid.ToString().ToUpper()) { case Rock.SystemGuid.FieldType.DAY_OF_WEEK: case Rock.SystemGuid.FieldType.SINGLE_SELECT: { selection.Add(value); } break; case Rock.SystemGuid.FieldType.MULTI_SELECT: { selection.Add(ComparisonType.Contains.ConvertToInt().ToString()); selection.Add(value); } break; default: { selection.Add(ComparisonType.EqualTo.ConvertToInt().ToString()); selection.Add(value); } break; } itemQry = itemQry.Where(paramExpression, propertyFilter.GetExpression(itemType, service, paramExpression, selection.ToJson())); } } } return(itemQry); }
/// <summary> /// Returns the value of <paramref name="parameter"/> suitable for storage/display. /// </summary> /// <param name="parameter">The DB Parameter. /// </param> /// <returns>a string containing the value.</returns> private static string GetValue(IDataParameter parameter) { object rawValue = parameter.Value; if (rawValue is DataTable) { var rows = new List<List<string>>(); foreach (DataRow row in ((DataTable)rawValue).Select()) { var colValues = new List<string>(); foreach (DataColumn col in row.Table.Columns) { colValues.Add((row[col] == DBNull.Value || row[col] == null) ? "NULL" : row[col].ToString()); } rows.Add(colValues); } return rows.ToJson(); } if (rawValue == null || rawValue == DBNull.Value) { return null; } // This assumes that all SQL variants use the same parameter format, it works for T-SQL if (parameter.DbType == DbType.Binary) { var bytes = rawValue as byte[]; if (bytes != null && bytes.Length <= MaxByteParameterSize) { return "0x" + BitConverter.ToString(bytes).Replace("-", string.Empty); } // Parameter is too long, so blank it instead return null; } if (rawValue is DateTime) { return ((DateTime)rawValue).ToString("s", System.Globalization.CultureInfo.InvariantCulture); } // we want the integral value of an enum, not its string representation var rawType = rawValue.GetType(); if (rawType.IsEnum) { // use ChangeType, as we can't cast - http://msdn.microsoft.com/en-us/library/exx3b86w(v=vs.80).aspx return Convert.ChangeType(rawValue, Enum.GetUnderlyingType(rawType)).ToString(); } return rawValue.ToString(); }
public void HandleDevice(object obj) { TcpClient client = (TcpClient)obj; var stream = client.GetStream(); Response response = new Response(); var buffer = new byte[client.ReceiveBufferSize]; int receiveBufferCount; try { // while ((receiveBufferCount = stream.Read(buffer, 0, buffer.Length)) != 0) // { // var msg = Encoding.UTF8.GetString(buffer, 0, buffer.Length); // Console.WriteLine(msg); var request = client.ReadRequest(); if (request.Method == null) { response.Status = "missing method"; // goto Finish; } if (request.Path == null) { response.Status += "missing resource"; } if (request.Body == null) { response.Status += ", missing body"; } if (request.Date == null) { response.Status += ", missing date"; goto Finish; } if (!(Util.ArrayContains(Method.methods, request.Method))) { response.Status += "illegal method"; goto Finish; } // check if date in correct format if (request.Date != null) { try { var number = Convert.ToInt32(request.Date); } catch (System.Exception) { response.Status += ", illegal date"; } goto Finish; } Finish: //invalid json object in body if (request.Body != null) { try { var categoryFromJson = JsonSerializer.Deserialize <Request>(request.Body); } catch (System.Exception e) { Console.WriteLine(e); response.Status += ", illegal body"; } response.Body = "Hello World"; goto End; } End: if (request.Path != null && request.Path.Contains("/api")) { if (request.Path.Contains("/api/categories")) { var extractedId = Regex.Match(request.Path, @"\d+$").Value; if (extractedId == "") { response.Status = "4 Bad Request"; } if (request.Path != "" && extractedId != "" && request.Method == "create") { response.Status = "4 Bad Request"; response.Body = null; } if (request.Path != "" && extractedId == "" && request.Method == "create") { response.Status = "1 Ok"; var category = request.Body.FromJson <Category>(); // Console.WriteLine(category); // Console.WriteLine(123); Program.categories.Add(new Category { Id = 4, Name = category.Name }); var stringCategory = Program.categories[3].ToJson(); Console.WriteLine(stringCategory); response.Body = stringCategory; // foreach (var item in Program.categories) // { // Console.WriteLine(item); // } } if (request.Path != "" && extractedId == "" && request.Method == "update") { response.Status = "4 Bad Request"; response.Body = null; } if (request.Path != "" && extractedId == "" && request.Method == "delete") { response.Status = "4 Bad Request"; response.Body = null; } if (request.Path != "" && extractedId != "" && request.Method == "delete") { var item = Program.categories.Find(x => x.Id == Int32.Parse(extractedId)); if (item != null) { Program.categories.Remove(item); response.Status = "1 Ok"; } else { response.Status = "5 not found"; } } if (request.Path == "/api/categories" && extractedId == "" && request.Method == "read") { response.Status = "1 Ok"; var categories = new List <object> { new { cid = 1, name = "Beverages" }, new { cid = 2, name = "Condiments" }, new { cid = 3, name = "Confections" } }; response.Body = categories.ToJson(); } if (request.Path == "/api/categories/1" && extractedId == "1" && request.Method == "read") { response.Status = "1 Ok"; // response.Body = (new { cid = 1, name = "Beverages" }.ToJson()); foreach (var item in Program.categories) { if (item.Id == 1) { response.Body = (new { cid = 1, name = item.Name }.ToJson()); } } } if (request.Path == "/api/categories/123" && extractedId != "" && request.Method == "read") { response.Status = "5 not found"; } if (request.Path == "/api/categories/123" && extractedId != "" && request.Method == "update") { response.Status = "5 not found"; } if (request.Path == "/api/categories/1" && extractedId != "" && request.Method == "update" && request.Body != null) { Console.WriteLine(request.Body); try { var category = request.Body.FromJson <Category>(); foreach (var item in Program.categories) { if (item.Id == category.Id) { item.Name = category.Name; } } response.Status = "3 updated"; // foreach (var item in Program.categories) // { // Console.WriteLine(item); // } } catch (System.Exception e) { } } } else { response.Status = "4 Bad Request"; } } Console.WriteLine(request.ToString()); Console.WriteLine("Response Status: ", response.Status); Console.WriteLine("Response Body: ", response.Status); // Console.WriteLine(response.Status); // foreach (var item in Program.categories) // { // Console.WriteLine(item); // } // implement some kind of cleanup if client sends close message(server sid) // if (msg == "exit2") client.Close(); // Console.WriteLine("{1}: Received: {0}", msg, Thread.CurrentThread.ManagedThreadId); // var serializeObject = new DataContractJsonSerializer(typeof(Response)); var serializedObj = JsonSerializer.Serialize <Response>(response, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); var byteReplyMsg = Encoding.UTF8.GetBytes(serializedObj); stream.Write(byteReplyMsg, 0, byteReplyMsg.Length); Console.WriteLine("{1}: Sent: {0}", response, Thread.CurrentThread.ManagedThreadId); // } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); client.Close(); } }
/// <summary> /// 导出到TEXT /// </summary> /// <param name="dataList"></param> /// <param name="filename"></param> private static void ExportToJson(List<BsonDocument> dataList, String filename) { var sw = new StreamWriter(filename, false); sw.Write(dataList.ToJson(SystemManager.JsonWriterSettings)); sw.Close(); }
public HttpResponseMessage GetAllGroups() { try { var portalId = PortalSettings.PortalId; var filteredRoleGroups = string.Empty; int loginStatus = 1; if (UserInfo == null || (UserInfo != null && UserInfo.UserID < 1)) { loginStatus = 0; // you can only get information if you're logged in Exceptions.LogException(new AccessViolationException("Unauthorized attempt to access GetAllGroups API end point")); // return 404 error simply to discourage hacking return Request.CreateResponse(HttpStatusCode.OK, loginStatus); } // get all role groups var roleGroups = Controllers.RoleController.GetRoleGroups(portalId); if (UserInfo.IsInRole(PortalSettings.AdministratorRoleName) || UserInfo.IsSuperUser) { // return ALL role groups filteredRoleGroups = roleGroups.ToJson(); } else { // get a listing of the unique role group IDs var roleGroupIds = roleGroups.Select(g => g.RoleGroupID).ToList(); var userRoles = Controllers.RoleController.GetUserRoles(UserInfo); // filter the role groups by only those that have a matching role for the user var filteredRoleGroupIds = userRoles.Where(r => roleGroupIds.Contains(r.RoleGroupID)).Select(r => r.RoleGroupID).ToList(); // return only the role groups that the user is a part of var uncleanRoleGroups = roleGroups.Where(g => filteredRoleGroupIds.Contains(g.RoleGroupID)); // remove any roles that the user is not a part of, and system roles var roleGroupsToReturn = new List<RoleGroupInfo>(); foreach (var group in uncleanRoleGroups.ToList()) { var newGroup = new RoleGroupInfo(); newGroup = group; foreach (var role in newGroup.Roles.ToList()) { var roleInfo = (RoleInfo) role.Value; if (roleInfo.IsSystemRole || !UserInfo.IsInRole(roleInfo.RoleName) || roleInfo.Status.ToString() == "Disabled") { newGroup.Roles.Remove(role.Key); } } roleGroupsToReturn.Add(newGroup); } filteredRoleGroups = roleGroupsToReturn.ToJson(); } return Request.CreateResponse(HttpStatusCode.OK, filteredRoleGroups); } catch (Exception exc) { Exceptions.LogException(exc); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } }
/// <summary> /// 邮件分类列表返回JSON /// </summary> /// <returns></returns> public ActionResult EmailCategoryJson() { List <Base_EmailCategory> ListData = DataFactory.Database().FindList <Base_EmailCategory>("CreateUserId", ManageProvider.Provider.Current().UserId); return(Content(ListData.ToJson())); }
public void map_spotify_releases_should_drop_not_found() { var data = new List <SpotifyImportListItemInfo> { new SpotifyImportListItemInfo { Album = "25", AlbumSpotifyId = "7uwTHXmFa1Ebi5flqBosig", Artist = "Adele" } }; var map = new List <SpotifyMap> { new SpotifyMap { SpotifyId = "7uwTHXmFa1Ebi5flqBosig", MusicbrainzId = "0" } }; Mocker.GetMock <IHttpClient>() .Setup(x => x.Post <List <SpotifyMap> >(It.IsAny <HttpRequest>())) .Returns <HttpRequest>(r => new HttpResponse <List <SpotifyMap> >(new HttpResponse(r, new HttpHeader(), map.ToJson()))); var result = Subject.MapSpotifyReleases(data); result.Should().BeEmpty(); }
private async Task <IEnumerable <SellbriteProduct> > GetProductsByPageAsync(DateTime startDateUtc, DateTime endDateUtc, int page, int limit, CancellationToken token) { var mark = Mark.CreateNew(); var products = new List <SellbriteProduct>(); var url = string.Format("{0}?min_modified_at={1}&max_modified_at={2}&page={3}&limit={4}", SellbriteEndPoint.ProductsUrl, startDateUtc.FromUtcToRFC3339(), endDateUtc.FromUtcToRFC3339(), page, limit); try { SellbriteLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo())); var response = await base.GetAsync(url, token).ConfigureAwait(false); products = JsonConvert.DeserializeObject <IEnumerable <Product> >(response).Select(p => p.ToSvProduct()).ToList(); SellbriteLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: products.ToJson(), additionalInfo: this.AdditionalLogInfo())); } catch (Exception ex) { var sellbriteException = new SellbriteException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), ex); SellbriteLogger.LogTraceException(sellbriteException); throw sellbriteException; } return(products); }
public override void DoWork() { try { //Perform required items for logging this.Progressing(); //Your code goes here //To log note this.ScheduleHistoryItem.AddLogNote("STARTING JOB"); stopwatch.Start(); // determine what skirmish to process if (Skirmish_PK == -1) { // get today's skirmishes globalSkirmishes = controller.GetCurrentSkirmishes(); } else { // process a specific skirmish globalSkirmishes = controller.GetSkirmishData(Skirmish_PK); } // get accolades globalAccolades = controller.GetAccolades(); foreach (Skirmish skirmish in globalSkirmishes) { #region Skirmish Initialization // create log file for skirmish this.ScheduleHistoryItem.AddLogNote("CREATE LOG FILE"); logger = File.CreateText(HttpRuntime.AppDomainAppPath + "/DesktopModules/BattleFrameworkModule/logs/" + skirmish.Skirmish_PK + ".txt"); _GAMESTATE.Skirmish_FK = skirmish.Skirmish_PK; // get all data for data warehouse object arrays globalCharacters = controller.GetSkirmishCharacters(skirmish.Skirmish_PK); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms DATA globalCharacters: " + Json.Serialize(globalCharacters)); globalSkills = controller.GetSkillDataFromSkirmishCharacters(skirmish.Skirmish_PK); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms DATA globalSkills: " + Json.Serialize(globalSkills)); globalInitTrack = controller.GetInitiativeTrackFromSkirmish(skirmish.Skirmish_PK); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms DATA globalInitTrack: " + Json.Serialize(globalInitTrack)); globalVotes = controller.GetVoteDataFromSkirmish(skirmish.Skirmish_PK, null); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms DATA globalVotes: " + Json.Serialize(globalVotes)); // reset warehouses globalCombatLog.Clear(); globalCharacterTrackLog.Clear(); skirmishPreparedSkills.Clear(); logger.WriteLine(""); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms BEGIN CHARACTER INITIALIZATION"); // initialize characters foreach(var character in globalCharacters) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SETTING [" + character.Character_Name + "] Max_Health to " + character.Health); character.Max_Health = character.Health; character.Conditions = new Conditions(); character.Conditions.Shield_Enchanters_Character_PK = new List<int>(); character.Conditions.DamageBonus_Enchanters_Character_PK = new List<int>(); character.Conditions.Guarded_Characters_PK = new List<int>(); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Creating character track log for character ..."); globalCharacterTrackLog.Add(new Character_Track_Log(){ Character_FK = character.Character_PK }); } logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms END CHARACTER INITIALIZATION"); logger.WriteLine(""); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms BEGIN SKILL INITIALIZATION"); // initialize passive skills foreach (var skill in globalSkills) { if (skill.bIsPassive) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms PREPARING [" + skill.Skill_Name + "](pk=" + skill.Skill_PK + ") | Preparer: [" + GetCharacter(skill.Character_FK).Character_Name + "] | Exec_Track_Step: " + skill.Exec_Track_Step); skirmishPreparedSkills.Add(new Prepared_Skills() { Skill_PK = skill.Skill_PK, Preparer_Character_FK = skill.Character_FK, Exec_Track_Step = skill.Exec_Track_Step }); } } logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms END SKILL INITIALIZATION"); #endregion // perform skills following initiatve track (should already be sorted from SQL) logger.WriteLine(""); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms BEGIN SKIRMISH(pk=" + skirmish.Skirmish_PK + ")"); foreach (var currAct in globalInitTrack) { _GAMESTATE.Current_Act_Order = currAct.Act_Order; // setup turn track #region TURN TRACK OVERVIEW /** * * TURN TRACK STEPS * Begin Turn * 1 - set active character to this character * 2 - is character stunned? * 3 - special character skills * Determine Skill * 4 - find favored skill * 5 - find favored targets for skill * Preliminary Skill Execution * 6 - target legibility (Invisiblity, Knocked Out, Charmed, ect) * 7 - special character skills * Perform Attack Roll * 8 - determine if skill instantly resolves * 9 - determine if attack has advantage or disadvantage * 10 - roll attack dice for attack and add base modifier * Perform Damage Roll * 11 - determine if attacks are successful and determine damage * 12 - special character skills (pre-damage) * 13 - inflict damage on target * 14 - special character skills (post-damage) * Target Conditions * 15 - determine if target receives any afflictions * 16 - special character skills * End Turn * * */ #endregion // interface Skill FavoredSkill = new Skill(); List<Character> FavoredSkillFavoredTargets = new List<Character>(); var lastTrackStep = 17; #region TURN TRACK // cycle through turn track var currChar = GetCharacter(currAct.Character_FK); for (var currTrackStep = 1; currTrackStep <= lastTrackStep; currTrackStep++) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms BEGIN TRACK STEP [" + currTrackStep + "] for [" + currChar.Character_Name + "]"); _GAMESTATE.Current_Track_Step = currTrackStep; switch (currTrackStep) { #region BEGIN TURN case 1: // 1 - set active character to this character logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SETTING [" + currChar.Character_Name + "](pk=" + currChar.Character_PK + ") as active character"); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM active character:" + Json.Serialize(currChar)); _GAMESTATE.Active_Character = currChar; break; case 2: // 2 - is character stunned? if (currChar.Conditions.bStunned) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Character is stunned, skip to end turn step"); currTrackStep = lastTrackStep; } break; case 3: // 3 - special character skills CheckSpecialSkills(); break; #endregion #region DETERMINE SKILL case 4: // 4 - find favored skill logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Finding favored skill for character to perform ..."); //FavoredSkill = GetSkill(globalVotes.OrderByDescending(x => x.Vote_Count).FirstOrDefault(x => x.Character_FK == currChar.Character_PK).Skill_FK); FavoredSkill = GetFavoredSkill(currChar.Character_PK); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Found favored skill. Skill_Name: [" + FavoredSkill.Skill_Name + "](pk=" + FavoredSkill.Skill_PK + ") | Skill:" + Json.Serialize(FavoredSkill)); _GAMESTATE.Pending_Skill = FavoredSkill; break; case 5: // 5 - find favored targets for skill // targets are separated by commas logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Finding favored targets for skill ..."); if (!globalVotes.Any(x => x.Skill_FK == FavoredSkill.Skill_PK && x.Character_FK == currChar.Character_PK)) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM No targets for this skill, find random target"); if (FavoredSkill.Skill_Type.Contains("Attack") || FavoredSkill.Skill_Type.Contains("Affliction") || FavoredSkill.Skill_Type.Contains("Taunt")) { // skill type is hostile, find random enemy targets for (var i = 1; i < FavoredSkill.Max_Targets; i++) { FavoredSkillFavoredTargets.Add(globalCharacters.FirstOrDefault(x => x.Guild_FK != currChar.Guild_FK && !FavoredSkillFavoredTargets.Contains(x))); } } else { // skill type is friendly, find random friendly targets if (FavoredSkill.Skill_Type == "Blessing,Advantage" || FavoredSkill.Skill_Type == "Blessing,Disadvantage" || FavoredSkill.Skill_Type == "Blessing,Damage" || FavoredSkill.Skill_Type.Contains("Guard")) { // skill cannot target self FavoredSkillFavoredTargets.OrderBy(x => Guid.NewGuid()).FirstOrDefault(x => x.Guild_FK == currChar.Guild_FK && x.Character_PK != currChar.Character_PK && !FavoredSkillFavoredTargets.Contains(x)); } else if (FavoredSkill.Skill_Type == "Blessing,AllStats" || FavoredSkill.Skill_Type == "Blessing,Dodge" || FavoredSkill.Skill_Type == "Blessing,Finesse" || FavoredSkill.Skill_Type == "Blessing,Agility" || FavoredSkill.Skill_Type == "Blessing,Senses" || FavoredSkill.Skill_Type == "Blessing,Mana" || FavoredSkill.Skill_Type == "Blessing,Shield" || FavoredSkill.Skill_Type == "Heal") { // skill can target self FavoredSkillFavoredTargets.OrderBy(x => Guid.NewGuid()).FirstOrDefault(x => x.Guild_FK == currChar.Guild_FK && !FavoredSkillFavoredTargets.Contains(x)); } } } else { var tmpTargets = Array.ConvertAll(globalVotes.FirstOrDefault(x => x.Skill_FK == FavoredSkill.Skill_PK && x.Character_FK == currChar.Character_PK).Targets.Split(','), int.Parse); FavoredSkillFavoredTargets.AddRange( tmpTargets.Select(target => GetCharacter(target))); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Found favored targets [" + Json.Serialize(FavoredSkillFavoredTargets) + "]"); } _GAMESTATE.Pending_Targets = FavoredSkillFavoredTargets; break; #endregion #region PRELIMINARY SKILL EXECUTION case 6: logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Determine target legibility"); // 6 - target legibility (Invisiblity, Knocked Out, Charmed, ect) // no targets acquired during voting, determine random targets if (!FavoredSkillFavoredTargets.Any()) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM no targets were acquired in Voting, determine random targets ..."); for (var i = 0; i < FavoredSkill.Max_Targets; i++) { Character newTarget = new Character(); if (FavoredSkill.Skill_Type == "Attack" || FavoredSkill.Skill_Type == "Taunt" || FavoredSkill.Skill_Type.Contains("Affliction")) { // assign target to random enemy newTarget = globalCharacters.FirstOrDefault(x => x.Guild_FK != currChar.Guild_FK && !x.Conditions.bKnockedOut && !x.Conditions.bInvisible && !FavoredSkillFavoredTargets.Exists(y => y.Character_PK == x.Character_PK)); } if (FavoredSkill.Skill_Type == "Heal") { // assign target to random friendly character (can include self) newTarget = globalCharacters.FirstOrDefault(x => x.Guild_FK == currChar.Guild_FK && !x.Conditions.bKnockedOut && !x.Conditions.bInvisible && !FavoredSkillFavoredTargets.Exists(y => y.Character_PK == x.Character_PK)); } if (FavoredSkill.Skill_Type.Contains("Blessing") || FavoredSkill.Skill_Type.Contains("Guard")) { // assign target to random ally newTarget = globalCharacters.FirstOrDefault(x => x.Guild_FK == currChar.Guild_FK && x.Character_PK != currChar.Character_PK && !x.Conditions.bKnockedOut && !x.Conditions.bInvisible && !FavoredSkillFavoredTargets.Exists(y => y.Character_PK == x.Character_PK)); } if(newTarget != null) FavoredSkillFavoredTargets.Add(newTarget); } logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM new targets: " + Json.Serialize(FavoredSkillFavoredTargets)); } foreach (var target in FavoredSkillFavoredTargets.ToList()) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM target=[" + target.Character_Name + "] |" + " bInvisible:" + target.Conditions.bInvisible + " | bKnockedOut:" + target.Conditions.bKnockedOut + " | bCharmed:" + target.Conditions.bCharmed + " | bTaunted:" + target.Conditions.bTaunted + " | bBlinded:" + target.Conditions.bBlinded + " | bGuarded:" + target.Conditions.bGuarded); // check if character has skills to bypass normal targetting rules CheckSpecialSkills(); // target is either Invisible or Knocked Out, reassign to random enemy if (target.Conditions.bInvisible || target.Conditions.bKnockedOut) { // remove old target from target list logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM target is invisible or knocked out, remove target from favored target list | Skill_Type:" + FavoredSkill.Skill_Type); FavoredSkillFavoredTargets.Remove(target); // ignore target reassignment if skill is an AoE attack that targets the entire team if (FavoredSkill.Max_Targets < 12) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM assign a new target | Skill_Type:" + FavoredSkill.Skill_Type); Character newTarget = new Character(); switch (FavoredSkill.Skill_Type) { case "Attack": case "Taunt": case "Affliction,Stunned": case "Affliction,Blinded": case "Affliction,Disadvantage": case "Affliction,Advantage": case "Affliction,StatDebuff": // find new target not on this character's team newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()) .FirstOrDefault( x => x.Guild_FK != currChar.Guild_FK && !FavoredSkillFavoredTargets.Exists( y => y.Character_PK == x.Character_PK) && !x.Conditions.bInvisible && !x.Conditions.bKnockedOut); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM New target found | {" + Json.Serialize(newTarget) + "}"); break; case "Heal": // find new target that is on this character's team that has less than full health newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()) .FirstOrDefault( x => x.Guild_FK == currChar.Guild_FK && x.Health < x.Max_Health && !FavoredSkillFavoredTargets.Exists( y => y.Character_PK == x.Character_PK) && !x.Conditions.bInvisible && !x.Conditions.bKnockedOut); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM New target found | {" + Json.Serialize(newTarget) + "}"); break; case "Blessing,Disadvantage": case "Blessing,Advantage": case "Blessing,Damage": // find new target on this character's team newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()) .FirstOrDefault( x => x.Guild_FK == currChar.Guild_FK && !FavoredSkillFavoredTargets.Exists( y => y.Character_PK == x.Character_PK) && !x.Conditions.bInvisible && !x.Conditions.bKnockedOut); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM New target found | {" + Json.Serialize(newTarget) + "}"); break; case "Blessing,StatBuff": case "Blessing,Shield": // find new target on this character's team that is NOT this character newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()) .FirstOrDefault( x => x.Guild_FK == currChar.Guild_FK && !FavoredSkillFavoredTargets.Exists( y => y.Character_PK == x.Character_PK) && !x.Conditions.bInvisible && !x.Conditions.bKnockedOut && x.Character_PK != currChar.Character_PK); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM New target found | {" + Json.Serialize(newTarget) + "}"); break; } if (FavoredSkill.Skill_Type.Contains("Guard")) { newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()) .FirstOrDefault( x => x.Guild_FK == currChar.Guild_FK && !FavoredSkillFavoredTargets.Exists( y => y.Character_PK == x.Character_PK) && !x.Conditions.bInvisible && !x.Conditions.bKnockedOut && x.Character_PK != currChar.Character_PK); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM New target found | {" + Json.Serialize(newTarget) + "}"); } // ensure a target was found, then add it if (newTarget != null) { if (newTarget.Character_PK != 0) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM adding new target to favored targets | " + Json.Serialize(newTarget)); FavoredSkillFavoredTargets.Add(newTarget); } } } } // if character is Charmed if (currChar.Conditions.bCharmed) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM target is charmed, reassign target to random ally"); // remove old target from target list FavoredSkillFavoredTargets.Remove(target); Character newTarget = new Character(); // assign new target to random ally newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()).FirstOrDefault(x => x.Guild_FK == currChar.Guild_FK && currChar.Conditions.Charm_Character_PK != x.Character_PK && !FavoredSkillFavoredTargets.Exists(y => y.Character_PK == x.Character_PK && x.Conditions.bInvisible && x.Conditions.bKnockedOut)); // ensure a target was found, then add it if (newTarget != null) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM target acquired, add to favored targets | newTarget:" + Json.Serialize(newTarget)); FavoredSkillFavoredTargets.Add(newTarget); } } // if character is Taunted - ignore Blessing, Heal, and Guard skill types when Taunted if (currChar.Conditions.bTaunted && FavoredSkill.Max_Targets < 12 && !FavoredSkill.Skill_Type.Contains("Blessing") && !FavoredSkill.Skill_Type.Contains("Heal") && !FavoredSkill.Skill_Type.Contains("Guard")) { // ensure taunter is still a legal target - otherwise maintain favored targets Boolean bTaunterTargettable = globalCharacters.Contains(globalCharacters.FirstOrDefault(x => x.Character_PK == currChar.Conditions.Taunted_Character_PK && !x.Conditions.bInvisible && !x.Conditions.bKnockedOut)); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM character is taunted, reassign target to taunter if able | TaunterCharPK:" + target.Conditions.Taunted_Character_PK + " | bTaunterTargettable:" + bTaunterTargettable); if (bTaunterTargettable) { // remove old target from target list FavoredSkillFavoredTargets.Remove(target); Character newTarget = new Character(); // assign new target to taunter newTarget = globalCharacters.FirstOrDefault(x => x.Character_PK == currChar.Conditions.Taunted_Character_PK); // ensure a target was found, then add it if (newTarget != null) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM taunter is targettable, add to favored targets | newTarget:{" + Json.Serialize(newTarget) + "}"); FavoredSkillFavoredTargets.Add(newTarget); } } } // if character is Blinded if (currChar.Conditions.bBlinded) { Character newTarget = new Character(); if (FavoredSkill.Skill_Type.Contains("Guard")) { // blinded character is attempting to guard, must reassign to random ally logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM character is blinded and attempting to guard, reassign target to random ally"); // remove old target from target list FavoredSkillFavoredTargets.Remove(target); // assign new target to random character (even ally) newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()).FirstOrDefault(x => x.Guild_FK == currChar.Guild_FK && !x.Conditions.bInvisible && !x.Conditions.bKnockedOut && x.Character_PK != currChar.Character_PK); } else { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM character is blinded, reassign target to random character"); // remove old target from target list FavoredSkillFavoredTargets.Remove(target); // assign new target to random character (even ally) newTarget = globalCharacters.OrderBy(x => Guid.NewGuid()).FirstOrDefault(x => !x.Conditions.bInvisible && !x.Conditions.bKnockedOut && x.Character_PK != currChar.Character_PK); } // ensure a target was found, then add it if (newTarget != null) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM target acquired, add to favored targets | newTarget:{" + Json.Serialize(newTarget) + "}"); FavoredSkillFavoredTargets.Add(newTarget); } else { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM no new target could be found"); } } // if target is Guarded - ignore Blessing, Heal, and Guard skill types when Guarded if (target.Conditions.bGuarded && !FavoredSkill.Skill_Type.Contains("Blessing") && !FavoredSkill.Skill_Type.Contains("Heal") && !FavoredSkill.Skill_Type.Contains("Guard")) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM target is guarded, reassign target to guard character"); // remove old target from target list FavoredSkillFavoredTargets.Remove(target); Character newTarget = new Character(); // assign new target to guard newTarget = globalCharacters.FirstOrDefault(x => x.Character_PK == target.Conditions.Guarded_Characters_PK.OrderByDescending(y => y).FirstOrDefault()); // ensure a target was found, then add it if (newTarget != null) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM target acquired, add to favored targets | newTarget:{" + Json.Serialize(newTarget) + "}"); FavoredSkillFavoredTargets.Add(newTarget); } } } // ensure at least one target exists after validation, unless skill is a prepared skill if (FavoredSkillFavoredTargets.Count == 0) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM no valid targets available - end the turn"); currTrackStep = lastTrackStep; } break; case 7: // 7 - special character skills CheckSpecialSkills(); break; #endregion #region PERFORM ATTACK ROLL case 8: // 8 - determine if skill instantly resolves // skip this step if skill is hostile and won't instantly resolve if (!FavoredSkill.Skill_Type.Contains("Blessing") && !FavoredSkill.Skill_Type.Contains("Guard")) continue; var bEndTheTurn = false; foreach (var target in FavoredSkillFavoredTargets) { Combat_Log newCombatLogEntry = new Combat_Log(); newCombatLogEntry.Action_Order = currAct.Act_Order; //newCombatLogEntry.Conditions newCombatLogEntry.Assailant_Character_FK = currChar.Character_PK; newCombatLogEntry.Skill_FK = FavoredSkill.Skill_PK; newCombatLogEntry.Target_Character_FK = target.Character_PK; newCombatLogEntry.Skirmish_FK = skirmish.Skirmish_PK; newCombatLogEntry.tmpDamage_Final_Result = new List<int>(); newCombatLogEntry.Skirmish_FK = skirmish.Skirmish_PK; switch (FavoredSkill.Skill_Type) { case "Blessing,Advantage": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Advantage on [" + target.Character_Name + "]"); target.Conditions.bAttackAdvantage = true; // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; case "Blessing,Disadvantage": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Disadvantage on [" + target.Character_Name + "]"); target.Conditions.bDefendAdvantage = true; // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; case "Blessing,Shield": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Shield(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Conditions.bShielded = true; target.Conditions.Shield += Int32.Parse(FavoredSkill.Damage_Roll); target.Conditions.Shield_Enchanters_Character_PK.Add(currChar.Character_PK); newCombatLogEntry.Damage_Final_Result = Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Bestow", 1); bEndTheTurn = true; break; case "Blessing,Damage": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Damage(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Conditions.bDamageBonus = true; target.Conditions.DamageBonus += Int32.Parse(FavoredSkill.Damage_Roll); target.Conditions.DamageBonus_Enchanters_Character_PK.Add(currChar.Character_PK); newCombatLogEntry.Damage_Final_Result = Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Bestow", 1); bEndTheTurn = true; break; case "Blessing,AllStats": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,AllStats(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Finesse += Int32.Parse(FavoredSkill.Damage_Roll); target.Agility += Int32.Parse(FavoredSkill.Damage_Roll); target.Senses += Int32.Parse(FavoredSkill.Damage_Roll); target.Mana += Int32.Parse(FavoredSkill.Damage_Roll); target.Dodge += Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; case "Blessing,Finesse": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Finesse(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Finesse += Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; case "Blessing,Agility": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Agility(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Agility += Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; case "Blessing,Senses": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Senses(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Senses += Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; case "Blessing,Mana": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Mana(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Mana += Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; case "Blessing,Dodge": logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM casting Blessing,Dodge(" + FavoredSkill.Damage_Roll + ") on [" + target.Character_Name + "]"); target.Dodge += Int32.Parse(FavoredSkill.Damage_Roll); // record accolade UpdateCharacterTrackLog(currChar.Character_PK, "Blessing_Stat_Buff", 1); bEndTheTurn = true; break; } // dynamic skill types if (FavoredSkill.Skill_Type.Contains("Guard")) { // determine how many guard this character can perform var amtOfGuard = Int32.Parse(FavoredSkill.Skill_Type.Split(',')[1]); for (var i = 1; i <= amtOfGuard; i++) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM guarding [" + target.Character_Name + "]"); target.Conditions.bGuarded = true; target.Conditions.Guarded_Characters_PK.Add(currChar.Character_PK); } bEndTheTurn = true; } // record entry globalCombatLog.Add(newCombatLogEntry); } // end the turn if (bEndTheTurn) currTrackStep = lastTrackStep; break; case 9: // 9 - determine if attack is rolled with advantage or disadvantage // REMOVE THIS TRACK STEP break; case 10: // 10 - roll attack dice for attack and add base modifier // loop through all targets and perform attacks foreach (var target in FavoredSkillFavoredTargets) { // create new combat log entry Combat_Log newCombatLogEntry = new Combat_Log(); newCombatLogEntry.Action_Order = globalInitTrack.FirstOrDefault(x => x.Character_FK == currChar.Character_PK).Act_Order; //newCombatLogEntry.Conditions newCombatLogEntry.Assailant_Character_FK = currChar.Character_PK; newCombatLogEntry.Skill_FK = FavoredSkill.Skill_PK; newCombatLogEntry.Target_Character_FK = target.Character_PK; newCombatLogEntry.Skirmish_FK = skirmish.Skirmish_PK; newCombatLogEntry.tmpDamage_Final_Result = new List<int>(); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM preliminary attack calculation | (bAttackAdvantage:" + currChar.Conditions.bAttackAdvantage + " | bAttackDisadvantage:" + currChar.Conditions.bAttackDisadvantage + ") | TARGET (bAttackAdvantage:" + target.Conditions.bAttackAdvantage + " | bAttackDisadvantage:" + target.Conditions.bAttackDisadvantage + ")"); if (currChar.Conditions.bAttackAdvantage || currChar.Conditions.bAttackDisadvantage) { var finalAdvDis = 0; // 0 = roll normally. -1 = roll disadvantage. 1 = roll advantage if (currChar.Conditions.bAttackAdvantage) finalAdvDis++; if (currChar.Conditions.bAttackDisadvantage) finalAdvDis--; if (target.Conditions.bDefendAdvantage) finalAdvDis++; if (target.Conditions.bDefendDisadvantage) finalAdvDis--; // determine final result (coded this way because character could have both advantage & disadvantage) logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM final preliminary attack calculation | finalAdvDis:" + finalAdvDis); if (finalAdvDis == 0) { currChar.Conditions.bAttackAdvantage = false; currChar.Conditions.bAttackDisadvantage = false; } else if (finalAdvDis > 0) { currChar.Conditions.bAttackAdvantage = true; currChar.Conditions.bAttackDisadvantage = false; } else if (finalAdvDis < 0) { currChar.Conditions.bAttackAdvantage = false; currChar.Conditions.bAttackDisadvantage = true; } } // don't roll if the attack is auto successful or the skill is a heal if (!FavoredSkill.bAutoSuccess) { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM rolling attack against [" + target.Character_Name + "] ..."); // perform roll with a d20 Int32 rollDiceRoll = 0; // reroll if character has advantage or disadvantage if (currChar.Conditions.bAttackAdvantage) { // perform roll with two d20's, taking the higher roll Int32 rollDiceReroll = rand.Next(1, 21); // record roll data newCombatLogEntry.Attack_Values = rollDiceRoll + "," + rollDiceReroll; if (rollDiceReroll > rollDiceRoll) rollDiceRoll = rollDiceReroll; } else if (currChar.Conditions.bAttackDisadvantage) { // perform roll with two d20's, taking the lower roll Int32 rollDiceReroll = rand.Next(1, 21); // record roll data newCombatLogEntry.Attack_Values = rollDiceRoll + "," + rollDiceReroll; if (rollDiceReroll < rollDiceRoll) rollDiceRoll = rollDiceReroll; } else { // perform roll with a d20 rollDiceRoll = rand.Next(1, 21); // record roll data newCombatLogEntry.Attack_Values = rollDiceRoll.ToString(); } logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM roll(s) achieved | Attack_Values:" + newCombatLogEntry.Attack_Values); // record accolades if (rollDiceRoll == 1) { // critical failure achieved UpdateCharacterTrackLog(currChar.Character_PK, "Critical_Fails", 1); } else if (rollDiceRoll == 20) { // critical success achieved UpdateCharacterTrackLog(currChar.Character_PK, "Critical_Successes", 1); } // add base modifiers switch (FavoredSkill.Attribute_FK) { case "Finesse": rollDiceRoll += currChar.Finesse; break; case "Agility": rollDiceRoll += currChar.Agility; break; case "Senses": rollDiceRoll += currChar.Senses; break; case "Mana": rollDiceRoll += currChar.Mana; break; } // record roll result newCombatLogEntry.Attack_Final_Result = rollDiceRoll; logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM final attack result with modifier[" + FavoredSkill.Attribute_FK + "] | Attack_Final_Result:" + rollDiceRoll); } // record new combat log globalCombatLog.Add(newCombatLogEntry); // check for special character skills after rolling attack CheckSpecialSkills(); } break; #endregion #region PERFORM DAMAGE ROLL case 11: // 11 - determine if attacks are successful and determine damage // get combat logs regarding this character performed favored skill - it is possible this attack targets multiple targets var relativeAttackCombatLogs = globalCombatLog.Where(x => x.Action_Order == globalInitTrack.FirstOrDefault(y => y.Character_FK == currChar.Character_PK).Act_Order && !x.bInterrupt); foreach (var log in relativeAttackCombatLogs) { Character targetChar = GetCharacter(log.Target_Character_FK); // determine if attack is successful logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM calculating if attack was successful ... | Attack_Final_Result:" + log.Attack_Final_Result + " | Target's Dodge:" + targetChar.Dodge + " | bAutoSuccess:" + FavoredSkill.bAutoSuccess); log.bAttackSuccessful = (log.Attack_Final_Result >= targetChar.Dodge || FavoredSkill.bAutoSuccess); if (log.bAttackSuccessful) { // attack is successful - roll damage List<string> rollArray = FavoredSkill.Damage_Roll.Split(',').ToList(); List<int> damageRolls = new List<int>(); // stores all damage rolls logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM attack successful, rolling damage ..."); foreach (var roll in rollArray) { if (roll == "0d0+0") { // don't perform a real roll on 0d0+0 log.tmpDamage_Final_Result.Add(0); log.Damage_Types = FavoredSkill.Damage_Types; continue; } logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM rolling [" + roll + "]"); string rollSet = roll.Substring(0, roll.IndexOf("+")); // extract "XdX" from "XdX+X" Int32 rollDiceAmt = Int32.Parse(rollSet.Substring(0, rollSet.IndexOf("d"))); Int32 rollDiceType = Int32.Parse(rollSet.Substring(rollSet.IndexOf("d") + 1)); Int32 rollModifier = Int32.Parse(roll.Substring(roll.IndexOf("+") + 1)); // extract "+X" from "XdX+X" Int32 rollFinalResult = 0; // roll dice for each amount required for (var x = 1; x <= rollDiceAmt; x++) { Int32 rollResult = rand.Next(1, rollDiceType + 1); // record damage roll damageRolls.Add(rollResult); // accumulate results rollFinalResult += rollResult; } // add modifiers switch (FavoredSkill.Attribute_FK) { case "Finesse": rollFinalResult += currChar.Finesse; break; case "Agility": rollFinalResult += currChar.Agility; break; case "Senses": rollFinalResult += currChar.Senses; break; case "Mana": rollFinalResult += currChar.Mana; break; } rollFinalResult += rollModifier; log.tmpDamage_Final_Result.Add(rollFinalResult); log.Damage_Types = FavoredSkill.Damage_Types; logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM final damage calculation | Damage_Final_Result:" + rollFinalResult + " | Damage_Types:" + FavoredSkill.Damage_Types); } // THIS IS PERFORMED IN STEP 13 // check if character has pending bonus damage //if (currChar.Conditions.bDamageBonus) //{ // log.Damage_Final_Result += currChar.Conditions.DamageBonus; // logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM bonus damage awarded | DamageBonus:" + currChar.Conditions.DamageBonus); // foreach (var enchanter in currChar.Conditions.DamageBonus_Enchanters_Character_PK) // { // // award each enchanter bonus accolades on how much bonus damage current character was granted // var enchantSkill = globalCombatLog.FirstOrDefault(x => x.Target_Character_FK == currChar.Character_PK && x.Assailant_Character_FK == enchanter).Skill_FK; // UpdateCharacterTrackLog(enchanter, "Blessing_Bonus_Damage", Int32.Parse(globalSkills.FirstOrDefault(x => x.Skill_PK == enchantSkill).Damage_Roll)); // } // // clear out damage bonus // currChar.Conditions.bDamageBonus //} } else { // target dodged attack UpdateCharacterTrackLog(targetChar.Character_PK, "Attacks_Dodged", 1); } } break; case 12: // 12 - special character skills (pre-damage) CheckSpecialSkills(); break; case 13: // 13 - inflict damage on target // get combat logs regarding this character performed favored skill - it is possible this attack targets multiple targets var relativeDamageCombatLogs = globalCombatLog.Where(x => x.Action_Order == currAct.Act_Order && x.bAttackSuccessful); foreach (var log in relativeDamageCombatLogs) { List<int> tmpDamageResults = log.tmpDamage_Final_Result; List<int> tmpDamageValues = new List<int>(); List<string> tmpDamageTypes = log.Damage_Types.Split(',').ToList(); Character target = GetCharacter(log.Target_Character_FK); Character assailant = GetCharacter(log.Assailant_Character_FK); Int32 overallDamageResult = 0; foreach (var dmgRoll in tmpDamageResults) { var finalDamageResult = dmgRoll; logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM inflict damage on target | finalDamageResult:" + dmgRoll + " | Vulnerabilities:[" + target.Vulnerabilities + "] | Resistances:[" + target.Resistances + "] | Immunities:[" + target.Immunities + "] | " + Json.Serialize(target)); if (target.Vulnerabilities != null) { // consider target vulnerabilities List<string> vulnerabilities = target.Vulnerabilities.Split(',').ToList(); var bVulnerableToAttack = vulnerabilities.Exists(x => x == tmpDamageTypes[tmpDamageResults.IndexOf(dmgRoll)]); // target is vulnerable to damage - deal double damage if (bVulnerableToAttack) finalDamageResult += dmgRoll; } if (target.Resistances != null) { // consider target resistances List<string> resistances = target.Resistances.Split(',').ToList(); var bResistantToAttack = resistances.Exists(x => x == tmpDamageTypes[tmpDamageResults.IndexOf(dmgRoll)]); // target is resistance to damage - deal half damage, rounded up if (bResistantToAttack) finalDamageResult -= (int)Math.Ceiling((double)dmgRoll / 2); } if (target.Immunities != null) { // consider target immunities List<string> immunities = target.Immunities.Split(',').ToList(); var bImmuneToAttack = immunities.Exists(x => x == tmpDamageTypes[tmpDamageResults.IndexOf(dmgRoll)]); // target is immune to damage - negate all damage if (bImmuneToAttack) finalDamageResult = 0; } // inflict damage on target if (FavoredSkill.Skill_Type != "Heal") { // check for bonus damage if (assailant.Conditions.bDamageBonus) { foreach (var enchanter in assailant.Conditions.DamageBonus_Enchanters_Character_PK.OrderByDescending(x => x)) { // find relative combat log var relativeCombatLog = globalCombatLog.FirstOrDefault(x => x.Target_Character_FK == assailant.Character_PK && x.Assailant_Character_FK == enchanter); // determine how much damage bonus enchanter granted Int32 grantedBonusDamage = Int32.Parse(globalSkills.FirstOrDefault(x => x.Skill_PK == relativeCombatLog.Skill_FK).Damage_Roll); // buff damage finalDamageResult += grantedBonusDamage; tmpDamageValues.Add(grantedBonusDamage); log.Damage_Types += ",True"; // record accolades UpdateCharacterTrackLog(enchanter, "Blessing_Bonus_Damage", grantedBonusDamage); } // clear out character bonus damage assailant.Conditions.bDamageBonus = false; assailant.Conditions.DamageBonus = 0; assailant.Conditions.DamageBonus_Enchanters_Character_PK.Clear(); } // skill type inflicts damage logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM [" + target.Character_Name + "] taking " + finalDamageResult + " " + tmpDamageTypes[tmpDamageResults.IndexOf(dmgRoll)] + " damage"); // check for shield if (target.Conditions.bShielded) { target.Conditions.Shield -= finalDamageResult; if (target.Conditions.Shield < 0) { target.TakeDamage(target.Conditions.Shield * -1); target.Conditions.Shield = 0; target.Conditions.bShielded = false; target.Conditions.Shield_Enchanters_Character_PK.Clear(); } // record accolades for enchanter who granted shield var tmpAttackDmg = finalDamageResult; foreach (var enchanter in target.Conditions.Shield_Enchanters_Character_PK.OrderByDescending(x => x)) { // find relative combat log where enchanter shielded target var relativeCombatLog = globalCombatLog.FirstOrDefault(x => x.Target_Character_FK == target.Character_PK && x.Assailant_Character_FK == enchanter); // determine how much shield the enchanter provided Int32 shieldAmtGranted = Int32.Parse(globalSkills.FirstOrDefault(x => x.Skill_PK == relativeCombatLog.Skill_FK).Damage_Roll); // accumulate how much damage the target has taken prior to this attack int previousDamage = globalCombatLog.Where(x => x.Target_Character_FK == target.Character_PK && x.Action_Order < currAct.Act_Order).Sum(x => x.Damage_Final_Result); // perform calculations tmpAttackDmg -= (shieldAmtGranted - previousDamage); if (tmpAttackDmg > 0) { if (GetCharacter(enchanter).Archetype.Contains("Enchanter") || GetCharacter(enchanter).Archetype.Contains("Hunter")) UpdateCharacterTrackLog(enchanter, "Blessing_Shield_Absorb", shieldAmtGranted); // shield did not absorb all damage logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM [" + globalCharacters.FirstOrDefault(x => x.Character_PK == enchanter).Character_Name + "] shielded [" + target.Character_Name + "] for " + shieldAmtGranted + " damage"); target.Conditions.Shield_Enchanters_Character_PK.Remove(enchanter); } else { if (GetCharacter(enchanter).Archetype.Contains("Enchanter") || GetCharacter(enchanter).Archetype.Contains("Hunter")) UpdateCharacterTrackLog(enchanter, "Blessing_Shield_Absorb", finalDamageResult); // shield absorbed all damage logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM [" + globalCharacters.FirstOrDefault(x => x.Character_PK == enchanter).Character_Name + "] shielded [" + target.Character_Name + "] for " + finalDamageResult + " damage"); break; } } // reduce total shield target.Conditions.Shield -= tmpAttackDmg; if (target.Conditions.Shield <= 0) { // clear out shield data if reduced to 0 target.Conditions.Shield = 0; target.Conditions.bShielded = false; target.Conditions.Shield_Enchanters_Character_PK.Clear(); } // take damage if remaining damage after shield calculations if (tmpAttackDmg > 0) { target.TakeDamage(finalDamageResult); } } else { // take damage target.TakeDamage(finalDamageResult); } } else { // skill type heals health logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM [" + target.Character_Name + "] healing (" + finalDamageResult + ") health"); target.Heal(finalDamageResult); } // accumulate overall damage for combat log overallDamageResult += finalDamageResult; tmpDamageValues.Add(finalDamageResult); } // record overall damage log.Damage_Final_Result = overallDamageResult; log.Damage_Values = tmpDamageValues.ToJson(); // record accolade if (target.Conditions.bKnockedOut) { UpdateCharacterTrackLog(assailant.Character_PK, "Opponent_Knock_Outs", 1); List<Character> Accolade_Assist_Awarded = new List<Character>(); foreach (var assistant in globalCombatLog.Where(x => x.Target_Character_FK == target.Character_PK && x.Damage_Final_Result > 0 && x.Damage_Types != null && !x.Damage_Types.Contains("Healing") && x.Assailant_Character_FK != assailant.Character_PK)) { if (!Accolade_Assist_Awarded.Exists(x => x.Character_PK == assistant.Assailant_Character_FK)) { UpdateCharacterTrackLog(assistant.Assailant_Character_FK, "Assist_Knock_Outs", 1); Accolade_Assist_Awarded.Add(GetCharacter(assistant.Assailant_Character_FK)); } } } } break; case 14: // 14 - special character skills (post-damage) CheckSpecialSkills(); break; #endregion #region TARGET CONDITIONS case 15: // 15 - determine if target receives any afflictions // get combat logs regarding this character performed favored skill - it is possible this attack targets multiple targets var relativeConditionCombatLogs = globalCombatLog.Where(x => x.Action_Order == globalInitTrack.FirstOrDefault(y => y.Character_FK == currChar.Character_PK).Act_Order); foreach (var log in relativeConditionCombatLogs) { // ignore passives that interrupted current action when inflicting conditions if (log.bInterrupt) continue; Character targetChar = GetCharacter(log.Target_Character_FK); // determine conditions if attack was successful if (log.bAttackSuccessful) { bool bSpecialRuleInflictCondition = true; // skill requires a minimum attack result to inflict condition if (FavoredSkill.Special_Min_Roll != null) { // check if minimum result required was met // IMPORTANT - always inflict condition if min roll equals 0 if (log.Attack_Final_Result < FavoredSkill.Special_Min_Roll && FavoredSkill.Special_Min_Roll != 0) bSpecialRuleInflictCondition = false; } if (bSpecialRuleInflictCondition) { // inflict afflictions if (FavoredSkill.Skill_Type.Contains("Affliction")) { var affliction = FavoredSkill.Skill_Type.Substring(FavoredSkill.Skill_Type.IndexOf(',') + 1); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM inflict Affliction(" + affliction + ") on target "); switch (affliction) { case "Stunned": targetChar.Conditions.bStunned = true; log.Conditions = 1; break; case "Blinded": targetChar.Conditions.bBlinded = true; log.Conditions = 2; break; case "Charmed": targetChar.Conditions.bCharmed = true; log.Conditions = 6; targetChar.Conditions.Charm_Character_PK = currChar.Character_PK; break; } // dynamic afflictions if (affliction.Contains("AllStats") || affliction.Contains("Finesse") || affliction.Contains("Agility") || affliction.Contains("Senses") || affliction.Contains("Mana") || affliction.Contains("Dodge")) { var debuff = affliction.Split('-'); // [0] = type | [1] = amount switch (debuff[0]) { case "AllStats": targetChar.Finesse -= Int32.Parse(debuff[1]); targetChar.Agility -= Int32.Parse(debuff[1]); targetChar.Senses -= Int32.Parse(debuff[1]); targetChar.Mana -= Int32.Parse(debuff[1]); targetChar.Dodge -= Int32.Parse(debuff[1]); break; case "Finesse": targetChar.Finesse -= Int32.Parse(debuff[1]); break; case "Agility": targetChar.Agility -= Int32.Parse(debuff[1]); break; case "Senses": targetChar.Senses -= Int32.Parse(debuff[1]); break; case "Mana": targetChar.Mana -= Int32.Parse(debuff[1]); break; case "Dodge": targetChar.Dodge -= Int32.Parse(debuff[1]); break; } // ensure no stat goes below 0 if (targetChar.Finesse < 0) targetChar.Finesse = 0; if (targetChar.Agility < 0) targetChar.Agility = 0; if (targetChar.Senses < 0) targetChar.Senses = 0; if (targetChar.Mana < 0) targetChar.Mana = 0; if (targetChar.Dodge < 0) targetChar.Dodge = 0; } // record accolade if(currChar.Archetype.Contains("Enchanter") || currChar.Archetype.Contains("Hunter")) UpdateCharacterTrackLog(currChar.Character_PK, "Afflictions_Inflicted", 1); } // inflict taunt if (FavoredSkill.Skill_Type == "Taunt") { logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM inflict Taunt on [" + targetChar.Character_Name + "]"); targetChar.Conditions.bTaunted = true; targetChar.Conditions.Taunted_Character_PK = currChar.Character_PK; log.Conditions = 8; } } } } break; case 16: //// 16 - check if skill can perform multiple attacks //if (FavoredSkill.Skill_Type.Contains("MultiAttack")) //{ // var relativeCombatLog = globalCombatLog.FirstOrDefault(x => x.Assailant_Character_FK == currChar.Character_PK && x.Skill_FK == FavoredSkill.Skill_PK); // // perform another turn if attack was successful or attack result equals or exceeds minimum roll required // if(relativeCombatLog.bAttackSuccessful && (relativeCombatLog.Attack_Final_Result > FavoredSkill.Special_Min_Roll || FavoredSkill.Special_Min_Roll == 0)) // currTrackStep = 1; // // EXCEPTION // // Cannot perform additional turns if skill type is a single target multi attack and the target has been knocked out // if (FavoredSkill.Skill_Type == "MultiAttack,Single" && // globalCharacters.FirstOrDefault( // x => x.Character_PK == relativeCombatLog.Target_Character_FK) // .Conditions.bKnockedOut) // currTrackStep = 16; //} break; case 17: // 17 - special character skills CheckSpecialSkills(); break; #endregion } logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms END TRACK STEP [" + currTrackStep + "] for [" + currChar.Character_Name + "]"); } #endregion } #region COMBAT LOG MANAGEMENT // push combat log to server logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Push combat log to server ..."); controller.CreateCombatLogForSkirmish(globalCombatLog); #endregion #region ACCOLADE MANAGEMENT logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Recording character accolades ..."); foreach (var log in globalCombatLog) { Skill performedSkill = globalSkills.FirstOrDefault(x => x.Skill_PK == log.Skill_FK); Character assailantCharacter = globalCharacters.FirstOrDefault(x => x.Character_PK == log.Assailant_Character_FK); Character targetCharacter = globalCharacters.FirstOrDefault(x => x.Character_PK == log.Target_Character_FK); switch (performedSkill.Skill_Type) { // special skills need to track accolades in their own way case "Taunt": case "Affliction,Disadvantage": case "Affliction,Advantage": case "Affliction,Blinded": case "Affliction,Charmed": case "Affliction,Stunned": case "Attack": if (log.bAttackSuccessful) { UpdateCharacterTrackLog(assailantCharacter.Character_PK, "Damage_Dealt", log.Damage_Final_Result); if (targetCharacter.Archetype.Contains("Tank") || targetCharacter.Archetype.Contains("Bruiser")) UpdateCharacterTrackLog(targetCharacter.Character_PK, "Damage_Taken", log.Damage_Final_Result); } break; case "Heal": UpdateCharacterTrackLog(assailantCharacter.Character_PK, "Health_Regained", log.Damage_Final_Result); break; } } logger.WriteLine(""); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms END SKIRMISH"); // check for all who survived foreach (var character in globalCharacters) { if (!character.Conditions.bKnockedOut) { UpdateCharacterTrackLog(character.Character_PK, "Skirmishes_Survived", 1); } else { UpdateCharacterTrackLog(character.Character_PK, "Self_Knock_Outs", 1); } } // accolade for character that acted first UpdateCharacterTrackLog( globalInitTrack.OrderBy(x => x.Act_Order).FirstOrDefault().Character_FK, "Initiative_Acted_First", 1); // check for guild win foreach (var accoladeLog in globalCharacterTrackLog) { var charAccoladeTotal = accoladeLog.Damage_Dealt + accoladeLog.Damage_Taken + accoladeLog.Opponent_Knock_Outs + accoladeLog.Self_Knock_Outs + accoladeLog.Assist_Knock_Outs + accoladeLog.Attacks_Dodged + accoladeLog.Critical_Successes + accoladeLog.Critical_Fails + accoladeLog.Health_Regained + accoladeLog.Skirmishes_Survived + accoladeLog.Afflictions_Inflicted + accoladeLog.Initiative_Acted_First + accoladeLog.Blessing_Bestow + accoladeLog.Blessing_Shield_Absorb + accoladeLog.Blessing_Bonus_Damage + accoladeLog.Blessing_Stat_Buff; if (GetCharacter(accoladeLog.Character_FK).Guild_FK == skirmish.Guild_1_FK) { skirmish.Guild_1_Accolade_Points += charAccoladeTotal; } else if (GetCharacter(accoladeLog.Character_FK).Guild_FK == skirmish.Guild_2_FK) { skirmish.Guild_2_Accolade_Points += charAccoladeTotal; } } // check for victory var victorGuildFK = (skirmish.Guild_1_Accolade_Points > skirmish.Guild_2_Accolade_Points ? skirmish.Guild_1_FK : skirmish.Guild_2_FK); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Guild Winner: " + victorGuildFK + " | Guild1(pk=" + skirmish.Guild_1_FK + ") : " + skirmish.Guild_1_Accolade_Points + " - Guild2(pk=" + skirmish.Guild_2_FK + "): " + skirmish.Guild_2_Accolade_Points); // update guild win bonus for each character track log foreach (var character in globalCharacters.Where(x => x.Guild_FK == victorGuildFK)) UpdateCharacterTrackLog(character.Character_PK, "Guild_Win_Bonus", 1); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Push character track log to server ..."); // push character track log to server controller.CreateCharacterTrackLogForSkirmish(globalCharacterTrackLog); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Push accolades to server ..."); // update user accolades on server controller.UpdateUserAccolades(skirmish.Skirmish_PK); #endregion #region CHARACTER MANAGEMENT // update character energy for each character that performed a skill in the skirmish logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Updating all character energy ..."); List<Energy_Consumption> newEnergyValues = globalCombatLog.Select(log => new Energy_Consumption { Character_FK = log.Assailant_Character_FK, Campaign_FK = skirmish.Campaign_FK, Consume_Energy = globalSkills.FirstOrDefault(x => x.Skill_PK == log.Skill_FK).Energy_Cost }).ToList(); // UNCOMMENT LATER // logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM Push energy costs to server ..."); //controller.UpdateCharacterEnergy(newEnergyValues); #endregion #region USER EXPERIENCE MANAGEMENT // record user experience controller.UpdateUserSkirmishExperience(skirmish.Skirmish_PK); #endregion // update skirmish controller.UpdateSkirmish(skirmish.Skirmish_PK, skirmish.Guild_1_Accolade_Points, skirmish.Guild_2_Accolade_Points); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM End Skirmish Combat Log:"); logger.WriteLine(Json.Serialize(globalCombatLog)); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM End Skirmish State of all characters:"); logger.WriteLine(Json.Serialize(globalCharacters)); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms SYSTEM End Skirmish accolade for all characters:"); logger.WriteLine(Json.Serialize(globalCharacterTrackLog)); stopwatch.Stop(); logger.Close(); } //Show success this.ScheduleHistoryItem.Succeeded = true; } catch (Exception ex) { this.ScheduleHistoryItem.Succeeded = false; this.ScheduleHistoryItem.AddLogNote(" ERROR: " + ex.Message); logger.WriteLine(DateTime.Today + " " + stopwatch.ElapsedMilliseconds + "ms CRITICAL ERROR: " + ex.Message); logger.Close(); this.Errored(ref ex); DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); } }
public string GetAll(int dvid) { if (!DataDV.GetDV().CheckConnected()) { return Errors.e7006; } var query = Query.EQ("dvid", dvid); var dball = sss.Find(query).AsParallel(); var display = new List<BsonDocument>(); Parallel.ForEach(dball, item => { item.Add("id", item["ssid"].ToInt32()); item.Remove("_id"); item.Remove("dvid"); item.Remove("ssid"); display.Add(item); }); return display.ToJson(); }
protected override void OnPreRender([NotNull] EventArgs e) { this.PageContext.PageElements.RegisterJQueryUI(); this.PageContext.PageElements.RegisterJsResourceInclude("blockUIJs", "js/jquery.blockUI.js"); DataTable ctbl = CommonDb.category_list( YafContext.Current.PageModuleID, PageContext.PageBoardID, null); var collection = new List<TreeNode>(); foreach (DataRow row in ctbl.Rows) { // Don't add the category itself. if (this.GetQueryStringAsInt("fa") == (int)row["CategoryID"]) { continue; } collection.Add(new TreeNode { title = row["Name"].ToString(), key = PageContext.PageBoardID + "_" + row["CategoryID"], lazy = true, folder = true, expanded = false, selected = false, extraClasses = string.Empty, tooltip = string.Empty }); } YafContext.Current.PageElements.RegisterJsResourceInclude("fancytree", "js/jquery.fancytree-all.min.js"); YafContext.Current.PageElements.RegisterCssIncludeResource( "css/fancytree/{0}/ui.fancytree.css".FormatWith( YafContext.Current.Get<YafBoardSettings>().FancyTreeTheme)); YafContext.Current.PageElements.RegisterJsResourceInclude("ftreedeljs", "js/fancytree.vzf.nodesadmincategorylist.js"); YafContext.Current.PageElements.RegisterJsBlockStartup( "ftreedelcat", "fancyTreeGetCategoriesListJs('{0}','{1}','{2}','{3}','{4}');" .FormatWith( Config.JQueryAlias, "treedelcat", "You selected category ", "{0}resource.ashx".FormatWith(YafForumInfo.ForumClientFileRoot), collection.ToJson())); base.OnPreRender(e); }
public static JsonObject CreateJwtPayload( IAuthSession session, string issuer, TimeSpan expireIn, string audience=null, IEnumerable<string> roles=null, IEnumerable<string> permissions =null) { var now = DateTime.UtcNow; var jwtPayload = new JsonObject { {"iss", issuer}, {"sub", session.UserAuthId}, {"iat", now.ToUnixTime().ToString()}, {"exp", now.Add(expireIn).ToUnixTime().ToString()}, }; if (audience != null) jwtPayload["aud"] = audience; if (!string.IsNullOrEmpty(session.Email)) jwtPayload["email"] = session.Email; if (!string.IsNullOrEmpty(session.FirstName)) jwtPayload["given_name"] = session.FirstName; if (!string.IsNullOrEmpty(session.LastName)) jwtPayload["family_name"] = session.LastName; if (!string.IsNullOrEmpty(session.DisplayName)) jwtPayload["name"] = session.DisplayName; if (!string.IsNullOrEmpty(session.UserName)) jwtPayload["preferred_username"] = session.UserName; else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@")) jwtPayload["preferred_username"] = session.UserAuthName; var profileUrl = session.GetProfileUrl(); if (profileUrl != null && profileUrl != AuthMetadataProvider.DefaultNoProfileImgUrl) jwtPayload["picture"] = profileUrl; var combinedRoles = new List<string>(session.Roles.Safe()); var combinedPerms = new List<string>(session.Permissions.Safe()); if (roles != null) combinedRoles.AddRange(roles); if (permissions != null) combinedPerms.AddRange(permissions); if (combinedRoles.Count > 0) jwtPayload["roles"] = combinedRoles.ToJson(); if (combinedPerms.Count > 0) jwtPayload["perms"] = combinedPerms.ToJson(); return jwtPayload; }
/// <summary> /// Gets the selection. /// </summary> /// <param name="entityType"></param> /// <param name="controls">The controls.</param> /// <returns></returns> public override string GetSelection( Type entityType, Control[] controls ) { var values = new List<string>(); var groupedControls = GroupControls( entityType, controls ); DropDownList ddlProperty = controls[0] as DropDownList; GetSelectionValuesForProperty( ddlProperty.SelectedValue, groupedControls, values ); return values.ToJson(); }
/// <summary> /// Maps the specified location. /// </summary> /// <param name="location">The location.</param> /// <param name="fences">The fences.</param> /// <param name="groups">The groups.</param> private void Map( MapItem location, List<MapItem> fences, List<MapItem> groups ) { pnlMap.Visible = true; string mapStylingFormat = @" <style> #map_wrapper {{ height: {0}px; }} #map_canvas {{ width: 100%; height: 100%; border-radius: 8px; }} </style>"; lMapStyling.Text = string.Format( mapStylingFormat, GetAttributeValue( "MapHeight" ) ); // add styling to map string styleCode = "null"; var markerColors = new List<string>(); DefinedValueCache dvcMapStyle = DefinedValueCache.Read( GetAttributeValue( "MapStyle" ).AsInteger() ); if ( dvcMapStyle != null ) { styleCode = dvcMapStyle.GetAttributeValue( "DynamicMapStyle" ); markerColors = dvcMapStyle.GetAttributeValue( "Colors" ) .Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ) .ToList(); markerColors.ForEach( c => c = c.Replace( "#", string.Empty ) ); } if ( !markerColors.Any() ) { markerColors.Add( "FE7569" ); } string locationColor = markerColors[0].Replace( "#", string.Empty ); var polygonColorList = GetAttributeValue( "PolygonColors" ).Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ).ToList(); string polygonColors = "\"" + polygonColorList.AsDelimited( "\", \"" ) + "\""; string groupColor = ( markerColors.Count > 1 ? markerColors[1] : markerColors[0] ).Replace( "#", string.Empty ); string latitude = "39.8282"; string longitude = "-98.5795"; string zoom = "4"; var orgLocation = GlobalAttributesCache.Read().OrganizationLocation; if ( orgLocation != null && orgLocation.GeoPoint != null ) { latitude = orgLocation.GeoPoint.Latitude.ToString(); longitude = orgLocation.GeoPoint.Longitude.ToString(); zoom = "12"; } // write script to page string mapScriptFormat = @" var locationData = {0}; var fenceData = {1}; var groupData = {2}; var allMarkers = []; var map; var bounds = new google.maps.LatLngBounds(); var infoWindow = new google.maps.InfoWindow(); var mapStyle = {3}; var pinShadow = new google.maps.MarkerImage('//chart.googleapis.com/chart?chst=d_map_pin_shadow', new google.maps.Size(40, 37), new google.maps.Point(0, 0), new google.maps.Point(12, 35)); var polygonColorIndex = 0; var polygonColors = [{5}]; var min = .999999; var max = 1.000001; initializeMap(); function initializeMap() {{ // Set default map options var mapOptions = {{ mapTypeId: 'roadmap' ,styles: mapStyle ,center: new google.maps.LatLng({7}, {8}) ,zoom: {9} }}; // Display a map on the page map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); map.setTilt(45); if ( locationData != null ) {{ var items = addMapItem(0, locationData, '{4}'); for (var j = 0; j < items.length; j++) {{ items[j].setMap(map); }} }} if ( fenceData != null ) {{ for (var i = 0; i < fenceData.length; i++) {{ var items = addMapItem(i, fenceData[i] ); for (var j = 0; j < items.length; j++) {{ items[j].setMap(map); }} }} }} if ( groupData != null ) {{ for (var i = 0; i < groupData.length; i++) {{ var items = addMapItem(i, groupData[i], '{6}'); for (var j = 0; j < items.length; j++) {{ items[j].setMap(map); }} }} }} // adjust any markers that may overlap adjustOverlappedMarkers(); if (!bounds.isEmpty()) {{ map.fitBounds(bounds); }} }} function addMapItem( i, mapItem, color ) {{ var items = []; if (mapItem.Point) {{ var position = new google.maps.LatLng(mapItem.Point.Latitude, mapItem.Point.Longitude); bounds.extend(position); if (!color) {{ color = 'FE7569' }} var pinImage = new google.maps.MarkerImage('//chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|' + color, new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34)); marker = new google.maps.Marker({{ position: position, map: map, title: htmlDecode(mapItem.Name), icon: pinImage, shadow: pinShadow }}); items.push(marker); allMarkers.push(marker); if ( mapItem.InfoWindow != null ) {{ google.maps.event.addListener(marker, 'click', (function (marker, i) {{ return function () {{ infoWindow.setContent( $('<div/>').html(mapItem.InfoWindow).text() ); infoWindow.open(map, marker); }} }})(marker, i)); }} if ( mapItem.EntityId && mapItem.EntityId > 0 ) {{ google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {{ return function () {{ $(""tr[datakey='"" + mapItem.EntityId + ""']"").addClass('row-highlight'); }} }})(marker, i)); google.maps.event.addListener(marker, 'mouseout', (function (marker, i) {{ return function () {{ $(""tr[datakey='"" + mapItem.EntityId + ""']"").removeClass('row-highlight'); }} }})(marker, i)); }} }} if (typeof mapItem.PolygonPoints !== 'undefined' && mapItem.PolygonPoints.length > 0) {{ var polygon; var polygonPoints = []; $.each(mapItem.PolygonPoints, function(j, point) {{ var position = new google.maps.LatLng(point.Latitude, point.Longitude); bounds.extend(position); polygonPoints.push(position); }}); var polygonColor = getNextPolygonColor(); polygon = new google.maps.Polygon({{ paths: polygonPoints, map: map, strokeColor: polygonColor, fillColor: polygonColor }}); items.push(polygon); // Get Center var polyBounds = new google.maps.LatLngBounds(); for ( j = 0; j < polygonPoints.length; j++) {{ polyBounds.extend(polygonPoints[j]); }} if ( mapItem.InfoWindow != null ) {{ google.maps.event.addListener(polygon, 'click', (function (polygon, i) {{ return function () {{ infoWindow.setContent( mapItem.InfoWindow ); infoWindow.setPosition(polyBounds.getCenter()); infoWindow.open(map); }} }})(polygon, i)); }} }} return items; }} function setAllMap(markers, map) {{ for (var i = 0; i < markers.length; i++) {{ markers[i].setMap(map); }} }} function htmlDecode(input) {{ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? """" : e.childNodes[0].nodeValue; }} function getNextPolygonColor() {{ var color = 'FE7569'; if ( polygonColors.length > polygonColorIndex ) {{ color = polygonColors[polygonColorIndex]; polygonColorIndex++; }} else {{ color = polygonColors[0]; polygonColorIndex = 1; }} return color; }} function adjustOverlappedMarkers() {{ if (allMarkers.length > 1) {{ for(i=0; i < allMarkers.length-1; i++) {{ var marker1 = allMarkers[i]; var pos1 = marker1.getPosition(); for(j=i+1; j < allMarkers.length; j++) {{ var marker2 = allMarkers[j]; var pos2 = marker2.getPosition(); if (pos1.equals(pos2)) {{ var newLat = pos1.lat() * (Math.random() * (max - min) + min); var newLng = pos1.lng() * (Math.random() * (max - min) + min); marker1.setPosition( new google.maps.LatLng(newLat,newLng) ); }} }} }} }} }} "; var locationJson = location != null ? string.Format( "JSON.parse('{0}')", location.ToJson().Replace( Environment.NewLine, "" ).EscapeQuotes().Replace( "\x0A", "" ) ) : "null"; var fencesJson = fences != null && fences.Any() ? string.Format( "JSON.parse('{0}')", fences.ToJson().Replace( Environment.NewLine, "" ).EscapeQuotes().Replace( "\x0A", "" ) ) : "null"; var groupsJson = groups != null && groups.Any() ? string.Format( "JSON.parse('{0}')", groups.ToJson().Replace( Environment.NewLine, "" ).EscapeQuotes().Replace( "\x0A", "" ) ) : "null"; string mapScript = string.Format( mapScriptFormat, locationJson, // 0 fencesJson, // 1 groupsJson, // 2 styleCode, // 3 locationColor, // 4 polygonColors, // 5 groupColor, // 6 latitude, // 7 longitude, // 8 zoom ); // 9 ScriptManager.RegisterStartupScript( pnlMap, pnlMap.GetType(), "group-finder-map-script", mapScript, true ); }
public void map_spotify_releases_should_cope_with_duplicate_spotify_ids() { var data = new List <SpotifyImportListItemInfo> { new SpotifyImportListItemInfo { Album = "25", AlbumSpotifyId = "7uwTHXmFa1Ebi5flqBosig", Artist = "Adele" }, new SpotifyImportListItemInfo { Album = "25", AlbumSpotifyId = "7uwTHXmFa1Ebi5flqBosig", Artist = "Adele" } }; var map = new List <SpotifyMap> { new SpotifyMap { SpotifyId = "7uwTHXmFa1Ebi5flqBosig", MusicbrainzId = "5537624c-3d2f-4f5c-8099-df916082c85c" } }; Mocker.GetMock <IHttpClient>() .Setup(x => x.Post <List <SpotifyMap> >(It.IsAny <HttpRequest>())) .Returns <HttpRequest>(r => new HttpResponse <List <SpotifyMap> >(new HttpResponse(r, new HttpHeader(), map.ToJson()))); var result = Subject.MapSpotifyReleases(data); result.Should().HaveCount(2); result[0].AlbumMusicBrainzId.Should().Be("5537624c-3d2f-4f5c-8099-df916082c85c"); result[1].AlbumMusicBrainzId.Should().Be("5537624c-3d2f-4f5c-8099-df916082c85c"); }
public ActionResult GetAutoCompleteData() { var flag = false; var msg = string.Empty; var systemCodes = new List <string>(); var sources = new List <string>(); var classNames = new List <string>(); var methodNames = new List <string>(); var methodCNames = new List <string>(); var rs = _perfLogService.GetAutoCompleteData(); if (rs.ReturnCode == ReturnCodeType.Success) { systemCodes = rs.Content.Item1; sources = rs.Content.Item2; classNames = rs.Content.Item3; methodNames = rs.Content.Item4; methodCNames = rs.Content.Item5; flag = true; } return(Json(new { success = flag, msg = msg, systemCodes = systemCodes.ToJson(), sources = sources.ToJson(), classNames = classNames.ToJson(), methodNames = methodNames.ToJson(), methodCNames = methodCNames.ToJson() }, JsonRequestBehavior.AllowGet)); }
private void WriteJsonIframeSafe(HttpContext context, List<FilesStatus> statuses) { context.Response.AddHeader("Vary", "Accept"); try { if (context.Request["HTTP_ACCEPT"].Contains("application/json")) context.Response.ContentType = "application/json"; else context.Response.ContentType = "text/plain"; } catch { context.Response.ContentType = "text/plain"; } var json = statuses.ToJson(); context.Response.Write(json); }
/*public String GetRowsReportUser(List<string> profile = null,Dictionary<string,string> fields=null,Int64 start=0,Int64 end=0,List<string> locations=null) * { * * * var orderfield = "name"; * BsonArray locsbson = new BsonArray(); * try * { * if (locations != null) * { * foreach (string loc in locations) * { * locsbson.Add(loc); * } * } * } * catch { } * * * * try * { * * string[] arrayprofile = profile.ToArray(); * List<string> cols = new List<string>(); * if (fields == null || fields.Count()==0) * { * cols.Add("user"); * cols.Add("name"); * cols.Add("lastname"); * cols.Add("profileId"); * cols.Add("email"); * //cols.Add("CreatedTimeStamp"); * } * else * { * foreach (var x in fields) * { * cols.Add(x.Key); * } * if (!fields.Keys.Contains("profileId")) * { * cols.Add("profileId"); * } * // cols.Add("CreatedTimeStamp"); * } * BsonArray bsonarray = new BsonArray(); * * for (int i = 0; i < arrayprofile.Length; i++) * { * bsonarray.Add(arrayprofile[i]); * } * * string[] arrayfields = cols.ToArray(); * List<BsonDocument> documents = new List<BsonDocument>(); * if (profile != null && profile.Count>0) * { * var query = Query.And(Query.In("profileId", bsonarray), Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end)); * * if (locsbson.Count() > 0) * { * query = Query.And(Query.In("profileId", bsonarray), Query.In("userLocations.id", locsbson), Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end)); * * } * * var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); * * * foreach (BsonDocument document in cursor) * { * document.Set("_id", document.GetElement("_id").Value.ToString()); * try * { * document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); * } * catch (Exception ex) * { * * } * documents.Add(document); * } * } * else * { * var query = Query.And( Query.GTE("CreatedTimeStamp", start), Query.LTE("CreatedTimeStamp", end)); * * var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); * foreach (BsonDocument document in cursor) * { * document.Set("_id", document.GetElement("_id").Value.ToString()); * try { * document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); * } * catch (Exception ex) * { * * } * documents.Add(document); * } * * } * return documents.ToJson(); * } * catch (Exception e) * { * // System.Windows.Forms.MessageBox.Show(e.ToString()); * return null; * } * }*/ public String GetRowsReportUser(List <string> profile = null, Dictionary <string, string> fields = null, Int64 start = 0, Int64 end = 0, List <string> locations = null) { var orderfield = "name"; BsonArray locsbson = new BsonArray(); try { if (locations != null) { foreach (string loc in locations) { locsbson.Add(loc); } } } catch { } try { string[] arrayprofile = profile.ToArray(); List <string> cols = new List <string>(); if (fields == null || fields.Count() == 0) { cols.Add("user"); cols.Add("name"); cols.Add("lastname"); cols.Add("profileId"); cols.Add("email"); // cols.Add("CreatedTimeStamp"); } else { foreach (var x in fields) { cols.Add(x.Key); } if (!fields.Keys.Contains("profileId")) { cols.Add("profileId"); } //cols.Add("CreatedTimeStamp"); } BsonArray bsonarray = new BsonArray(); for (int i = 0; i < arrayprofile.Length; i++) { bsonarray.Add(arrayprofile[i]); } string[] arrayfields = cols.ToArray(); List <BsonDocument> documents = new List <BsonDocument>(); if (profile != null && profile.Count > 0) { var query = Query.And(Query.In("profileId", bsonarray)); if (locsbson.Count() > 0) { query = Query.And(Query.In("profileId", bsonarray), Query.Or(Query.In("userLocations.id", locsbson), Query.Size("userLocations", 0), Query.Not(Query.Size("userLocations", 0)))); } var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); foreach (BsonDocument document in cursor) { document.Set("_id", document.GetElement("_id").Value.ToString()); try { document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); } catch (Exception ex) { } documents.Add(document); } } else { var query = Query.And(Query.Exists("name")); var cursor = collection.FindAs(typeof(BsonDocument), query).SetFields(arrayfields).SetSortOrder(SortBy.Ascending(orderfield)); foreach (BsonDocument document in cursor) { document.Set("_id", document.GetElement("_id").Value.ToString()); try { document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); } catch (Exception ex) { } documents.Add(document); } } return(documents.ToJson()); } catch (Exception e) { // System.Windows.Forms.MessageBox.Show(e.ToString()); return(null); } }
/// <summary> /// Writes the <see cref="T:System.Web.UI.WebControls.CompositeControl" /> content to the specified <see cref="T:System.Web.UI.HtmlTextWriter" /> object, for display on the client. /// </summary> /// <param name="writer">An <see cref="T:System.Web.UI.HtmlTextWriter" /> that represents the output stream to render HTML content on the client.</param> protected override void Render( HtmlTextWriter writer ) { _tbName.Attributes["onblur"] = string.Format( "populateAttributeKey('{0}','{1}')", _tbName.ClientID, _tbKey.ClientID ); writer.RenderBeginTag( HtmlTextWriterTag.Fieldset ); writer.RenderBeginTag( HtmlTextWriterTag.Legend ); _lAttributeActionTitle.RenderControl( writer ); writer.RenderEndTag(); var existingKeyNames = new List<string>(); ReservedKeyNames.ForEach( n => existingKeyNames.Add(n)); ObjectPropertyNames.ForEach( n => existingKeyNames.Add(n)); _hfExistingKeyNames.Value = existingKeyNames.ToJson(); _hfExistingKeyNames.RenderControl( writer ); _validationSummary.RenderControl( writer ); // row 1 writer.AddAttribute( HtmlTextWriterAttribute.Class, "row" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); writer.AddAttribute( HtmlTextWriterAttribute.Class, "col-md-6" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); _tbName.RenderControl( writer ); writer.RenderEndTag(); writer.AddAttribute( HtmlTextWriterAttribute.Class, "col-md-6" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); writer.RenderEndTag(); writer.RenderEndTag(); // row // row 2 writer.AddAttribute( HtmlTextWriterAttribute.Class, "row" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); writer.AddAttribute( HtmlTextWriterAttribute.Class, "col-md-12" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); _tbDescription.RenderControl( writer ); writer.RenderEndTag(); writer.RenderEndTag(); // row // row 3 writer.AddAttribute( HtmlTextWriterAttribute.Class, "row" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); // row 3 col 1 writer.AddAttribute( HtmlTextWriterAttribute.Class, "col-md-6" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); _cpCategories.RenderControl( writer ); _tbKey.RenderControl( writer ); _cvKey.RenderControl( writer ); _tbIconCssClass.RenderControl( writer ); writer.AddAttribute( HtmlTextWriterAttribute.Class, "row" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); writer.AddAttribute( HtmlTextWriterAttribute.Class, "col-sm-6" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); _cbRequired.RenderControl( writer ); writer.RenderEndTag(); writer.AddAttribute( HtmlTextWriterAttribute.Class, "col-sm-6" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); _cbShowInGrid.RenderControl( writer ); _cbAllowSearch.RenderControl( writer ); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); // row 3 col 2 writer.AddAttribute( HtmlTextWriterAttribute.Class, "col-md-6" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); _ddlFieldType.RenderControl( writer ); _phQualifiers.RenderControl( writer ); _phDefaultValue.RenderControl( writer ); writer.RenderEndTag(); writer.RenderEndTag(); // </fieldset> writer.RenderEndTag(); if ( ShowActions ) { writer.AddAttribute( HtmlTextWriterAttribute.Class, "actions" ); writer.RenderBeginTag( HtmlTextWriterTag.Div ); _btnSave.RenderControl( writer ); writer.Write( Environment.NewLine ); _btnCancel.RenderControl( writer ); writer.RenderEndTag(); } RegisterClientScript(); }
public static JsonObject CreateJwtPayload( IAuthSession session, string issuer, TimeSpan expireIn, string audience = null, IEnumerable <string> roles = null, IEnumerable <string> permissions = null) { var now = DateTime.UtcNow; var jwtPayload = new JsonObject { { "iss", issuer }, { "sub", session.UserAuthId }, { "iat", now.ToUnixTime().ToString() }, { "exp", now.Add(expireIn).ToUnixTime().ToString() }, }; if (audience != null) { jwtPayload["aud"] = audience; } if (!string.IsNullOrEmpty(session.Email)) { jwtPayload["email"] = session.Email; } if (!string.IsNullOrEmpty(session.FirstName)) { jwtPayload["given_name"] = session.FirstName; } if (!string.IsNullOrEmpty(session.LastName)) { jwtPayload["family_name"] = session.LastName; } if (!string.IsNullOrEmpty(session.DisplayName)) { jwtPayload["name"] = session.DisplayName; } if (!string.IsNullOrEmpty(session.UserName)) { jwtPayload["preferred_username"] = session.UserName; } else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@")) { jwtPayload["preferred_username"] = session.UserAuthName; } var profileUrl = session.GetProfileUrl(); if (profileUrl != null && profileUrl != AuthMetadataProvider.DefaultNoProfileImgUrl) { jwtPayload["picture"] = profileUrl; } var combinedRoles = new List <string>(session.Roles.Safe()); var combinedPerms = new List <string>(session.Permissions.Safe()); roles.Each(x => combinedRoles.AddIfNotExists(x)); permissions.Each(x => combinedPerms.AddIfNotExists(x)); if (combinedRoles.Count > 0) { jwtPayload["roles"] = combinedRoles.ToJson(); } if (combinedPerms.Count > 0) { jwtPayload["perms"] = combinedPerms.ToJson(); } return(jwtPayload); }
public void RunQuery() { ValidateQuery(); var leanKitAuth = new LeanKitBasicAuth { Hostname = _args.Host, Username = _args.User, Password = _args.Password }; // For internal development testing if (_args.Host.Equals("kanban-cibuild", StringComparison.InvariantCultureIgnoreCase)) leanKitAuth.UrlTemplateOverride = "http://{0}.localkanban.com"; WriteInfo("Connecting to LeanKit account..."); var api = new LeanKitClientFactory().Create(leanKitAuth); if (_args.Boards) { WriteInfo("Getting all boards..."); var boards = api.GetBoards(); var boardList = boards.Select(Mapper.Map<BoardLiteView>); var output = _args.Csv ? boardList.ToCsv() : _args.Json ? boardList.ToJson() : boardList.Dump(); Console.WriteLine(output); } else if (_args.Board > 0) { WriteInfo(string.Format("Getting board [{0}]...", _args.Board)); var board = api.GetBoard(_args.Board); if (_args.Lanes || _args.Lane > 0 || _args.Cards) { // Get lanes var boardLanes = new List<Lane>(); if (_args.Lane > 0) { WriteInfo(string.Format("Getting lane [{0}]...", _args.Lane)); boardLanes.AddRange(board.AllLanes().Where(lane => lane.Id == _args.Lane)); } else { if (_args.IncludeBacklog) boardLanes.AddRange(board.Backlog); boardLanes.AddRange(board.Lanes); if (_args.IncludeArchive) boardLanes.AddRange(board.Archive); } if (_args.Cards) { WriteInfo("Getting cards..."); var cards = new List<MappedCardView>(); foreach (var lane in boardLanes) { cards.AddRange(lane.Cards.Select(Mapper.Map<MappedCardView>)); } // Archived cards is a separate API call if (_args.IncludeArchive) { var archivedCards = api.GetArchiveCards(_args.Board); cards.AddRange(archivedCards.Select(Mapper.Map<MappedCardView>)); } var output = _args.Csv ? cards.ToCsv() : _args.Json ? cards.ToJson() : cards.Dump(); Console.WriteLine(output); } else { var lanes = boardLanes.Select(Mapper.Map<LaneView>); var output = _args.Csv ? lanes.ToCsv() : _args.Json ? lanes.ToJson() : lanes.Dump(); Console.WriteLine(output); } } else { var boardView = Mapper.Map<BoardView>(board); var output = _args.Csv ? boardView.ToCsv() : _args.Json ? boardView.ToJson() : boardView.Dump(); Console.WriteLine(output); } } }
/// <summary> /// 根据订单和用户生成支付记录 /// 生成的支付记录没有,支付方式,支付方式有前端返回来 /// </summary> /// <param name="singlePayInput">The order.</param> public Tuple <ServiceResult, Pay> AddSinglePay(SinglePayInput singlePayInput) { var webSite = Resolve <IAutoConfigService>().GetValue <WebSiteConfig>(); var pay = new Pay { EntityId = singlePayInput.Orders.Select(r => r.Id).ToJson(), Status = PayStatus.WaiPay, Type = singlePayInput.CheckoutType, Amount = singlePayInput.Orders.Sum(r => r.PaymentAmount), UserId = singlePayInput.User.Id }; // 是否为管理员代付 if (singlePayInput.IsAdminPay) { pay.PayType = PayType.AdminPay; } if (singlePayInput.Type == CheckoutType.Customer) { pay.Type = singlePayInput.Type; } var payExtension = new PayExtension { TradeNo = singlePayInput.Orders.FirstOrDefault() .Serial, // 使用第一个订单作为交易号 // Subject = order.OrderExtension?.Product?.Name, // 支付标题为商品名称 TotalAmount = singlePayInput.Orders.Sum(r => r.PaymentAmount), Body = $"您正在{webSite.WebSiteName}商城上购买商品,请认真核对订单信息", // ProductCode = order.OrderExtension?.Product?.Bn, UserName = singlePayInput.User.GetUserName(), IsFromOrder = singlePayInput.IsFromOrder }; if (singlePayInput.IsGroupBuy) { //是否为拼团购买 payExtension.IsGroupBuy = true; payExtension.BuyerCount = singlePayInput.BuyerCount; } if (singlePayInput.ExcecuteSqlList != null) { payExtension.ExcecuteSqlList = singlePayInput.ExcecuteSqlList; } if (singlePayInput.AfterSuccess != null) { payExtension.AfterSuccess = singlePayInput.AfterSuccess; } if (singlePayInput.OrderUser != null) { payExtension.OrderUser = singlePayInput.OrderUser; } payExtension.RedirectUrl = singlePayInput.RedirectUrl; if (Convert.ToInt16(singlePayInput.TriggerType) > 0) { payExtension.TriggerType = singlePayInput.TriggerType; } if (!singlePayInput.EntityId.IsNullOrEmpty()) { pay.EntityId = singlePayInput.EntityId; } IList <KeyValuePair <Guid, decimal> > acmountPay = new List <KeyValuePair <Guid, decimal> >(); if (singlePayInput.ReduceMoneys != null && singlePayInput.ReduceMoneys.Count > 0) { payExtension.Note = "扣除"; singlePayInput.ReduceMoneys.Foreach(r => { payExtension.Note += " " + r.Name + r.MaxPayPrice; acmountPay.Add(new KeyValuePair <Guid, decimal>(r.MoneyId, r.MaxPayPrice)); }); } pay.AccountPay = acmountPay.ToJson(); if (!singlePayInput.RedirectUrl.IsNullOrEmpty()) { payExtension.RedirectUrl = singlePayInput.RedirectUrl; } pay.Extensions = payExtension.ToJson(); if (Resolve <IPayService>().Add(pay)) { return(Tuple.Create(ServiceResult.Success, pay)); } return(Tuple.Create(ServiceResult.Failure("支付订单创建失败"), new Pay())); }
private ProjectRole AddActorToRole(Uri projectUri, int roleId, string actorType, string actorName) { var uri = projectUri.Append(ProjectRoleUriPostfix).Append(roleId.ToString()); var actors = new List<string> { actorName }; var request = new JsonObject { { actorType, actors.ToJson() } }; return client.Post<ProjectRole>(uri.ToString(), request); }
public static void ImputEsbDepartmentTree(SqlSugarClient Edb, SqlSugarClient Ddb) { List <V_DingTalk_DepartmentTree> DepTreeList = Edb.Ado.SqlQuery <V_DingTalk_DepartmentTree>("exec SP_DingTalk_DepartmentTree"); List <DepartmentTrees> list = JsonHelper.JonsToList <DepartmentTrees>(DepTreeList.ToJson()).OrderBy(e => e.level).ToList(); Ddb.CodeFirst.InitTables(typeof(DepartmentTrees)); Ddb.DbMaintenance.TruncateTable("DepartmentTrees"); int count = Ddb.Insertable <DepartmentTrees>(list).ExecuteCommand(); Console.Write("\r\n执行完成\r\n"); }