public bool UpdateUserInfo(OutUserModel outUser) { bool res = false; try { string sql = @"UPDATE `user` SET `realName`=@RealName,`idCard`=@IdCard,`userAvatar`=@UserAvatar,`email`=@Email,`mobileNum`=@MobileNum,`userToken`=@UserToken,`tokenCreateTime`=NOW(),`extra`=@Extra,`updateTime`=NOW();"; MySqlParameter[] param = { new MySqlParameter("@RealName", outUser.RealName), new MySqlParameter("@IdCard", outUser.IdCard), new MySqlParameter("@UserAvatar", outUser.UserAvatar), new MySqlParameter("@Email", outUser.Email), new MySqlParameter("@MobileNum", outUser.MobileNum), new MySqlParameter("@UserToken", GUIDHelper.GenerateGUID()), new MySqlParameter("@Extra", outUser.Extra), }; res = MySqlHelper.ExecuteNonQuery(ConfigHelper.ConnStr, sql, param) > 0; } catch (Exception ex) { LogHelper.Error(ex); } return(res); }
private void NewGUID(ReferenceObject refobj) { Undo.RecordObject(refobj, "RefObj"); refobj.Data.GUID = GUIDHelper.NewGUID(); PrefabUtility.RecordPrefabInstancePropertyModifications(refobj); RefreshData(); }
public ActionResult Login(UserModel user) { var users = _user.GetUsers(); var userModel = users.FirstOrDefault(x => x.EUserName == user.EUserName && x.EPassword == user.EPassword); if (userModel == null) { return(Json(null, JsonRequestBehavior.DenyGet)); } else { userModel.ERefreshTime = DateTime.Now; var token = GUIDHelper.GetGuid(); userModel.EToken = token; userModel.EIp = HttpContext.Request.UserHostAddress; if (string.IsNullOrWhiteSpace(user.EId)) { userModel.EId = GUIDHelper.GetGuid(); _user.SaveUsers(new List <UserModel>() { userModel }); } { _user.UpdateUsers(new List <UserModel>() { userModel }); } return(Json(token, JsonRequestBehavior.DenyGet)); } }
public void Prepare(Graph routeGraph) { relatedRouteSegmentIds = routeGraph.SortLinkPath(relatedRouteSegmentIds); Id = GUIDHelper.StringToGUID("conduit" + relatedRouteSegmentIds[0].ToString() + BuildCode); WalkOfInterestId = GUIDHelper.StringToGUID("woi" + relatedRouteSegmentIds[0].ToString() + BuildCode); }
public async Task <List <User> > GetDataByids(string ids, List <User> list = null) { // 当第一个线程执行的时候,会对locker对象 "加锁", // 当其他线程执行的时候,会等待 locker 执行完解锁 lock (locker) { } list = list ?? await base.Query(); if (!string.IsNullOrEmpty(ids)) { var idList = ids.Split(','); if (GUIDHelper.IsGuidByReg(idList[0])) { return(list.Where(s => idList.Contains(s.Guid)).ToList()); } else { return(list.Where(s => idList.ToInt32List().Contains(s.Id)).ToList()); } } return(list); }
/// <summary> /// 上传图片 /// </summary> /// <param name="file"></param> /// <param name="path"></param> /// <param name="imgUrl"></param> /// <param name="ip"></param> /// <param name="userId"></param> /// <returns></returns> public string UploadImg(IFormFile file, string path, string imgUrl, string ip, int userId) { var now = DateTime.Now; imgUrl = imgUrl + now.Year + "/" + now.Month + "/" + now.Day + "/"; //if (!path.EndsWith("/")) // path = path + "/"; //if (imgUrl.StartsWith("/")) // imgUrl = imgUrl.TrimStart('/'); path = Path.Combine(path, imgUrl); //文件名称 string fileName = GUIDHelper.GetStringID() + ".png"; imgUrl = imgUrl + fileName; Task.Run(() => { FileHelper.UploadFileWithFormFile(file, path, path + fileName); }); var uploadModel = new Sys_UploadFile(); uploadModel.CrtDate = now; uploadModel.FileName = fileName; uploadModel.FilePath = imgUrl; uploadModel.FileSize = 0; uploadModel.FileType = "image/jpeg"; uploadModel.Ip = ip; uploadModel.TypeId = (int)UploadTypeEnum.image; uploadModel.UserId = userId; uploadModel.Status = (int)UploadStatusEnum.未使用; uploadModel.Id = _repository.Insert(uploadModel, true); return(JSONHelper.Seriallize(new { url = imgUrl, uploadId = uploadModel.Id })); }
public static void SetAndGet() { var list = new List <UserDto>(); for (int i = 0; i < 1000; i++) { list.Add(new UserDto { Id = GUIDHelper.GetUniqueId(), Status = i % 2 == 0 ? 1 : 5 }); } Stopwatch sw = new Stopwatch(); sw.Start(); var rList = new ConcurrentQueue <UserDto>(list); Parallel.ForEach(rList, model => { Console.WriteLine(JSONHelper.Seriallize(model)); }); sw.Stop(); Console.WriteLine("Parallel.ForEach:" + sw.ElapsedMilliseconds); //sw.Restart(); //// var rList = new ConcurrentQueue<UserDto>(list); //foreach (var model in list) //{ // Console.WriteLine(JSONHelper.Seriallize(model)); //} //sw.Stop(); //Console.WriteLine("foreach:" + sw.ElapsedMilliseconds); }
public static GetRandomNumberOfGuidsCommandResult GetCount(int count) { using (GetRandomNumberOfGuidsCommandResult commandResult = new GetRandomNumberOfGuidsCommandResult()) { commandResult.Guids = GUIDHelper.GetNumberOfGuid(count); return(commandResult); } }
private void loadContacts() { string _prefix = "NBS-"; GUIDHelper helper = GUIDHelper.getInstance(); ObservableCollection <ContactModel> initList = new ObservableCollection <ContactModel>(); for (int i = 0; i < 20; i = i + 1) { ContactModel m = new ContactModel(); //m.HashID = "00000" + i; m.HashID = helper.GetGUID().Substring(10); m.Message = _prefix + "" + i; m.AvatarHashID = "NBS-xxx-" + i; if (i % 2 == 0) { m.AvatarName = new BitmapImage(new Uri("pack://application:,,,/avatars/nbs100.png")); } else { m.AvatarName = new BitmapImage(new Uri("pack://application:,,,/avatars/fuchen200.png")); } initList.Add(m); } if (initList != null) { ResultList = initList; } }
public void AddPNMObject(PhysicalNetworkModel.RatioTapChanger tap) { var controlMrid = GUIDHelper.CreateDerivedGuid(Guid.Parse(tap.mRID), 55); string xml = "<cim:RatioTapChanger rdf:ID = '_" + tap.mRID + "'>\r\n"; xml += " <cim:RatioTapChanger.TransformerEnd rdf:resource='#_" + tap.TransformerEnd.@ref + "'/>\r\n"; //xml += " <cim:TapChanger.TapChangerControl rdf:resource='#_" + controlMrid.ToString() + "'/>\r\n"; xml += " <cim:IdentifiedObject.name>TAP</cim:IdentifiedObject.name>\r\n"; if (tap.neutralU != null) { xml += " <cim:TapChanger.neutralU>" + DoubleToString(tap.neutralU.Value / 1000) + "</cim:TapChanger.neutralU>\r\n"; } if (tap.neutralStep != null) { xml += " <cim:TapChanger.neutralStep>" + tap.neutralStep + "</cim:TapChanger.neutralStep>\r\n"; } if (tap.normalStep != null && tap.normalStep != "") { xml += " <cim:TapChanger.normalStep>" + tap.normalStep + "</cim:TapChanger.normalStep>\r\n"; } xml += " <cim:TapChanger.lowStep>" + tap.lowStep + "</cim:TapChanger.lowStep>\r\n"; xml += " <cim:TapChanger.highStep>" + tap.highStep + "</cim:TapChanger.highStep>\r\n"; xml += " <cim:TapChanger.ltcFlag>" + (tap.ltcFlag ? "true" : "false") + "</cim:TapChanger.ltcFlag>\r\n"; xml += " <cim:RatioTapChanger.tculControlMode rdf:resource='http://iec.ch/TC57/2013/CIM-schema-cim16#TransformerControlMode.volt'/>\r\n"; if (tap.stepVoltageIncrement != null) { xml += " <cim:RatioTapChanger.stepVoltageIncrement>" + DoubleToString(tap.stepVoltageIncrement.Value) + "</cim:RatioTapChanger.stepVoltageIncrement>\r\n"; } xml += "</cim:RatioTapChanger>\r\n\r\n"; _writer.Write(xml); /* * // Create regulating control if automatic * if (tap.ltcFlag) * { * * var ptEnd = _cimContext.GetObject<PhysicalNetworkModel.PowerTransformerEnd>(tap.TransformerEnd.@ref); * * xml = "<cim:TapChangerControl rdf:ID = '_" + controlMrid.ToString() + "'>\r\n"; * xml += " <cim:IdentifiedObject.name>Tab Controler</cim:IdentifiedObject.name>\r\n"; * xml += " <cim:RegulatingControl.mode rdf:resource='http://iec.ch/TC57/2013/CIM-schema-cim16#RegulatingControlModeKind.voltage' />\r\n"; * xml += " <cim:RegulatingControl.Terminal rdf:resource='#_" + ptEnd.Terminal.@ref + "'/>\r\n"; * * xml += "</cim:TapChangerControl>\r\n\r\n"; * } */ }
public static void RemoveGUIDFromAllChildren() { NodeGraph[] nodeGraphs = FindObjectsOfType(typeof(NodeGraph)) as NodeGraph[]; foreach (var ng in nodeGraphs) { foreach (var node in ng.GetComponentsInChildren <Transform>()) { node.name = GUIDHelper.RemoveGUIDFromName(node.name); } } }
public void StartPlay() { SocketRequest req = new SocketRequest(); req.p1 = GUIDHelper.generate(); req.p2 = "join"; req.p3 = DataHelper.GetInstance().LoadToken(dbManager); req.p4 = SystemInfo.deviceUniqueIdentifier; req.p5 = "10"; SendBytes(ProtoHelper.Proto2Bytes(req)); }
private void OnWebSocketOpen(WebSocket webSocket) { Debug.Log("WebSocket open! now login."); SocketRequest req = new SocketRequest(); req.p1 = GUIDHelper.generate(); req.p2 = "login"; req.p3 = DataHelper.GetInstance().LoadToken(dbManager); req.p4 = SystemInfo.deviceUniqueIdentifier; webSocket.Send(DESHelper.EncodeBytes(GZipHelper.compress(ProtoHelper.Proto2Bytes(req)), AppContext.GetInstance().getDesKey())); }
private void DoTake(bool take) { SocketRequest sr = new SocketRequest(); sr.p1 = GUIDHelper.generate(); sr.p2 = "takeLandlord"; sr.p3 = LocalToken(); sr.p4 = SystemInfo.deviceUniqueIdentifier; sr.p5 = AppContext.GetInstance().Watch.gameId.ToString(); sr.p6 = AppContext.GetInstance().Watch.seatId.ToString(); sr.p7 = take.ToString(); SendBytes(ProtoHelper.Proto2Bytes(sr)); }
public void TestGUID_Identity_10million() { HashSet <long> idset = new HashSet <long>(); for (int i = 0; i < 1000 * 10000; i++) { long id = GUIDHelper.Identity(); if (idset.Contains(id)) { Assert.Fail("重复了 index:" + i); } idset.Add(id); } }
public async Task <List <Dept> > GetDataByids(string ids, List <Dept> list = null) { list = list ?? await base.Query(); if (!string.IsNullOrEmpty(ids)) { var idList = ids.Split(','); if (GUIDHelper.IsGuidByReg(idList[0])) { return(list.Where(s => idList.Contains(s.Guid)).ToList()); } else { return(list.Where(s => idList.ToInt32List().Contains(s.Id)).ToList()); } } return(list); }
public void AddCurrentLimit(Guid terminalMrid, string name, double currentLimitValue) { // Limit set string xml = "<cim:OperationalLimitSet rdf:ID='_" + GUIDHelper.CreateDerivedGuid(terminalMrid, 750, true).ToString() + "'>\r\n"; xml += " <cim:IdentifiedObject.name>" + name + "_limitset</cim:IdentifiedObject.name>\r\n"; xml += " <cim:OperationalLimitSet.Terminal rdf:resource = '#_" + terminalMrid.ToString() + "'/>\r\n"; xml += "</cim:OperationalLimitSet>\r\n\r\n"; // Current xml += "<cim:CurrentLimit rdf:ID='_" + GUIDHelper.CreateDerivedGuid(terminalMrid, 760, true).ToString() + "'>\r\n"; xml += " <cim:OperationalLimit.OperationalLimitType rdf:resource='#_b05800c4-9744-45d8-8d9e-c1f39562e4fb' />\r\n"; xml += " <cim:IdentifiedObject.name>" + name + "_limit</cim:IdentifiedObject.name>\r\n"; xml += " <cim:OperationalLimit.OperationalLimitSet rdf:resource = '#_" + GUIDHelper.CreateDerivedGuid(terminalMrid, 750, true).ToString() + "'/>\r\n"; xml += " <cim:CurrentLimit.value>" + DoubleToString(currentLimitValue) + "</cim:CurrentLimit.value>\r\n"; xml += "</cim:CurrentLimit>\r\n\r\n"; _writer.Write(xml); }
public void HttpPost(int actionId, byte[] data) { //Debug.Log(string.Format("http post:[actionId:{0},dataLenght:{1}]", actionId, data == null ? 0 : data.Length)); byte[] encodeBytes = new byte[0]; if (data != null && data.Length > 0) { encodeBytes = DESHelper.EncodeBytes(GZipHelper.compress(data), AppContext.GetInstance().getDesKey()); } HTTPRequest request = new HTTPRequest(new Uri(Constants.COMMON_DISPATCH_URL), HTTPMethods.Post, OnRequestFinished); request.SetHeader("TI", GUIDHelper.generate()); request.SetHeader("AI", actionId.ToString()); request.SetHeader("TK", ignoreSession(actionId) ? Constants.DEFAULT_TOKEN: LocalToken()); request.SetHeader("FP", SystemInfo.deviceUniqueIdentifier); request.SetHeader("X-Real-Ip", "192.168.15.100"); request.ConnectTimeout = TimeSpan.FromSeconds(30); request.RawData = encodeBytes; request.Send(); }
public void SendPlayCards(PlayCardsReq req) { HideAll(); SocketRequest sr = new SocketRequest(); sr.p1 = GUIDHelper.generate(); sr.p2 = "playCards"; sr.p3 = LocalToken(); sr.p4 = SystemInfo.deviceUniqueIdentifier; sr.p5 = AppContext.GetInstance().Watch.gameId.ToString(); sr.p6 = AppContext.GetInstance().Watch.seatId.ToString(); sr.p7 = AppContext.GetInstance().Watch.seqInGame.ToString(); sr.p8 = req.typeWithPoints.cardsType.ToString(); sr.p9 = req.Keys(); sr.p10 = CardHelper.GetInstance().Join(req.points); sr.p11 = CardHelper.GetInstance().Join(req.handPoints); SendBytes(ProtoHelper.Proto2Bytes(sr)); GetComponent <GameUIRender>().SendMessage("LetItGo"); }
/// <summary> /// /// </summary> /// <param name="token"></param> /// <returns></returns> public ActionResult CheckToken(string token) { var ip = HttpContext.Request.UserHostAddress; var users = _user.GetUsers(); var userModel = users.FirstOrDefault(x => x.EIp == ip && x.EToken == token && x.ERefreshTime.AddMinutes(60) > DateTime.Now); if (userModel == null) { return(Json(null, JsonRequestBehavior.DenyGet)); } { userModel.ERefreshTime = DateTime.Now; token = GUIDHelper.GetGuid(); userModel.EToken = token; userModel.EIp = HttpContext.Request.UserHostAddress; _user.UpdateUsers(new List <UserModel>() { userModel }); return(Json(token, JsonRequestBehavior.DenyGet)); } }
private void loadMessage() { string _prefix = "NBS-"; GUIDHelper helper = GUIDHelper.getInstance(); ObservableCollection <MessageInfo> initList = new ObservableCollection <MessageInfo>(); for (int i = 0; i < 20; i = i + 1) { MessageInfo m = new MessageInfo(); //m.HashID = "00000" + i; m.HashID = helper.GetGUID().Substring(10); m.NickName = _prefix + "" + i; m.RealTime = DateTime.Now.AddHours((20 - 20 / (i + 1))).AddMinutes(-25 / (i + 1)); m.IsSelf = i % 3 == 0 ? false : true; if (i % 2 == 0) { m.AvatarImg = @"pack://*****:*****@"pack://application:,,,/avatars/fuchen200.png"; } int a = i > 5 ? i : 5; StringBuilder sb = new StringBuilder(); for (int j = 1; j < a; j++) { sb.Append(j + "kKsvK" + j); } m.MsgContent = sb.ToString(); initList.Add(m); } if (initList != null) { MsgRecordList = initList; } }
/// <summary> /// 保存图片 /// </summary> /// <param name="pictures"></param> /// <returns></returns> public bool SavePicture(PictureModel picture) { //项目分类 var categories = _category.GetCategories(); //项目 var items = _item.GetItems(); var picturesInDatabase = GetPictures(); //需要修改的照片 var pictures2modify = new List <KeyValuePair <string, string> >(); //1.处理图片的Id if (string.IsNullOrWhiteSpace(picture.EId) || !picturesInDatabase.Exists(x => x.EId == picture.EId)) { //新建一个Id picture.EId = GUIDHelper.GetGuid(); picture.EIsNew = true; //处理分类 var catetoryName = picture.ETakeTime.ToString("yyyy-MM"); var category = categories.FirstOrDefault(x => x.EName == catetoryName); var parentCategoryName = picture.ETakeTime.ToString("yyyy"); var parentCategory = categories.FirstOrDefault(x => x.EName == parentCategoryName); if (parentCategory == null) { parentCategory = new CategoryModel() { EId = GUIDHelper.GetGuid(), EName = parentCategoryName, EIsNew = true }; categories.Add(parentCategory); } //如果不存在 if (category == null) { category = new CategoryModel() { EId = GUIDHelper.GetGuid(), EName = catetoryName, EParentId = parentCategory.EId, EIsNew = true }; categories.Add(category); } //处理项目 var item = new ItemModel() { EId = GUIDHelper.GetGuid(), ECategoryId = category.EId, EIsNew = true, EName = picture.ETakeTime.ToString("yyyy-MM-dd"), EDetailName = picture.EName, EDateTime = picture.ETakeTime }; items.Add(item); picture.EItemId = item.EId; pictures2modify.Add(new KeyValuePair <string, string>(picture.EPath, picture.EId)); } PictureHandler.SetPictureInfo(PictruePropertyHexTable.Author, pictures2modify); _item.SaveItems(items); _category.SaveCategorys(categories); SavePictures(new List <PictureModel>() { picture }); return(true); }
public async Task <IActionResult> ClientModulePostTicket([FromRoute] Guid projectCode, [FromBody] TicketPostBase boundObject, ApiVersion version) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var projectDB = await _context.Projects.FirstOrDefaultAsync(p => p.Code == projectCode); if (projectDB == null) { return(Conflict(new { header = "Please contact the website admin.", subheader = "", text = "The project-id '" + projectCode + "' is not registered." })); } else if (projectDB.IsPaused) { return(Conflict(new { header = "Please be patient.", subheader = "", text = "This page is currently paused for feedback." })); } if (!String.IsNullOrEmpty(boundObject.IotaAddress)) { if (!IOTAHelper.IsAddress(boundObject.IotaAddress)) { return(BadRequest(new { header = "Input error", subheader = "", text = "The submitted IOTA address is not a valid address, please check it." })); } } if (!String.IsNullOrEmpty(boundObject.Email)) { if (!_regexUtil.IsValidEmail(boundObject.Email)) { return(BadRequest(new { header = "Input error", subheader = "", text = "The submitted email address is not a valid address, please check it." })); } } if (boundObject.Url.EndsWith("/")) { boundObject.Url.Remove(boundObject.Url.Length - 1); } Ticket ticket = new Ticket() { Name = boundObject.Name, Email = boundObject.Email, IotaAddress = boundObject.IotaAddress, NavigatorString = boundObject.NavigatorString, BrowserFontSize = boundObject.BrowserFontSize, ScreenHeight = boundObject.ScreenHeight, ScreenWidth = boundObject.ScreenWidth, Annotations = boundObject.Annotations, Sent = boundObject.Sent, IsPublic = boundObject.IsPublic, Url = boundObject.Url, ViewGuid = GUIDHelper.CreateCryptographicallySecureGuid(), // a test if same ViewGuid already exists would be good ProjectId = projectDB.Id }; _context.Tickets.Add(ticket); await _context.SaveChangesAsync(); //Task.Run(() => // not a good idea in ASP.net! //{ // Email.DefaultSender = new MailgunSender("", // Mailgun Domain // "" // Mailgun API Key // ); // var email = Email // .From("*****@*****.**") // .To(ticket.Email) // .Subject("Thanks for your feedback") // .Body("Thank you"); // email.Send(); //}); var domainDB = await _context.Domains.FirstOrDefaultAsync(d => d.Id == projectDB.DomainId); if (domainDB != null) { await _hubContext.Clients.All.SendAsync("TicketAdded", new { authIdentifier = domainDB.UserAuthIdentifier, domain = domainDB.Url, projectName = projectDB.Name, domainId = domainDB.Id, projectId = projectDB.Id, ticketId = ticket.Id, sent = ticket.Sent }); // would be better to take an extra (temporary) identifier, that the client-side stores } return(CreatedAtAction(nameof(ClientModuleGetByViewID), new { projectCode, viewGuid = ticket.ViewGuid, version = $"{version}" }, ticket)); }
// FIXME: this should be the contructor public static Node FindChildNodes(GameObject unityObj) { var node = new Node() { Children = new Node[unityObj.transform.childCount], UnityObj = unityObj, GUID = new Guid(GUIDHelper.ExtractGUIDFromName(unityObj.name)), Name = GUIDHelper.RemoveGUIDFromName(unityObj.name) }; // unityObj.name = node.Name; // write name without GUID back to Object node.IsAnnotatable = node.CheckIfObjectIsAnnotatable(); var renderer = unityObj.GetComponent <MeshRenderer>(); if (renderer != null && unityObj.GetComponent <IgnoreNode>() == null) { node.HasBounds = true; node.BoundsWithContext.Bounds = renderer.bounds; var meshfilter = unityObj.GetComponent <MeshFilter>(); if (node.BoundsWithContext.HasLocalBounds = meshfilter != null) { node.BoundsWithContext.LocalBounds = meshfilter.mesh.bounds; node.BoundsWithContext.LocalTransform = unityObj.transform; } var meshCollider = unityObj.GetComponent <MeshCollider>(); if (meshCollider == null && meshfilter != null) { meshCollider = unityObj.AddComponent <MeshCollider>(); } if (node.BoundsWithContext.HasMeshCollider = meshCollider != null) { node.BoundsWithContext.MeshCollider = meshCollider; } node.HasGeometry = true; } for (int index = 0; index < unityObj.transform.childCount; index++) { var childObj = unityObj.transform.GetChild(index).gameObject; var childNode = FindChildNodes(childObj); childNode.Parent = node; node.Children[index] = childNode; if (childNode.HasBounds) { if (node.HasBounds) { node.BoundsWithContext.Bounds.Encapsulate(childNode.BoundsWithContext.Bounds); node.HasBounds = true; } else { node.BoundsWithContext.Bounds = childNode.BoundsWithContext.Bounds; node.HasBounds = childNode.HasBounds; } } } return(node); }
public async Task <IActionResult> PostProject([FromRoute] int domainID, [FromBody] ProjectPostAndPutBase boundObject, ApiVersion version) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { base.SetAuthIdentifierFromRequest(); if (!new RegexUtilities().IsValidEmail(boundObject.NotificationEmail)) { return(BadRequest(new { header = "Input error", subheader = "", text = "Please submit a valid email." })); } var domainDB = await QueryHelper.GetDomainByIDAuthenticatedAsync(_context, _authIdentifier, domainID); if (domainDB == null) { return(NotFound(new { header = "The given domain-id was not found in your domains", subheader = "", text = "Please check the id." })); } boundObject.Name = boundObject.Name.Trim(); await _context.Entry(domainDB).Collection(t => t.Projects).LoadAsync(); // load explicitly if (domainDB.Projects.Any(p => p.Name == boundObject.Name && p.DomainId == domainID)) { return(Conflict(new { header = "Conflict", subheader = "", text = "There is already a project with the name '" + boundObject.Name + "' in your projects." })); } // generate real Project Project project = new Project { Name = boundObject.Name, Description = boundObject.Description, Code = GUIDHelper.CreateCryptographicallySecureGuid(), // a test if same ViewGuid already exists would be good NotificationEmail = boundObject.NotificationEmail, IsPaused = boundObject.IsPaused, DomainId = domainID }; _context.Projects.Add(project); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetProject), new { domainID, id = project.Id, version = $"{version}" }, project)); } catch (MissingAuthIdentifierException) { return(_statusCode); } catch { throw; } }
private void Awake() { CreateNodesFromHierachy(); GUID = new Guid(GUIDHelper.ExtractGUIDFromName(this.name)); }
public async Task <IActionResult> ClientModulePostAlternativesSelection([FromRoute] Guid projectCode, [FromBody] AlternativesSelectionPostBase boundObject, ApiVersion version) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var projectDB = await _context.Projects.FirstOrDefaultAsync(p => p.Code == projectCode); if (projectDB == null) { return(Conflict(new { header = "Please contact the website admin.", subheader = "", text = "The project-id '" + projectCode + "' is not registered." })); } else if (projectDB.IsPaused) { return(Conflict(new { header = "Please be patient.", subheader = "", text = "This page is currently paused for feedback." })); } if (!String.IsNullOrEmpty(boundObject.IotaAddress)) { if (!IOTAHelper.IsAddress(boundObject.IotaAddress)) { return(BadRequest(new { header = "Input error", subheader = "", text = "The submitted IOTA address is not a valid address, please check it." })); } } if (!String.IsNullOrEmpty(boundObject.Email)) { if (!_regexUtil.IsValidEmail(boundObject.Email)) { return(BadRequest(new { header = "Input error", subheader = "", text = "The submitted email address is not a valid address, please check it." })); } } if (boundObject.Url.EndsWith("/")) { boundObject.Url.Remove(boundObject.Url.Length - 1); } AlternativesSelection selection = new AlternativesSelection() { Name = boundObject.Name, Email = boundObject.Email, IotaAddress = boundObject.IotaAddress, Sent = boundObject.Sent, AreaInfoItems = boundObject.AreaInfoItems, Url = boundObject.Url, ViewGuid = GUIDHelper.CreateCryptographicallySecureGuid(), // a test if same ViewGuid already exists would be good ProjectId = projectDB.Id }; _context.AlternativesSelections.Add(selection); await _context.SaveChangesAsync(); var domainDB = await _context.Domains.FirstOrDefaultAsync(d => d.Id == projectDB.DomainId); if (domainDB != null) { await _hubContext.Clients.All.SendAsync("AlternativesSelectionAdded", new { authIdentifier = domainDB.UserAuthIdentifier, domain = domainDB.Url, projectName = projectDB.Name, domainId = domainDB.Id, projectId = projectDB.Id, alternativesSelectionId = selection.Id, sent = selection.Sent }); // would be better to take an extra (temporary) identifier, that the client-side stores } return(CreatedAtAction(nameof(ClientModuleGetByViewID), new { projectCode, viewGuid = selection.ViewGuid, version = $"{version}" }, selection)); }
public IEnumerable <WeatherForecast> Get(string id = "") { _logger.LogInformation("测试测试:" + id); //测试redis读写 _redisProvider.Client.Set("test1", "dfas", 600); var ss = _redisProvider.Client.Get("test1"); //测试mongodb读写 var operLogColl = _mongoProvider.Mongo.GenMongoCollection <OperLog>(); var newid = GUIDHelper.CreateGUID().GetGUIDString(); var data = new OperLog() { OldData = "asdf", NewData = "21012109370757596801402089595806", OLID = newid, OperID = newid, OperName = "18120846228", PrimaryKey = "", OperType = 1, TableName = "test", OperTime = DateTime.Now }; //添加1条数据 operLogColl.InsertOne(data); //测试redis分布式事务 try { while (true) { if (_redisProvider.SetNx("test", 10000)) { _logger.LogInformation("开始事务"); Thread.Sleep(3000); _logger.LogInformation("结束事务"); break; } Thread.Sleep(100); } } catch (Exception ex) { //throw; } finally { _redisProvider.Remove("test"); } //throw new Exception("测试错误异常"); var rng = new Random(); return(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray()); }
public KonstantCimArchiveWriter(IEnumerable <PhysicalNetworkModel.IdentifiedObject> cimObjects, string outputFolder, string archiveName, Guid modelRdfId, bool highVoltageOnly = false) { System.IO.Directory.CreateDirectory(outputFolder); System.IO.Directory.CreateDirectory(outputFolder + "\\files"); CimContext initialContext = CimContext.Create(cimObjects); string eqTempFileName = outputFolder + @"\files\" + archiveName + "_eq.xml"; string glTempFileName = outputFolder + @"\files\" + archiveName + "_gl.xml"; string aiTempFileName = outputFolder + @"\files\" + archiveName + "_ai.xml"; string peTempFileName = outputFolder + @"\files\" + archiveName + "_pe.xml"; Dictionary <string, string> assetToEqRefs = new Dictionary <string, string>(); var filtered = FilterHelper.Filter(initialContext, new FilterRule() { MinVoltageLevel = highVoltageOnly ? 20000 : 10000, }); var mappingContext = new MappingContext(); // Reinitialize cim context to filtered objects CimContext _context = CimContext.Create(filtered); var converter = new PNM2PowerFactoryCimConverter(filtered, new List <IPreProcessor> { new ACLSMerger(mappingContext), new TransformerCableMerger(mappingContext), new KonstantBigEnergyConsumerHandler(mappingContext), new KonstantPowerFactoryDataPrepareAndFix(mappingContext) }); // Reinitialize cim context to converted objects var outputCimObjects = converter.GetCimObjects().ToList(); // We need to reinitialize context, because converter has modified objects _context = CimContext.Create(outputCimObjects); var eqWriter = new EQ_Writer(eqTempFileName, _context, mappingContext, modelRdfId, archiveName); eqWriter.ForceThreePhases = true; var glWriter = new GL_Writer(glTempFileName); var aiWriter = new AI_Writer(aiTempFileName, _context, mappingContext); var peWriter = new PE_Writer(peTempFileName, _context, mappingContext); ////////////////////// // do the lines var lineContext = new LineInfoContext(_context); //lineContext.CreateLineInfo(); Dictionary <SimpleLine, string> lineToGuid = new Dictionary <SimpleLine, string>(); foreach (var line in lineContext.GetLines()) { var lineGuid = GUIDHelper.CreateDerivedGuid(Guid.Parse(line.Children[0].Equipment.mRID), 678, true).ToString(); lineToGuid.Add(line, lineGuid); //eqWriter.AddLine(lineGuid, line.Name); } ////////////////////// // do the general cim objects foreach (var cimObject in _context.GetAllObjects()) { if (cimObject.name != null && cimObject.name.Contains("571313124501006982")) { } if (!(cimObject is Location) && !(cimObject is VoltageLevel && ((VoltageLevel)cimObject).BaseVoltage < 400)) { if (cimObject is ACLineSegment) { var acls = cimObject as ACLineSegment; var lines = lineContext.GetLines().Where(l => l.Children.Exists(c => c.Equipment == acls)).ToList(); if (lines.Count == 1) { var line = lines[0]; eqWriter.AddPNMObject(acls, lineToGuid[line]); } else { eqWriter.AddPNMObject((dynamic)cimObject); } } else { // Don't add things that goes into asset and protectionn file if (!( (cimObject is PhysicalNetworkModel.Asset) || (cimObject is PhysicalNetworkModel.AssetInfo) || (cimObject is PhysicalNetworkModel.ProductAssetModel) || (cimObject is PhysicalNetworkModel.Manufacturer) || (cimObject is CurrentTransformerExt) || (cimObject is PotentialTransformer) || (cimObject is ProtectionEquipmentExt) )) { eqWriter.AddPNMObject((dynamic)cimObject); } } } if (cimObject is PowerSystemResource) { var psrObj = cimObject as PowerSystemResource; if (psrObj.Location != null && psrObj.Location.@ref != null && psrObj.PSRType != "InternalCable") { var loc = _context.GetObject <PhysicalNetworkModel.LocationExt>(psrObj.Location.@ref); glWriter.AddLocation(Guid.Parse(psrObj.mRID), loc); } if (psrObj.Assets != null && psrObj.Assets.@ref != null) { assetToEqRefs.Add(psrObj.Assets.@ref, psrObj.mRID); } } } ////////////////////// // do the asset object foreach (var cimObject in _context.GetAllObjects()) { if (cimObject is PhysicalNetworkModel.Asset) { if (assetToEqRefs.ContainsKey(cimObject.mRID)) { var eqMrid = assetToEqRefs[cimObject.mRID]; aiWriter.AddPNMObject((dynamic)cimObject, eqMrid); } } if (cimObject is PhysicalNetworkModel.AssetInfo) { aiWriter.AddPNMObject((dynamic)cimObject); } if (cimObject is PhysicalNetworkModel.ProductAssetModel) { aiWriter.AddPNMObject((dynamic)cimObject); } if (cimObject is PhysicalNetworkModel.Manufacturer) { aiWriter.AddPNMObject((dynamic)cimObject); } } ////////////////////// // do the projection object foreach (var cimObject in _context.GetAllObjects()) { if (cimObject is PhysicalNetworkModel.ProtectionEquipment) { peWriter.AddPNMObject((dynamic)cimObject); } if (cimObject is PhysicalNetworkModel.PotentialTransformer) { peWriter.AddPNMObject((dynamic)cimObject); } if (cimObject is PhysicalNetworkModel.CurrentTransformer) { peWriter.AddPNMObject((dynamic)cimObject); } } eqWriter.Close(); glWriter.Close(); aiWriter.Close(); peWriter.Close(); string startPath = outputFolder + "\\files"; string zipPath = outputFolder + "\\" + archiveName + ".zip"; File.Delete(zipPath); ZipFile.CreateFromDirectory(startPath, zipPath); }
public IEnumerable <IdentifiedObject> Transform(CimContext context, IEnumerable <IdentifiedObject> inputParam) { FeederInfoContext feederContext = new FeederInfoContext(context); feederContext.CreateFeederObjects(); List <IdentifiedObject> input = inputParam.ToList(); HashSet <PhysicalNetworkModel.IdentifiedObject> dropList = new HashSet <IdentifiedObject>(); List <PhysicalNetworkModel.IdentifiedObject> addList = new List <IdentifiedObject>(); // AssetInfo to Asset ref dictionary Dictionary <string, string> assetInfoToAssetRef = new Dictionary <string, string>(); foreach (var inputCimObject in input) { if (inputCimObject is PhysicalNetworkModel.Asset) { var asset = inputCimObject as PhysicalNetworkModel.Asset; if (asset.AssetInfo != null && !assetInfoToAssetRef.ContainsKey(asset.AssetInfo.@ref)) { assetInfoToAssetRef.Add(asset.AssetInfo.@ref, asset.mRID); } } } // Asset to Equipment ref dictionary Dictionary <string, string> assetToEquipmentRef = new Dictionary <string, string>(); foreach (var inputCimObject in input) { if (inputCimObject is PhysicalNetworkModel.PowerSystemResource) { var psr = inputCimObject as PhysicalNetworkModel.PowerSystemResource; if (psr.Assets != null) { assetToEquipmentRef.Add(psr.Assets.@ref, psr.mRID); } } } // Set busbar names to station + voltagelevel + bay foreach (var inputCimObject in input) { if (inputCimObject is BusbarSection) { var bus = inputCimObject as BusbarSection; var st = bus.GetSubstation(true, context); bus.name = st.name + "_" + GetVoltageLevelStr(bus.BaseVoltage) + "_" + bus.name; var feederInfo = feederContext.GeConductingEquipmentFeederInfo(bus); if (feederInfo != null && feederInfo.Feeders != null && feederInfo.Feeders.Count > 0) { var feeder = feederInfo.Feeders[0]; if (feeder.ConnectionPoint.Substation != null) { bus.description = feeder.ConnectionPoint.Substation.name; } } } } // Set feeder name on junction connectivity nodes between cables foreach (var inputCimObject in input) { if (inputCimObject is ConnectivityNode) { var cn = inputCimObject as ConnectivityNode; if (cn.mRID == "c540b203-e442-7027-824c-bc561b3de47d") { } var cnEqs = context.GetConnections(cn); if (cnEqs.Count > 0) { if (cnEqs.All(e => e.ConductingEquipment is ACLineSegment)) { var eq = cnEqs.First().ConductingEquipment; var feederInfo = feederContext.GeConductingEquipmentFeederInfo(eq); if (feederInfo != null && feederInfo.Feeders != null && feederInfo.Feeders.Count > 0) { var feeder = feederInfo.Feeders[0]; if (feeder.ConnectionPoint.Substation != null) { cn.description = feeder.ConnectionPoint.Substation.name; } } } } } } // Set peterson coil name to station + gis name + min og max foreach (var inputCimObject in input) { if (inputCimObject is PetersenCoil) { var coil = inputCimObject as PetersenCoil; var st = coil.GetSubstation(true, context); if (coil.Asset != null && coil.Asset.AssetInfo != null && coil.Asset.AssetInfo.@ref != null) { var coilInfo = context.GetObject <PetersenCoilInfoExt>(coil.Asset.AssetInfo.@ref); coil.name = st.name + " " + coil.name; if (coilInfo != null && coilInfo.minimumCurrent != null && coilInfo.maximumCurrent != null) { coil.name += " " + (int)coilInfo?.minimumCurrent?.Value + "-" + (int)coilInfo?.maximumCurrent?.Value; } else { Logger.Log(LogLevel.Warning, "Slukkepole på station: " + st.name + " mangler værdier."); } } else { coil.name = st.name + " " + coil.name + " 0-0"; } } } // Set reactor coil (linear shunt compensator) to station + gis name + min og max foreach (var inputCimObject in input) { if (inputCimObject is LinearShuntCompensator) { var coil = inputCimObject as LinearShuntCompensator; var st = coil.GetSubstation(true, context); if (coil.Asset != null && coil.Asset.AssetInfo != null && coil.Asset.AssetInfo.@ref != null) { var coilInfo = context.GetObject <LinearShuntCompensatorInfoExt>(coil.Asset.AssetInfo.@ref); coil.name = st.name + " " + coil.name; if (coilInfo != null && coilInfo.minimumReactivePower != null && coilInfo.maximumReactivePower != null) { coil.name += " " + (int)coilInfo?.minimumReactivePower?.Value + "-" + (int)coilInfo?.maximumReactivePower?.Value; } else { Logger.Log(LogLevel.Warning, "Reaktorspole på station: " + st.name + " mangler værdier."); } } else { coil.name = st.name + " " + coil.name + " 0-0"; } } } // Remove injection > 50 kV foreach (var inputCimObject in input) { if (inputCimObject is ExternalNetworkInjection) { var inj = inputCimObject as ExternalNetworkInjection; if (inj.BaseVoltage > 50000) { dropList.Add(inj); var injConnections = context.GetConnections(inj); foreach (var injCon in injConnections) { dropList.Add(injCon.Terminal); } } } } // Fix and check objects foreach (var inputCimObject in input) { // Remove switch gear busbar asset model information (because PF complain about missing type, and Konstant/Thue says he don't want types into PF for now if (inputCimObject is BusbarSectionInfo) { BusbarSectionInfo bsi = inputCimObject as BusbarSectionInfo; bsi.AssetModel = null; var assetMrid = assetInfoToAssetRef[inputCimObject.mRID]; var asset = context.GetObject <PhysicalNetworkModel.Asset>(assetMrid); asset.type = null; asset.name = null; asset.AssetModel = null; } // Remove asset manufacture information on busbars and switches if (inputCimObject is BusbarSection || inputCimObject is Switch) { ConductingEquipment ci = inputCimObject as ConductingEquipment; var asset = context.GetObject <PhysicalNetworkModel.Asset>(ci.Assets.@ref); asset.type = null; asset.name = null; asset.AssetModel = null; } // Remove measurment current transformer and cts sitting on voltage level < 60 kV if (inputCimObject is CurrentTransformer && !((CurrentTransformer)inputCimObject).PSRType.ToLower().Contains("kundemaaling")) { var ct = inputCimObject as CurrentTransformer; bool ctIsDropped = false; try { var ctTerminal = context.GetObject <Terminal>(ct.Terminal.@ref); var ctEq = context.GetObject <ConductingEquipment>(ctTerminal.ConductingEquipment.@ref); if (ctEq.BaseVoltage < 60000) { dropList.Add(ct); ctIsDropped = true; } } catch (ArgumentException ex) { dropList.Add(ct); ctIsDropped = true; } // Move CT to line end, transformer end var st = ct.GetSubstation(true, context); foreach (var eq in st.GetEquipments(context)) { // If component inside same bay as ct if (eq is ConductingEquipment && eq.EquipmentContainer.@ref == ct.EquipmentContainer.@ref) { var ci = eq as ConductingEquipment; var ciConnections = context.GetConnections(ci); foreach (var ciConnection in ciConnections) { var ciNeighbors = context.GetConnections(ciConnection.ConnectivityNode).Where(c => c.ConductingEquipment != ci).ToList(); if (ciNeighbors.Any(c => c.ConductingEquipment is ACLineSegment)) { ct.Terminal.@ref = ciConnection.Terminal.mRID; } else if (ciNeighbors.Any(c => c.ConductingEquipment is PowerTransformer)) { ct.Terminal.@ref = ciConnection.Terminal.mRID; } else if (ciNeighbors.Count == 0) { ct.Terminal.@ref = ciConnection.Terminal.mRID; } } } } } // Check that current transformer infos has currents if (inputCimObject is CurrentTransformerInfoExt) { var ctInfo = inputCimObject as CurrentTransformerInfoExt; var assetMrid = assetInfoToAssetRef[ctInfo.mRID]; var eqMrid = assetToEquipmentRef[assetMrid]; var ct = context.GetObject <CurrentTransformerExt>(eqMrid); var ctAsset = context.GetObject <PhysicalNetworkModel.Asset>(assetMrid); if (ct.PSRType != null && ct.PSRType == "StromTransformer") { // Make sure primary and secondary current is set, because otherwise PF import fails if (ctInfo.primaryCurrent == null) { var stName = ct.GetSubstation(true, context).name; var bayName = ct.GetBay(true, context).name; Logger.Log(LogLevel.Warning, "CT Missing primary current. Will not be transfered to PF: " + stName + " " + bayName); ctInfo.primaryCurrent = new CurrentFlow() { Value = 0, unit = UnitSymbol.A }; dropList.Add(ct); dropList.Add(ctAsset); dropList.Add(ctInfo); } if (ctInfo.secondaryCurrent == null) { var stName = ct.GetSubstation(true, context).name; var bayName = ct.GetBay(true, context).name; Logger.Log(LogLevel.Warning, "CT Missing secondary current: " + stName + " " + bayName); ctInfo.secondaryCurrent = new CurrentFlow() { Value = 0, unit = UnitSymbol.A }; } } else { dropList.Add(ct); dropList.Add(ctAsset); dropList.Add(ctInfo); } } // Remove potential transformers sitting on voltage level < 60 kV if (inputCimObject is PotentialTransformer) { var pt = inputCimObject as PotentialTransformer; // If terminal point to object we don't have including - i.e. some 400 volt component - don't bother with the CT if (context.GetAllObjects().Exists(o => o.mRID == pt.Terminal.@ref)) { var ptTerminal = context.GetObject <Terminal>(pt.Terminal.@ref); var ptEq = context.GetObject <ConductingEquipment>(ptTerminal.ConductingEquipment.@ref); if (ptEq.BaseVoltage < 60000) { dropList.Add(pt); } } else { dropList.Add(pt); } } // Check that potential transformer info has voltages if (inputCimObject is PotentialTransformerInfoExt) { var vtInfo = inputCimObject as PotentialTransformerInfoExt; var assetMrid = assetInfoToAssetRef[vtInfo.mRID]; var eqMrid = assetToEquipmentRef[assetMrid]; var vtAsset = context.GetObject <PhysicalNetworkModel.Asset>(assetMrid); var vt = context.GetObject <PotentialTransformer>(eqMrid); var vtSt = vt.GetSubstation(true, context); // Make sure primary and secondary voltage is set, because otherwise PF import fails if (vtInfo.primaryVoltage == null) { vtInfo.primaryVoltage = new Voltage() { Value = 0, unit = UnitSymbol.V }; var stName = vt.GetSubstation(true, context).name; var bayName = vt.GetBay(true, context).name; Logger.Log(LogLevel.Warning, "VT Missing primary voltage. VT will not be transfered to PF." + stName + " " + bayName); dropList.Add(vt); dropList.Add(vtAsset); dropList.Add(vtInfo); } else if (vtInfo.secondaryVoltage == null) { vtInfo.secondaryVoltage = new Voltage() { Value = 0, unit = UnitSymbol.V }; var stName = vt.GetSubstation(true, context).name; var bayName = vt.GetBay(true, context).name; Logger.Log(LogLevel.Warning, "VT Missing secondary voltage. VI will not be transfered to PF." + stName + " " + bayName); dropList.Add(vt); dropList.Add(vtAsset); dropList.Add(vtInfo); } } // Set relay names to station + bay if (inputCimObject is ProtectionEquipment) { var relay = inputCimObject as ProtectionEquipment; // get relay station and bay via the switch it is connected to if (relay.ProtectedSwitches != null && relay.ProtectedSwitches.Length > 0) { try { var peSw = context.GetObject <PowerSystemResource>(relay.ProtectedSwitches[0].@ref); var bay = peSw.GetBay(true, context); var st = peSw.GetSubstation(true, context); relay.name = st.name + " " + bay.name; } catch (Exception ex) { Logger.Log(LogLevel.Warning, "Cannot find switch: " + relay.ProtectedSwitches[0].@ref + " connected to replay: " + inputCimObject.mRID); } } else { dropList.Add(inputCimObject); } } // Set electrical values on internal substation cables to 0 if (inputCimObject is ACLineSegment) { var acls = inputCimObject as ACLineSegment; if (acls.PSRType == "InternalCable") { // Set name to internal cable acls.name = "Internal Cable"; // Set length to 1 meter acls.length.Value = 1; // Set value to zero acls.r = new Resistance() { Value = 0 }; acls.r0 = new Resistance() { Value = 0 }; acls.x = new Reactance() { Value = 0 }; acls.x0 = new Reactance() { Value = 0 }; acls.bch = new Susceptance() { Value = 0 }; acls.b0ch = new Susceptance() { Value = 0 }; acls.gch = new Conductance() { Value = 0 }; acls.g0ch = new Conductance() { Value = 0 }; } } // Sæt transformer vikling navn og r,x,b,g værdier på vikling 2 til 0 if (inputCimObject is PowerTransformerEndExt) { var ptEnd = inputCimObject as PowerTransformerEndExt; var pt = context.GetObject <PowerTransformer>(ptEnd.PowerTransformer.@ref); ptEnd.name = pt.Substation.name + "_" + pt.name + "_T" + ptEnd.endNumber; /* Don't calculate r,x,b,g anymore. * if (ptEnd.endNumber == "1") * { * ptEnd.b0 = new Susceptance() { Value = 0 }; * ptEnd.g0 = new Conductance() { Value = 0 }; * * if (ptEnd.ratedU == null || * ptEnd.ratedS == null || * ptEnd.excitingCurrentZero == null || * ptEnd.loss == null || * ptEnd.lossZero == null || * ptEnd.uk == null) * { * // FIX: burde måske logge fejl, men PF skal nok brokke sig * } * else * { * // Beregn r: loss * (ratedU / ratedS * 1000)^2 * ptEnd.r = new Resistance() { Value = ptEnd.loss.Value * Math.Pow((ptEnd.ratedU.Value / (ptEnd.ratedS.Value * 1000)), 2) }; * * // Beregn g: (LossZero / ratedU^2) * double g = ptEnd.lossZero.Value / Math.Pow(ptEnd.ratedU.Value, 2); * ptEnd.g = new Conductance() { Value = g }; * * // Beregn YOC: (excitingCurrentZero*ratedS)/(100 * (ratedU^2)) * double yoc = (ptEnd.excitingCurrentZero.Value * (ptEnd.ratedS.Value * 1000)) / (100 * Math.Pow(ptEnd.ratedU.Value, 2)); * * // Beregn b: SQRT(YOC^2-g^2) * ptEnd.b = new Susceptance() * { * Value = Math.Sqrt(Math.Pow(yoc, 2) - Math.Pow(g, 2)) * }; * * // Beregn Zk: (uk*ratedU^2)/(100*ratedS) * double zk = (ptEnd.uk.Value * Math.Pow(ptEnd.ratedU.Value, 2)) / (100 * (ptEnd.ratedS.Value * 1000)); * * // Beregn x: SQRT(Zk^2-r^2) * ptEnd.x = new Reactance() * { * Value = Math.Sqrt( * Math.Pow(zk, 2) - Math.Pow(ptEnd.r.Value, 2) * ) * }; * } * } */ if (ptEnd.endNumber == "2") { // Set value to zero ptEnd.r = new Resistance() { Value = 0 }; ptEnd.r0 = new Resistance() { Value = 0 }; ptEnd.x = new Reactance() { Value = 0 }; ptEnd.x0 = new Reactance() { Value = 0 }; ptEnd.b = new Susceptance() { Value = 0 }; ptEnd.b0 = new Susceptance() { Value = 0 }; ptEnd.g = new Conductance() { Value = 0 }; ptEnd.g0 = new Conductance() { Value = 0 }; } } // Remove 'TRF' from transformer name if (inputCimObject is PowerTransformer) { inputCimObject.name = inputCimObject.name.Replace("TRF", ""); } // Ensure bay name is max 32 charaters if (inputCimObject is IdentifiedObject && inputCimObject.name != null && inputCimObject.name.Length > 32) { inputCimObject.name = inputCimObject.name.Substring(0, 32); } // Set name of disconnectors to ADSK if (inputCimObject is Disconnector) { inputCimObject.name = "ADSK"; } // Set name of disconnectors to ADSK if (inputCimObject is Fuse) { inputCimObject.name = "SIKRING"; } // Ensure connectivity nodes / busbars have proper names. // Needed by Konstant to support short circuit result extracts etc. PF uses the name of the node/busbar in reports. // Also needed to support time series import (Jakob busbar naming) if (inputCimObject is ConnectivityNode) { var cn = inputCimObject as ConnectivityNode; if (cn.mRID == "1663a3a8-a706-726a-8de5-7f57e2f9e68b") { } if (cn.name == null || cn.name.Length == 0) { var cnNeighbors = cn.GetNeighborConductingEquipments(context); var pt = cnNeighbors.Find(o => o is PowerTransformer) as PowerTransformer; var bus = cnNeighbors.Find(o => o is BusbarSection); if (pt != null) { var stVoltageLevels = context.GetSubstationVoltageLevels(pt.Substation); var ptConnections = context.GetConnections(pt); var ptTerminal = ptConnections.First(c => c.ConnectivityNode == cn); var ptEnds = pt.GetEnds(context); var ptEnd = ptEnds.Find(e => e.Terminal.@ref == ptTerminal.Terminal.mRID); double ptEndVoltageLevel = ptEnd.BaseVoltage; if (pt.name != null) { // HACK SHOULD BE CLEANED UP // Terminal actual exist in source, but get trown away in filter, because nothing connected to it if (!ptConnections.Exists(c => c.Terminal.sequenceNumber == "2")) { Logger.Log(LogLevel.Info, "Station: " + pt.Substation.name + " Trafo: " + pt.name + " mangler secondær skinne. Vil bliver oprettet"); var ptLvCn = new ConnectivityNode() { mRID = Guid.NewGuid().ToString(), name = pt.GetSubstation(true, context).name + "_" + GetVoltageLevelStr(400) + "_" + pt.name.Replace("TRF", "") }; addList.Add(ptLvCn); if (stVoltageLevels.Exists(o => o.BaseVoltage == 400)) { var vl = stVoltageLevels.First(o => o.BaseVoltage == 400); _mappingContext.ConnectivityNodeToVoltageLevel.Add(ptLvCn, vl); } else { var vl = new DAX.CIM.PhysicalNetworkModel.VoltageLevel() { mRID = Guid.NewGuid().ToString(), name = "0,4 kV", EquipmentContainer1 = new VoltageLevelEquipmentContainer() { @ref = pt.Substation.mRID }, BaseVoltage = 400 }; addList.Add(vl); stVoltageLevels.Add(vl); _mappingContext.ConnectivityNodeToVoltageLevel.Add(ptLvCn, vl); } var ptLvTerminal = new Terminal() { mRID = Guid.NewGuid().ToString(), phases = PhaseCode.ABCN, phasesSpecified = true, sequenceNumber = "2", ConnectivityNode = new TerminalConnectivityNode() { @ref = ptLvCn.mRID }, ConductingEquipment = new TerminalConductingEquipment { @ref = pt.mRID } }; var ptEnd2 = context.GetPowerTransformerEnds(pt).First(p => p.endNumber == "2"); ptEnd2.Terminal = new TransformerEndTerminal() { @ref = ptLvTerminal.mRID }; addList.Add(ptLvTerminal); } } // IF the PT END CN is connected to a conducting equipment if (cnNeighbors.Exists(o => !(o is PowerTransformer) && o.BaseVoltage > 0.0)) { ptEndVoltageLevel = cnNeighbors.First(o => !(o is PowerTransformer) && o.BaseVoltage > 0.0).BaseVoltage; if (stVoltageLevels.Exists(o => o.BaseVoltage == ptEndVoltageLevel)) { var vl = stVoltageLevels.First(o => o.BaseVoltage == ptEndVoltageLevel); _mappingContext.ConnectivityNodeToVoltageLevel.Add(cn, vl); } } // IF the PT END CN is *not* connected to anything else { // Set CN to PT END voltage level var vl = stVoltageLevels.First(o => o.BaseVoltage == ptEndVoltageLevel); _mappingContext.ConnectivityNodeToVoltageLevel.Add(cn, vl); // If 60 kV transformer secondary side if (ptEndVoltageLevel < 20000 && ptEndVoltageLevel > 5000) { if (ptEnds.Exists(e => e.BaseVoltage == 60000)) { EnergyConsumer ec = new EnergyConsumer() { mRID = GUIDHelper.CreateDerivedGuid(Guid.Parse(pt.mRID), 1001, true).ToString(), name = pt.GetSubstation(true, context).name + "_" + GetVoltageLevelStr(ptEndVoltageLevel) + "_" + pt.name.Replace("TRF", ""), EquipmentContainer = new EquipmentEquipmentContainer() { @ref = vl.mRID }, BaseVoltage = vl.BaseVoltage }; Terminal ecTerm = new Terminal() { mRID = GUIDHelper.CreateDerivedGuid(Guid.Parse(pt.mRID), 1002, true).ToString(), name = ec.name + "_T1", ConductingEquipment = new TerminalConductingEquipment() { @ref = ec.mRID }, ConnectivityNode = new TerminalConnectivityNode() { @ref = cn.mRID } }; addList.Add(ec); addList.Add(ecTerm); } } } cn.name = pt.GetSubstation(true, context).name + "_" + GetVoltageLevelStr(ptEndVoltageLevel) + "_" + pt.name.Replace("TRF", ""); /* * // Hvis trafo deler node med skinne, eller node er 400 volt, så brug jakob navngivning * if (bus != null || ptEndVoltageLevel == 400) * cn.name = pt.GetSubstation(true, context).name + "_" + GetVoltageLevelStr(ptEndVoltageLevel) + "_" + pt.name.Replace("TRF", ""); * else * cn.name = "CN"; */ } else if (bus != null && bus.name != null) { cn.name = bus.name; cn.description = bus.description; } else { var bay = cn.GetBay(false, context); if (bay != null) { if (cnNeighbors.Count == 1 || cnNeighbors.Exists(n => !(n is Switch))) { cn.name = bay.name + " ENDE"; } else { cn.name = bay.name; } } else { cn.name = "CN"; } } } } } // return objects, except the one dropped foreach (var inputObj in input) { if (!dropList.Contains(inputObj)) { yield return(inputObj); } } // yield added objects, foreach (var inputObj in addList) { yield return(inputObj); } }