//获得某个的章节的level信息 public List <LevelInfo> GetChapterLevel(int chapter) { Log.GUI("GetChapterLevel " + chapter); List <LevelInfo> allLevels = null; //int c = 0; Log.GUI("copyInfoLength " + copyInfo.CopyInfoCount); int curChapter = GetCurrentChapter(); int curLevel = GetCurrentLevel(); Log.Sys("curChapter chapter " + curChapter + " chapter " + chapter + " curLevel " + curLevel); if (curChapter > chapter) { allLevels = GetAllChapterLevelInfo(chapter); foreach (LevelInfo l in allLevels) { var cin = CopyInfo.CreateBuilder(); cin.IsPass = true; l.levelServer = cin.BuildPartial(); } } else if (curChapter < chapter) { allLevels = new List <LevelInfo>(); } else { allLevels = GetAllChapterLevelInfo(chapter); foreach (LevelInfo l in allLevels) { if (l.CopyId < curLevel) { var cin = CopyInfo.CreateBuilder(); cin.IsPass = true; l.levelServer = cin.BuildPartial(); } else { var cin = CopyInfo.CreateBuilder(); cin.IsPass = false; l.levelServer = cin.BuildPartial(); } } } return(allLevels); }
public static CopyInfo GetCopyInfo(string copyName) { CopyInfo copyInfo = null; copyInfos.TryGetValue(copyName, out copyInfo); if (copyInfo == null) { string name = copyName.ToLower(); XmlNodeList xmlnode = GetXML(name); if (xmlnode != null) { ParseCopyInfo(copyName, xmlnode); copyInfos.TryGetValue(copyName, out copyInfo); } } return(copyInfo); }
void ChangeCopyNum(uint copyType, stNumCopyUserCmd_S cmd) { if (m_dicCopyInfo.ContainsKey(copyType)) { CopyInfo info = m_dicCopyInfo[copyType]; info.CopyUseNum = cmd.copy_num; info.MaxCopyNum = cmd.max_copy_num; } else { CopyInfo info = new CopyInfo(); info.CopyType = copyType; info.CopyUseNum = cmd.copy_num; info.MaxCopyNum = cmd.max_copy_num; AddCopyInfo(copyType, info); } }
public void Show(CopyInfo copyInfo, SceneInfo sceneInfo) { if (container) { container.gameObject.SetActive(true); } mapNameText.text = copyInfo.Name; mapResText.text = copyInfo.ResName; thingsListView.Clear(); things.Clear(); GameObjectInfo gameObjectInfo = null; for (int i = 0; i < sceneInfo.AllGameObjectInfos.Count; ++i) { gameObjectInfo = sceneInfo.AllGameObjectInfos[i]; if (gameObjectInfo.Type != GameObjectTypes.Effect) { things.Add(gameObjectInfo.myIndex + ":" + gameObjectInfo.PrefabName); } } gameObjectInfo = sceneInfo.TerrainInfo; things.Add(gameObjectInfo.myIndex + ":" + gameObjectInfo.PrefabName); thingsListView.DataSource = things; effectsListView.Clear(); effects.Clear(); for (int i = 0; i < sceneInfo.Effects.Count; ++i) { gameObjectInfo = sceneInfo.Effects[i]; effects.Add(gameObjectInfo.myIndex + ":" + gameObjectInfo.PrefabName); } effectsListView.DataSource = effects; npcListView.Clear(); NpcInfo npcInfo = null; for (int i = 0; i < copyInfo.NPCList.Count; ++i) { npcInfo = copyInfo.NPCList[i]; // npcs.Add(); } }
public void InitNewPlayerInfo() { playerInfo = PlayerInfo.CreateBuilder(); playerInfo.Exp = 0; playerInfo.Gold = 0; var role = RolesInfo.CreateBuilder(); role.Name = "test"; role.PlayerId = 100; role.Level = 1; role.Job = Job.WARRIOR; playerInfo.Roles = role.Build(); var cinfo = GCCopyInfo.CreateBuilder(); var cin = CopyInfo.CreateBuilder(); cin.Id = 209; cin.IsPass = true; cinfo.AddCopyInfo(cin); playerInfo.CopyInfos = cinfo.Build(); WindowMng.windowMng.ShowNotifyLog("初始化新的数据"); }
public void OnCompeleteCopy(stCompleteCopyUserCmd_S cmd) { m_uCopyCountDown = cmd.close_time; m_uCopyFinishCountDown = cmd.close_time; CopyDataBase cdb = GameTableManager.Instance.GetTableItem <CopyDataBase>(m_uEnterCopyID); if (cdb != null) { if (cdb.IsShowFinish) { UIPanelManager upMger = DataManager.Manager <UIPanelManager>(); upMger.ShowPanel(PanelID.FBResult); TimerAxis.Instance().SetTimer(m_uCopyFinishTimerID, 1000, this, cmd.close_time); //延迟两秒显示副本奖励 CoroutineMgr.Instance.DelayInvokeMethod(2f, () => { if (upMger.IsShowPanel(PanelID.FBResult)) { upMger.HidePanel(PanelID.FBResult); } if (cdb.havePassReward != 0 && !string.IsNullOrEmpty(cdb.rewardList)) { string[] rewardListStr = cdb.rewardList.Split(new char[] { ';' }); List <CommonAwardData> cmADDAtas = null; CommonAwardData tempcmAD = null; string[] tempRewardArray = null; uint tempItemID = 0; uint tempNum = 0; if (null != rewardListStr && rewardListStr.Length > 0) { for (int i = 0, max = rewardListStr.Length; i < max; i++) { if (string.IsNullOrEmpty(rewardListStr[i])) { continue; } tempRewardArray = rewardListStr[i].Split(new char[] { '_' }); if (null == tempRewardArray || tempRewardArray.Length != 2) { continue; } if (!string.IsNullOrEmpty(tempRewardArray[0]) && uint.TryParse(tempRewardArray[0].Trim(), out tempItemID) && !string.IsNullOrEmpty(tempRewardArray[1]) && uint.TryParse(tempRewardArray[1].Trim(), out tempNum) ) { tempcmAD = new CommonAwardData(tempItemID, tempNum); if (null == cmADDAtas) { cmADDAtas = new List <CommonAwardData>(); } CopyInfo info = GetCopyInfoById(m_uEnterCopyID); if (!info.IsFinished) { cmADDAtas.Add(tempcmAD); } } } //超过收益次数 还是显示奖励界面但是没有奖励道具 if (null != cmADDAtas) { upMger.ShowPanel(PanelID.FBPassAwardPanel, data: cmADDAtas); } } } }); } } }
/// <summary> /// Copy the <paramref name="sourceThing"/> into the target <paramref name="partition"/> /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="partition">The current partition</param> /// <param name="sourceThing">The source <see cref="Thing"/> to copy</param> /// <param name="targetContainer">The target container <see cref="Thing"/></param> /// <param name="allSourceThings">All source <see cref="Thing"/>s in the current copy operation</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="sourceToCopyMap">A dictionary mapping identifiers of original to copy</param> /// <param name="rdls">The <see cref="ReferenceDataLibrary"/></param> /// <param name="targetEngineeringModelSetup">The target <see cref="EngineeringModelSetup"/></param> /// <param name="securityContext">The <see cref="ISecurityContext"/></param> public virtual void Copy(NpgsqlTransaction transaction, string partition, Thing sourceThing, Thing targetContainer, IReadOnlyList <Thing> allSourceThings, CopyInfo copyinfo, Dictionary <Guid, Guid> sourceToCopyMap, IReadOnlyList <ReferenceDataLibrary> rdls, EngineeringModelSetup targetEngineeringModelSetup, ISecurityContext securityContext) { }
static void CollectionCopy(CopyInfo item) { SharedMethods.CopyCollection(item.SourceDatabase, item.TargetDatabase, item.SourceCollection, item.TargetCollection, item.BatchSize, item.CopyIndexes, item.DropCollections, item.SkipCount, item.EraseObjectId, item.Options); }
/// <summary> /// Copy the <paramref name="sourceThing"/> into the target <paramref name="partition"/> /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="partition">The current partition</param> /// <param name="sourceThing">The source <see cref="Thing"/> to copy</param> /// <param name="targetContainer">The target container <see cref="Thing"/></param> /// <param name="allSourceThings">All source <see cref="Thing"/>s in the current copy operation</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="sourceToCopyMap">A dictionary mapping identifiers of original to copy</param> /// <param name="rdls">The <see cref="ReferenceDataLibrary"/></param> /// <param name="targetEngineeringModelSetup"></param> /// <param name="securityContext">The <see cref="ISecurityContext"/></param> public override void Copy(NpgsqlTransaction transaction, string partition, Thing sourceThing, Thing targetContainer, IReadOnlyList <Thing> allSourceThings, CopyInfo copyinfo, Dictionary <Guid, Guid> sourceToCopyMap, IReadOnlyList <ReferenceDataLibrary> rdls, EngineeringModelSetup targetEngineeringModelSetup, ISecurityContext securityContext) { if (!(sourceThing is ElementUsage sourceElementUsage)) { throw new InvalidOperationException("The source is not of the right type"); } var copy = sourceElementUsage.DeepClone <ElementUsage>(); copy.Iid = sourceToCopyMap[sourceElementUsage.Iid]; // check reference data validity in target iteration if models are different if (copyinfo.Source.TopContainer.Iid != copyinfo.Target.TopContainer.Iid) { var possibleCats = rdls.SelectMany(x => x.DefinedCategory).ToList(); var ignoredCategories = copy.Category.Except(possibleCats).ToList(); foreach (var ignoredCategory in ignoredCategories) { copy.Category.Remove(ignoredCategory); } } if (copyinfo.Options.KeepOwner.HasValue && (!copyinfo.Options.KeepOwner.Value || copyinfo.Options.KeepOwner.Value && !targetEngineeringModelSetup.ActiveDomain.Contains(copy.Owner) ) ) { copy.Owner = copyinfo.ActiveOwner; } if (copyinfo.Source.IterationId.Value != copyinfo.Target.IterationId.Value) { // change definition reference if different iteration copy.ElementDefinition = sourceToCopyMap[sourceElementUsage.ElementDefinition]; } if (!this.OperationSideEffectProcessor.BeforeCreate(copy, targetContainer, transaction, partition, securityContext)) { return; } this.ElementUsageDao.Write(transaction, partition, copy, targetContainer); this.OperationSideEffectProcessor.AfterCreate(copy, targetContainer, null, transaction, partition, securityContext); foreach (var parameterOverride in allSourceThings.Where(x => sourceElementUsage.ParameterOverride.Contains(x.Iid))) { ((ServiceBase)this.ParameterOverrideService).Copy(transaction, partition, parameterOverride, copy, allSourceThings, copyinfo, sourceToCopyMap, rdls, targetEngineeringModelSetup, securityContext); } }
/// <summary> /// Gets the source data for the copy operation /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="requestPartition">The contextual partition</param> /// <returns>The source data</returns> public IReadOnlyList <Thing> GetCopySourceData(NpgsqlTransaction transaction, CopyInfo copyinfo, string requestPartition) { if (copyinfo.Source.IterationId.HasValue && copyinfo.Source.IterationId.Value != Guid.Empty) { var topcontainerPartition = $"EngineeringModel_{copyinfo.Source.TopContainer.Iid.ToString().Replace("-", "_")}"; this.TransactionManager.SetIterationContext(transaction, topcontainerPartition, copyinfo.Source.IterationId.Value); } // transaction shall be contextual to source iteration if applicable (get new transaction) var partition = copyinfo.Source.IterationId.HasValue && copyinfo.Source.IterationId.Value != Guid.Empty ? $"Iteration_{copyinfo.Source.TopContainer.Iid.ToString().Replace("-", "_")}" : $"EngineeringModel_{copyinfo.Source.TopContainer.Iid.ToString().Replace("-", "_")}"; var readservice = this.ServiceProvider.MapToReadService(copyinfo.Source.Thing.ClassKind.ToString()); var securityContext = new RequestSecurityContext { ContainerReadAllowed = true, ContainerWriteAllowed = true }; var sourceThings = copyinfo.Options.CopyKind == CopyKind.Deep ? readservice.GetDeep(transaction, partition, new[] { copyinfo.Source.Thing.Iid }, securityContext) : readservice.GetShallow(transaction, partition, new[] { copyinfo.Source.Thing.Iid }, securityContext); var source = sourceThings.ToList(); // also get all referenced element-definition as they dont exist in target iteration if (copyinfo.Source.IterationId.Value != copyinfo.Target.IterationId.Value) { source.AddRange(this.GetElementDefinitionTreeFromRootDefinition(transaction, partition, securityContext, source, readservice, source.Select(x => x.Iid).ToList())); } // revert context to current this.TransactionManager.SetIterationContext(transaction, requestPartition, copyinfo.Target.IterationId.Value); return(source); }
void handleMsg(KBEngine.Packet packet) { var receivePkg = packet.protoBody.GetType().FullName; Debug.Log("Server Receive " + receivePkg); var className = receivePkg.Split(char.Parse(".")) [1]; IBuilderLite retPb = null; uint flowId = packet.flowId; bool findHandler = false; if (className == "CGAutoRegisterAccount") { var au = GCAutoRegisterAccount.CreateBuilder(); au.Username = "******"; retPb = au; } else if (className == "CGRegisterAccount") { var au = GCRegisterAccount.CreateBuilder(); retPb = au; } else if (className == "CGLoginAccount") { var au = GCLoginAccount.CreateBuilder(); var playerInfo = ServerData.Instance.playerInfo; if (playerInfo.HasRoles) { var role = RolesInfo.CreateBuilder().MergeFrom(playerInfo.Roles); au.AddRolesInfos(role); } retPb = au; } else if (className == "CGSelectCharacter") { var inpb = packet.protoBody as CGSelectCharacter; if (inpb.PlayerId == 101) { selectPlayerJob = 4; } else if (inpb.PlayerId == 102) { selectPlayerJob = 2; } else { selectPlayerJob = 1; } var au = GCSelectCharacter.CreateBuilder(); au.TokenId = "12345"; retPb = au; } else if (className == "CGBindingSession") { var au = GCBindingSession.CreateBuilder(); au.X = 22; au.Y = 1; au.Z = 17; au.Direction = 10; au.MapId = 0; au.DungeonBaseId = 0; au.DungeonId = 0; retPb = au; } else if (className == "CGEnterScene") { var inpb = packet.protoBody as CGEnterScene; var au = GCEnterScene.CreateBuilder(); au.Id = inpb.Id; retPb = au; } else if (className == "CGListBranchinges") { var au = GCListBranchinges.CreateBuilder(); var bran = Branching.CreateBuilder(); bran.Line = 1; bran.PlayerCount = 2; au.AddBranching(bran); retPb = au; } else if (className == "CGHeartBeat") { } else if (className == "CGLoadSaleItems") { var au = GCLoadSaleItems.CreateBuilder(); retPb = au; } else if (className == "CGListAllTeams") { var au = GCListAllTeams.CreateBuilder(); retPb = au; } else if (className == "CGCopyInfo") { var pinfo = ServerData.Instance.playerInfo; if (pinfo.HasCopyInfos) { retPb = GCCopyInfo.CreateBuilder().MergeFrom(pinfo.CopyInfos); } else { //First Fetch Login Info var au = GCCopyInfo.CreateBuilder(); var cin = CopyInfo.CreateBuilder(); cin.Id = 101; cin.IsPass = false; au.AddCopyInfo(cin); var msg = au.Build(); pinfo.CopyInfos = msg; retPb = GCCopyInfo.CreateBuilder().MergeFrom(msg); } } else if (className == "CGLoadVipLevelGiftReceiveInfo") { var au = GCLoadVipLevelGiftReceiveInfo.CreateBuilder(); var vip = ReceviedReward.CreateBuilder(); vip.RewardId = 1; au.AddReceviedLevelRewards(vip); vip = ReceviedReward.CreateBuilder(); vip.RewardId = 2; au.AddReceviedLevelRewards(vip); vip = ReceviedReward.CreateBuilder(); vip.RewardId = 3; au.AddReceviedLevelRewards(vip); retPb = au; } else if (className == "CGLoadVipInfo") { var au = GCLoadVipInfo.CreateBuilder(); au.VipType = VipType.NONE_VIP; au.VipRemainTime = 0; au.VipLevel = 4; au.VipExp = 0; retPb = au; } else if (className == "CGLoadTaskList") { var au = GCLoadTaskList.CreateBuilder(); var task = PlayerTask.CreateBuilder(); task.TaskId = 1; task.PlayerTaskId = 1; task.PlayerId = 2; task.TaskState = 5; task.Chain = 6; au.AddPlayerTask(task); task = PlayerTask.CreateBuilder(); task.TaskId = 2; task.PlayerTaskId = 1; task.PlayerId = 2; task.TaskState = 5; task.Chain = 6; au.AddPlayerTask(task); task = PlayerTask.CreateBuilder(); task.TaskId = 3; task.PlayerTaskId = 1; task.PlayerId = 2; task.TaskState = 5; task.Chain = 6; au.AddPlayerTask(task); retPb = au; } else if (className == "CGLoadAchievements") { var au = GCLoadAchievements.CreateBuilder(); var ac = Achievement.CreateBuilder(); ac.AchievementId = 1000; au.AddAchievements(ac); ac = Achievement.CreateBuilder(); ac.AchievementId = 1001; au.AddAchievements(ac); ac = Achievement.CreateBuilder(); ac.AchievementId = 1002; au.AddAchievements(ac); ac = Achievement.CreateBuilder(); ac.AchievementId = 1003; au.AddAchievements(ac); ac = Achievement.CreateBuilder(); ac.AchievementId = 1004; au.AddAchievements(ac); retPb = au; } else if (className == "CGAuctionInfo") { var au = GCAuctionInfo.CreateBuilder(); au.MaxSize = 1; au.PageSize = 6; var item = AuctionItem.CreateBuilder(); item.Id = 11; item.BaseId = 14; item.Type = 1; item.SellCount = 2; item.RemainTime = 60; item.TotalCost = 88; au.AddAuctionItems(item); item = AuctionItem.CreateBuilder(); item.Id = 119; item.BaseId = 15; item.Type = 1; item.SellCount = 2; item.RemainTime = 609; item.TotalCost = 889; au.AddAuctionItems(item); item = AuctionItem.CreateBuilder(); item.Id = 118; item.BaseId = 16; item.Type = 1; item.SellCount = 2; item.RemainTime = 608; item.TotalCost = 888; au.AddAuctionItems(item); item = AuctionItem.CreateBuilder(); item.Id = 117; item.BaseId = 23; item.Type = 1; item.SellCount = 2; item.RemainTime = 607; item.TotalCost = 887; au.AddAuctionItems(item); item = AuctionItem.CreateBuilder(); item.Id = 116; item.BaseId = 24; item.Type = 1; item.SellCount = 2; item.RemainTime = 605; item.TotalCost = 886; au.AddAuctionItems(item); item = AuctionItem.CreateBuilder(); item.Id = 115; item.BaseId = 25; item.Type = 1; item.SellCount = 2; item.RemainTime = 605; item.TotalCost = 88; au.AddAuctionItems(item); retPb = au; } else if (className == "CGUserDressEquip") { PlayerData.UserDressEquip(packet); findHandler = true; } else if (className == "CGAutoRegisterAccount") { var au = GCAutoRegisterAccount.CreateBuilder(); au.Username = "******" + random.Next(); retPb = au; } else if (className == "CGRegisterAccount") { var inpb = packet.protoBody as CGRegisterAccount; ServerData.Instance.playerInfo.Username = inpb.Username; var au = GCRegisterAccount.CreateBuilder(); retPb = au; } else if (className == "CGPlayerMove") { var au = GCPlayerMove.CreateBuilder(); retPb = au; } else { var fullName = packet.protoBody.GetType().FullName; var handlerName = fullName.Replace("ChuMeng", "ServerPacketHandler"); var tp = Type.GetType(handlerName); if (tp == null) { if (ServerPacketHandler.HoldCode.staticTypeMap.ContainsKey(handlerName)) { tp = ServerPacketHandler.HoldCode.staticTypeMap [handlerName]; } } if (tp == null) { Debug.LogError("PushMessage noHandler " + handlerName); } else { findHandler = true; var ph = (ServerPacketHandler.IPacketHandler)Activator.CreateInstance(tp); ph.HandlePacket(packet); } } if (retPb != null) { SendPacket(retPb, flowId); } else { if (className != "CGHeartBeat" && !findHandler) { Debug.LogError("DemoServer::not Handle Message " + className); } } }
/// <summary> /// Copy the <paramref name="sourceThing"/> into the target <paramref name="partition"/> /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="partition">The current partition</param> /// <param name="sourceThing">The source <see cref="Thing"/> to copy</param> /// <param name="targetContainer">The target container <see cref="Thing"/></param> /// <param name="allSourceThings">All source <see cref="Thing"/>s in the current copy operation</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="sourceToCopyMap">A dictionary mapping identifiers of original to copy</param> /// <param name="rdls">The <see cref="ReferenceDataLibrary"/></param> /// <param name="targetEngineeringModelSetup"></param> /// <param name="securityContext">The <see cref="ISecurityContext"/></param> public override void Copy(NpgsqlTransaction transaction, string partition, Thing sourceThing, Thing targetContainer, IReadOnlyList <Thing> allSourceThings, CopyInfo copyinfo, Dictionary <Guid, Guid> sourceToCopyMap, IReadOnlyList <ReferenceDataLibrary> rdls, EngineeringModelSetup targetEngineeringModelSetup, ISecurityContext securityContext) { if (!(sourceThing is ParameterSubscription sourceSubscription)) { throw new InvalidOperationException("The source is not of the right type"); } var copy = sourceSubscription.DeepClone <ParameterSubscription>(); copy.Iid = sourceToCopyMap[sourceSubscription.Iid]; if (!this.OperationSideEffectProcessor.BeforeCreate(copy, targetContainer, transaction, partition, securityContext)) { return; } this.ParameterSubscriptionDao.Write(transaction, partition, copy, targetContainer); this.OperationSideEffectProcessor.AfterCreate(copy, targetContainer, null, transaction, partition, securityContext); var newparameterSubscription = this.ParameterSubscriptionDao.Read(transaction, partition, new[] { copy.Iid }).Single(); if (copyinfo.Options.KeepValues.HasValue && copyinfo.Options.KeepValues.Value) { var valuesets = this.ParameterSubscriptionValueSetService .GetShallow(transaction, partition, newparameterSubscription.ValueSet, securityContext) .OfType <ParameterSubscriptionValueSet>().ToList(); // update all value-set foreach (var valueset in valuesets) { var sourceToCopySubscribedValueSetPair = sourceToCopyMap.SingleOrDefault(x => x.Value == valueset.SubscribedValueSet); var sourceSubscriptionValueSet = allSourceThings.OfType <ParameterSubscriptionValueSet>() .FirstOrDefault(x => x.SubscribedValueSet == sourceToCopySubscribedValueSetPair.Key && sourceSubscription.ValueSet.Contains(x.Iid)); if (sourceSubscriptionValueSet == null) { continue; } sourceToCopyMap[sourceSubscriptionValueSet.Iid] = valueset.Iid; valueset.Manual = sourceSubscriptionValueSet.Manual; valueset.ValueSwitch = sourceSubscriptionValueSet.ValueSwitch; this.ParameterSubscriptionValueSetService.UpdateConcept(transaction, partition, valueset, copy); } } }
public static bool Download(HathUri Uri, CopyInfo CInfo = null) { SHA1Managed Hasher = new SHA1Managed(); string hash = BitConverter.ToString(Hasher.ComputeHash(Encoding.ASCII.GetBytes(Uri.FileName))).Replace("-", "").ToLower(); string fileDir = string.Format("{0}{1}/{2}/", Settings.Cache, hash.Substring(0, 1), hash.Substring(1, 1)); try { Directory.CreateDirectory(Path.GetDirectoryName(fileDir + Uri.FileName)); using (WebClient client = new WebClient()) { using (Stream streamRemote = client.OpenRead(new Uri(Uri.Url))) { int contentSize = 0; byte[] byteBuffer; int rec = 0; int iByteSize = 0; if (client.ResponseHeaders.Get("Content-Length") == "1009,1009" || client.ResponseHeaders.Get("Content-Length") == "28658,28658") { contentSize = 1009; } else { try { contentSize = int.Parse(client.ResponseHeaders.Get("Content-Length")); } catch { Log.Add("Server sent corrupt Content-Length header... " + client.BaseAddress, LogType.Warning, true); return(false); } } if (contentSize >= 0 && (contentSize != 28658 && contentSize != 1009)) { byteBuffer = new byte[contentSize]; } else { if (contentSize == 28658 || contentSize == 1009) { if (HHClient.Request(Settings.MoreFiles, "", true)) { Log.Add("Requested more files.", LogType.Info, true); if (Download(Uri)) { return(true); } } } return(false); } try { while ((iByteSize = streamRemote.Read(byteBuffer, rec, byteBuffer.Length - rec)) > 0) { rec += iByteSize; MainStats.TriggerByteDownload(iByteSize); } } catch { return(false); } using (Stream streamLocal = new FileStream(fileDir + Uri.FileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Write)) { streamLocal.Write(byteBuffer, 0, byteBuffer.Length); streamLocal.Close(); } streamRemote.Close(); if (CInfo != null) { File.Copy(fileDir + Uri.FileName, CInfo.Location + CInfo.FileName); } if (Settings.CopyDlToGalleries) { HathDownloader.CopyIsMissing(fileDir + Uri.FileName, Uri.FileName); } SqlManager.InsertFile(new FileData(Uri.FileName, contentSize)); MainStats.TriggerFileDownload(Uri.FileName, contentSize); if (Uri.UriType == HathUriType.Proxy || Uri.UriType == HathUriType.HathDl) { PendingRegister.AddFile(Uri.FileName); } } } return(true); } catch { return(false); } }
/// <summary> /// Creates a marc file for the given Assembly within the given output path. /// </summary> /// <param name="csprojFile">Path of the 'csproj' file</param> /// <param name="assemblyFile">Path of the assembly file</param> /// <param name="outputPath">Target output path of the pack</param> public FileInfo PackMarc(string csprojFile, string assemblyFile, string outputPath) { // Assertions if (!new FileInfo(csprojFile).Exists) { throw new NullReferenceException(string.Format("csproj file '{0}' does not exist!", csprojFile)); } if (!new FileInfo(assemblyFile).Exists) { throw new NullReferenceException(string.Format("Assembly file '{0}' does not exist!", assemblyFile)); } // Resolve the Assembly, Meta-Inf and build properties files FileInfo assemblyFileInfo = new FileInfo(assemblyFile); FileInfo[] metaInfFiles = ResolveMetaInfFiles(csprojFile); CopyInfo[] buildPropDefinedFiles = ResolveBuildPropertiesFiles(csprojFile); // Resolve the output path and file info string assemblyBaseName = Path.GetFileNameWithoutExtension(assemblyFile); string assemblyFilePath = assemblyFileInfo.FullName; string absoluteOutputPath = string.Format(AbsoluteOutputPathFormat, outputPath, assemblyBaseName); FileInfo marcFileInfo = new FileInfo(absoluteOutputPath); DirectoryInfo marcDirectoryInfo = marcFileInfo.Directory; if (marcDirectoryInfo == null) { throw new NullReferenceException(string.Format("DirectoryInfo is null for '{0}'", absoluteOutputPath)); } // If the ouput path does not exists, create it if (!marcDirectoryInfo.Exists) { marcDirectoryInfo.Create(); } // Zip the contents using (FileStream fileStream = File.Create(absoluteOutputPath)) { using (ZipOutputStream zipStream = new ZipOutputStream(fileStream)) { // Processing the meta inf files for (int i = -1; ++i < metaInfFiles.Length;) { FileInfo file = metaInfFiles[i]; AddToZipStream(zipStream, file, file.Name); } // Processing the build properties files for (int i = -1; ++i < buildPropDefinedFiles.Length;) { CopyInfo cpyInfo = buildPropDefinedFiles[i]; string srcPath = cpyInfo.Source; string tgtPath = cpyInfo.Target; AddToZipStream(zipStream, srcPath, tgtPath + "/" + Path.GetFileName(srcPath)); } // Copy the assembly file AddToZipStream(zipStream, assemblyFilePath, Path.GetFileName(assemblyFilePath)); } } return(marcFileInfo); }
/// <summary> /// Returns a CopyInfo for all files that have to be packed through the definition of /// the 'build.properties' file. /// </summary> /// <param name="csprojFile">Path of a 'csproj' file</param> /// <returns>Array of CopyInfo</returns> private CopyInfo[] ResolveBuildPropertiesFiles(string csprojFile) { if (!HasBuildProperties(csprojFile, out FileInfo buildPropFile)) { return(new CopyInfo[0]); } string dirPath = Path.GetDirectoryName(csprojFile); if (string.IsNullOrEmpty(dirPath)) { throw new NullReferenceException("Directory path is null"); } ICollection <CopyInfo> cpyInfos = new LinkedList <CopyInfo>(); IPlainTextDocument document = new PropertiesDocumentParser(buildPropFile).Parse(); IDictionary <string, string> referencesTable = GetReferencesTable(csprojFile); // Processing includes string[] inclDef = document.SelectValues("include") ?? new string[0]; for (int i = -1; ++i < inclDef.Length;) { string include = inclDef[i]; const string includeTarget = "includes"; // Name of the folder within the marc // Wildcard? int wildCardIndex = include.IndexOf(WildcardDefinition); if (wildCardIndex != -1) { string includeFolderName = include.Substring(0, wildCardIndex); string subDirPath = string.Format("{0}\\{1}", dirPath, includeFolderName); DirectoryInfo subDirInfo = new DirectoryInfo(subDirPath); if (!subDirInfo.Exists) { throw new NullReferenceException(string.Format("The directory '{0}' does not exist!", subDirPath)); } FileInfo[] subDirFiles = subDirInfo.GetFiles(); for (int j = -1; ++j < subDirFiles.Length;) { FileInfo file = subDirFiles[j]; CopyInfo cpyInf = new CopyInfo(file.FullName, includeTarget); cpyInfos.Add(cpyInf); } } else { // TODO Support non-wildcard } } // Processing add string[] addDefs = document.SelectValues("add") ?? new string[0]; for (int i = -1; ++i != addDefs.Length;) { string add = addDefs[i]; // Wildcard usage? int wildcardIndex = add.IndexOf("*"); // Handle wildcard if (wildcardIndex != -1) { string prefix = add.Substring(0, wildcardIndex); IEnumerable <KeyValuePair <string, string> > matchingEntries = referencesTable.Where(entry => entry.Key.StartsWith(prefix)); using (IEnumerator <KeyValuePair <string, string> > itr = matchingEntries.GetEnumerator()) { while (itr.MoveNext()) { KeyValuePair <string, string> entry = itr.Current; string assemblyPath = entry.Value; AddToCopyList(assemblyPath, cpyInfos); } } continue; } // Relative path? if (add.StartsWith("./")) { // TODO Add support of relative paths continue; } // Absolute path? if (File.Exists(add)) { // TODO Add support of absolute paths continue; } // Simple reference string referenceItem = referencesTable.FirstOrDefault(entry => entry.Key == add).Value; AddToCopyList(referenceItem, cpyInfos); } return(cpyInfos.ToArray()); }
/// <summary> /// Copy the <paramref name="sourceThing"/> into the target <paramref name="partition"/> /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="partition">The current partition</param> /// <param name="sourceThing">The source <see cref="Thing"/> to copy</param> /// <param name="targetContainer">The target container <see cref="Thing"/></param> /// <param name="allSourceThings">All source <see cref="Thing"/>s in the current copy operation</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="sourceToCopyMap">A dictionary mapping identifiers of original to copy</param> /// <param name="rdls">The <see cref="ReferenceDataLibrary"/></param> /// <param name="targetEngineeringModelSetup"></param> /// <param name="securityContext">The <see cref="ISecurityContext"/></param> public override void Copy(NpgsqlTransaction transaction, string partition, Thing sourceThing, Thing targetContainer, IReadOnlyList <Thing> allSourceThings, CopyInfo copyinfo, Dictionary <Guid, Guid> sourceToCopyMap, IReadOnlyList <ReferenceDataLibrary> rdls, EngineeringModelSetup targetEngineeringModelSetup, ISecurityContext securityContext) { if (!(sourceThing is Parameter sourceParameter)) { throw new InvalidOperationException("The source is not of the right type"); } var copy = sourceParameter.DeepClone <Parameter>(); copy.Iid = sourceToCopyMap[sourceParameter.Iid]; if (copy.Group.HasValue) { copy.Group = sourceToCopyMap[copy.Group.Value]; } // if source and target iteration are different, remove state dependency. Keep option dependency if (copyinfo.Source.IterationId.Value != copyinfo.Target.IterationId.Value) { copy.StateDependence = null; } // check parameter type validity if different top-container if (copyinfo.Source.TopContainer.Iid != copyinfo.Target.TopContainer.Iid && !rdls.SelectMany(x => x.ParameterType).Contains(copy.ParameterType)) { throw new InvalidOperationException($"Cannot copy {copy.ClassKind} with parameter-type id {copy.ParameterType}. The parameter-type is unavailable in the targetted model."); } if (copyinfo.Options.KeepOwner.HasValue && (!copyinfo.Options.KeepOwner.Value || copyinfo.Options.KeepOwner.Value && !targetEngineeringModelSetup.ActiveDomain.Contains(copy.Owner) ) ) { copy.Owner = copyinfo.ActiveOwner; } if (!this.OperationSideEffectProcessor.BeforeCreate(copy, targetContainer, transaction, partition, securityContext)) { return; } this.ParameterDao.Write(transaction, partition, copy, targetContainer); this.OperationSideEffectProcessor.AfterCreate(copy, targetContainer, null, transaction, partition, securityContext); var newparameter = this.ParameterDao.Read(transaction, partition, new[] { copy.Iid }).Single(); if (copyinfo.Options.KeepValues.HasValue && copyinfo.Options.KeepValues.Value) { var valuesets = this.ValueSetService .GetShallow(transaction, partition, newparameter.ValueSet, securityContext) .OfType <ParameterValueSet>().ToList(); var topcontainerPartition = $"EngineeringModel_{copyinfo.Source.TopContainer.Iid.ToString().Replace("-", "_")}"; this.TransactionManager.SetIterationContext(transaction, topcontainerPartition, copyinfo.Source.IterationId.Value); var sourcepartition = $"Iteration_{copyinfo.Source.TopContainer.Iid.ToString().Replace("-", "_")}"; var iteration = (Iteration)this.IterationService.Get(transaction, topcontainerPartition, new Guid[] { copyinfo.Source.IterationId.Value }, securityContext).SingleOrDefault(); if (iteration == null) { throw new InvalidOperationException($"The source iteration {copyinfo.Source.IterationId.Value} could not be found."); } this.OldParameterContextProvider.Initialize(sourceParameter, transaction, sourcepartition, securityContext, iteration); // switch back to request context var engineeringModelPartition = partition.Replace("Iteration", "EngineeringModel"); this.TransactionManager.SetIterationContext(transaction, engineeringModelPartition, copyinfo.Target.IterationId.Value); // update all value-set this.DefaultValueArrayFactory.Load(transaction, securityContext); foreach (var valueset in valuesets) { var sourceValueset = this.OldParameterContextProvider.GetsourceValueSet(valueset.ActualOption, valueset.ActualState) ?? this.OldParameterContextProvider.GetDefaultValue(); if (sourceValueset == null) { Logger.Warn("No source value-set was found for the copy operation."); continue; } sourceToCopyMap[sourceValueset.Iid] = valueset.Iid; valueset.Manual = sourceValueset.Manual; valueset.Computed = sourceValueset.Computed; valueset.Reference = sourceValueset.Reference; valueset.ValueSwitch = sourceValueset.ValueSwitch; valueset.Formula = this.DefaultValueArrayFactory.CreateDefaultValueArray(newparameter.ParameterType); valueset.Published = this.DefaultValueArrayFactory.CreateDefaultValueArray(newparameter.ParameterType); this.ValueSetService.UpdateConcept(transaction, partition, valueset, copy); } } var sourceSubscriptions = allSourceThings.OfType <ParameterSubscription>().Where(x => sourceParameter.ParameterSubscription.Contains(x.Iid)).ToList(); foreach (var sourceSubscription in sourceSubscriptions) { if (sourceSubscription.Owner == newparameter.Owner) { // do not create subscriptions continue; } ((ServiceBase)this.ParameterSubscriptionService).Copy(transaction, partition, sourceSubscription, newparameter, allSourceThings, copyinfo, sourceToCopyMap, rdls, targetEngineeringModelSetup, securityContext); } }
private static void RunInit() { var manifest = new Manifest(); Console.WriteLine(); Console.WriteLine("SimpleWix Init | Let's generate a manifest file!"); Console.Write("Project Name: "); var name = Console.ReadLine(); if (name.IsNullOrWhitespace()) { throw new Exception("Must provide a project name."); } manifest.appname = name; Console.Write("Version: [0.0.1.0] "); var version = Console.ReadLine(); if (version.IsNullOrWhitespace()) { version = "0.0.1.0"; Console.Write(version); Console.WriteLine(); } manifest.version = version; Console.Write("Manufacturer: [] "); var manufacturer = Console.ReadLine(); if (manufacturer.IsNullOrWhitespace()) { manufacturer = ""; Console.Write(manufacturer); Console.WriteLine(); } manifest.manufacturer = version; var outputfilepath = Path.Combine(SimpleWix.CurrentFolder, "manifest.json"); Console.Write("Manifest Filepath: [" + outputfilepath + "] "); var userPath = Console.ReadLine(); if (!userPath.IsNullOrWhitespace()) { outputfilepath = userPath; Console.Write(outputfilepath); Console.WriteLine(); } manifest.upgradecode = Guid.NewGuid().ToString(); manifest.complete = true; manifest.quietmode = false; Console.Write("Would you like to setup your source files now: [(y)/n] "); var features = new List <Feature>(); var res = Console.ReadLine(); if (res.IsNullOrWhitespace()) { res = "y"; } if (res?.ToLower().Contains("y") ?? false) { for (int i = 0; i < 1000; i++) { var feat = new Feature(); Console.Write("Feature Name: [default] "); res = Console.ReadLine(); if (res.IsNullOrWhitespace()) { res = "default"; } feat.title = res; Console.Write("Feature Description: [Default installation package.] "); res = Console.ReadLine(); if (res.IsNullOrWhitespace()) { res = "Default installation package."; } feat.description = res; for (int j = 0; j < 1000; j++) { var copyinfo = new CopyInfo(); Console.Write("Source Path: [] "); res = @"" + Console.ReadLine(); if (res.IsNullOrWhitespace()) { Console.Write("Must provide source"); continue; } copyinfo.source = res; Console.Write("Include sub folders?: [y/(n)] "); res = Console.ReadLine(); if (res.IsNullOrWhitespace()) { res = "n"; } copyinfo.includesubfolders = res?.ToLower().Contains("y") ?? false; Console.Write("Destination Path: [] "); res = @"" + Console.ReadLine(); if (res.IsNullOrWhitespace()) { Console.Write("Must provide destination"); continue; } copyinfo.destination = res; feat.copyinfo.Add(copyinfo); Console.Write("Would you like to add another source to the " + feat.title + " feature?: [y/(n)] "); res = Console.ReadLine(); if (res.IsNullOrWhitespace()) { res = "n"; } if (!res?.ToLower().Contains("y") ?? false) { break; } } manifest.features.Add(feat); Console.Write("Would you like to add another feature to the " + manifest.appname + " project?: [y/n] "); res = Console.ReadLine(); if (res.IsNullOrWhitespace()) { res = "n"; } if (!res?.ToLower().Contains("y") ?? false) { break; } } } if (File.Exists(outputfilepath)) { Console.Write("The manifest file already exists, would you like to overwrite? [y/n]"); bool overWrite = Console.ReadLine()?.ToLower().Contains("y") ?? false; if (!overWrite) { Console.WriteLine("Cancelled."); return; } File.Delete(outputfilepath); } //var settings = new JsonSerializerSettings(); var str = JsonConvert.SerializeObject(manifest, Formatting.Indented); // File.Create(outputfilepath); File.WriteAllText(outputfilepath, str); Console.WriteLine("Success! Manifest file saved to: " + outputfilepath); }
/// <summary> /// Copy the <paramref name="sourceThing"/> into the target <paramref name="partition"/> /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="partition">The current partition</param> /// <param name="sourceThing">The source <see cref="Thing"/> to copy</param> /// <param name="targetContainer">The target container <see cref="Thing"/></param> /// <param name="allSourceThings">All source <see cref="Thing"/>s in the current copy operation</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="sourceToCopyMap">A dictionary mapping identifiers of original to copy</param> /// <param name="rdls">The <see cref="ReferenceDataLibrary"/></param> /// <param name="targetEngineeringModelSetup">The target <see cref="EngineeringModelSetup"/></param> /// <param name="securityContext">The <see cref="ISecurityContext"/></param> public override void Copy(NpgsqlTransaction transaction, string partition, Thing sourceThing, Thing targetContainer, IReadOnlyList <Thing> allSourceThings, CopyInfo copyinfo, Dictionary <Guid, Guid> sourceToCopyMap, IReadOnlyList <ReferenceDataLibrary> rdls, EngineeringModelSetup targetEngineeringModelSetup, ISecurityContext securityContext) { if (!(sourceThing is ParameterGroup sourceParameterGroup)) { throw new InvalidOperationException("The source is not of the right type"); } var copy = sourceParameterGroup.DeepClone <ParameterGroup>(); copy.Iid = sourceToCopyMap[sourceParameterGroup.Iid]; if (copy.ContainingGroup.HasValue) { copy.ContainingGroup = sourceToCopyMap[copy.ContainingGroup.Value]; } this.ParameterGroupDao.Write(transaction, partition, copy, targetContainer); }
public static PacketDistributed CreatePacket(MessageID packetID) { PacketDistributed packet = null; switch (packetID) { case MessageID.CSLogin: { packet = new CSLogin(); } break; case MessageID.SCLoginRet: { packet = new SCLoginRet(); } break; case MessageID.CSLoginThirdPlatform: { packet = new CSLoginThirdPlatform(); } break; case MessageID.SCLoginThirdPlatformRet: { packet = new SCLoginThirdPlatformRet(); } break; case MessageID.CSThirdPlatformVerifyCharge: { packet = new CSThirdPlatformVerifyCharge(); } break; case MessageID.SCThirdPlatformVerifyCharge: { packet = new SCThirdPlatformVerifyCharge(); } break; case MessageID.CSAskUserData: { packet = new CSAskUserData(); } break; case MessageID.PBUserBaseData: { packet = new PBUserBaseData(); } break; case MessageID.PBUserBagData: { packet = new PBUserBagData(); } break; case MessageID.PBUserCopyData: { packet = new PBUserCopyData(); } break; case MessageID.SCAskUserData: { packet = new SCAskUserData(); } break; case MessageID.MissionInfo: { packet = new MissionInfo(); } break; case MessageID.CopyInfo: { packet = new CopyInfo(); } break; case MessageID.ItemInfo: { packet = new ItemInfo(); } break; case MessageID.CardInfo: { packet = new CardInfo(); } break; case MessageID.DropBag: { packet = new DropBag(); } break; case MessageID.BattleCard: { packet = new BattleCard(); } break; case MessageID.CSBattleData: { packet = new CSBattleData(); } break; case MessageID.DataBuffInfo: { packet = new DataBuffInfo(); } break; case MessageID.DataSingleAction: { packet = new DataSingleAction(); } break; case MessageID.DataAction: { packet = new DataAction(); } break; case MessageID.DataRound: { packet = new DataRound(); } break; case MessageID.DataBattle: { packet = new DataBattle(); } break; case MessageID.SCBattleData: { packet = new SCBattleData(); } break; case MessageID.CSPVPBattleData: { packet = new CSPVPBattleData(); } break; case MessageID.SCPVPBattleData: { packet = new SCPVPBattleData(); } break; case MessageID.CSChangeMember: { packet = new CSChangeMember(); } break; case MessageID.SCChangeMember: { packet = new SCChangeMember(); } break; case MessageID.CSCardCombining: { packet = new CSCardCombining(); } break; case MessageID.SCCardCombiningRet: { packet = new SCCardCombiningRet(); } break; case MessageID.CSCardEvolve: { packet = new CSCardEvolve(); } break; case MessageID.SCCardEvolveRet: { packet = new SCCardEvolveRet(); } break; case MessageID.CSCardStrengthen: { packet = new CSCardStrengthen(); } break; case MessageID.SCCardStrengthenRet: { packet = new SCCardStrengthenRet(); } break; case MessageID.CSFriendsList: { packet = new CSFriendsList(); } break; case MessageID.SCFriendsList: { packet = new SCFriendsList(); } break; case MessageID.CSSearchFriend: { packet = new CSSearchFriend(); } break; case MessageID.SCSearchFriend: { packet = new SCSearchFriend(); } break; case MessageID.CSGiveFriendPower: { packet = new CSGiveFriendPower(); } break; case MessageID.SCGiveFriendPower: { packet = new SCGiveFriendPower(); } break; case MessageID.CSGetFriendPower: { packet = new CSGetFriendPower(); } break; case MessageID.SCGetFriendPower: { packet = new SCGetFriendPower(); } break; case MessageID.CSADDFriend: { packet = new CSADDFriend(); } break; case MessageID.SCADDFriend: { packet = new SCADDFriend(); } break; case MessageID.CSDeleteFriend: { packet = new CSDeleteFriend(); } break; case MessageID.SCDeleteFriend: { packet = new SCDeleteFriend(); } break; case MessageID.CSGetRandomAssistanceList: { packet = new CSGetRandomAssistanceList(); } break; case MessageID.SCGetRandomAssistanceList: { packet = new SCGetRandomAssistanceList(); } break; case MessageID.PBFriend: { packet = new PBFriend(); } break; case MessageID.CSSellCard: { packet = new CSSellCard(); } break; case MessageID.SCSellCard: { packet = new SCSellCard(); } break; case MessageID.SCErrorMsg: { packet = new SCErrorMsg(); } break; case MessageID.CSMailList: { packet = new CSMailList(); } break; case MessageID.SCMailList: { packet = new SCMailList(); } break; case MessageID.PBMail: { packet = new PBMail(); } break; case MessageID.CSMailDelete: { packet = new CSMailDelete(); } break; case MessageID.SCMailDelete: { packet = new SCMailDelete(); } break; case MessageID.CSMailSend: { packet = new CSMailSend(); } break; case MessageID.SCMailSend: { packet = new SCMailSend(); } break; case MessageID.CSMailFriend: { packet = new CSMailFriend(); } break; case MessageID.SCMailFriend: { packet = new SCMailFriend(); } break; case MessageID.CSMailSystem: { packet = new CSMailSystem(); } break; case MessageID.SCMailSystem: { packet = new SCMailSystem(); } break; case MessageID.CSMailRead: { packet = new CSMailRead(); } break; case MessageID.SCMailRead: { packet = new SCMailRead(); } break; case MessageID.CSGMcmds: { packet = new CSGMcmds(); } break; case MessageID.SCGMcmds: { packet = new SCGMcmds(); } break; case MessageID.CSTaskList: { packet = new CSTaskList(); } break; case MessageID.SCTaskList: { packet = new SCTaskList(); } break; case MessageID.PBTask: { packet = new PBTask(); } break; case MessageID.CSFinishTask: { packet = new CSFinishTask(); } break; case MessageID.SCFinishTask: { packet = new SCFinishTask(); } break; case MessageID.CSShop: { packet = new CSShop(); } break; case MessageID.SCShopRet: { packet = new SCShopRet(); } break; case MessageID.CSGamble: { packet = new CSGamble(); } break; case MessageID.SCGambleRet: { packet = new SCGambleRet(); } break; case MessageID.CSGuide: { packet = new CSGuide(); } break; case MessageID.SCGuide: { packet = new SCGuide(); } break; case MessageID.ButtonInfo: { packet = new ButtonInfo(); } break; case MessageID.CSChangeName: { packet = new CSChangeName(); } break; case MessageID.SCChangeName: { packet = new SCChangeName(); } break; case MessageID.CSBindAccount: { packet = new CSBindAccount(); } break; case MessageID.SCBindAccount: { packet = new SCBindAccount(); } break; case MessageID.CSAskPVPList: { packet = new CSAskPVPList(); } break; case MessageID.SCAskPVPList: { packet = new SCAskPVPList(); } break; case MessageID.PVPUserBaseData: { packet = new PVPUserBaseData(); } break; case MessageID.CSAskScoreShopFresh: { packet = new CSAskScoreShopFresh(); } break; case MessageID.SCAskScoreShopFresh: { packet = new SCAskScoreShopFresh(); } break; case MessageID.CSPVPShop: { packet = new CSPVPShop(); } break; case MessageID.SCPVPShopRet: { packet = new SCPVPShopRet(); } break; case MessageID.ProductInfo: { packet = new ProductInfo(); } break; case MessageID.CSProductList: { packet = new CSProductList(); } break; case MessageID.SCProductList: { packet = new SCProductList(); } break; case MessageID.CSClearBattleData: { packet = new CSClearBattleData(); } break; case MessageID.SCClearBattleData: { packet = new SCClearBattleData(); } break; case MessageID.CSRandomCardFree: { packet = new CSRandomCardFree(); } break; case MessageID.SCRandomCardFree: { packet = new SCRandomCardFree(); } break; case MessageID.CS20038: { packet = new CS20038(); } break; case MessageID.SC30038: { packet = new SC30038(); } break; case MessageID.CS20039: { packet = new CS20039(); } break; case MessageID.SC30039: { packet = new SC30039(); } break; case MessageID.CS20040: { packet = new CS20040(); } break; case MessageID.SC30040: { packet = new SC30040(); } break; case MessageID.CS20041: { packet = new CS20041(); } break; case MessageID.SC30041: { packet = new SC30041(); } break; case MessageID.CSscode: { packet = new CSscode(); } break; case MessageID.SCscode: { packet = new SCscode(); } break; case MessageID.CSCYouProductList: { packet = new CSCYouProductList(); } break; case MessageID.SCCYouProductList: { packet = new SCCYouProductList(); } break; case MessageID.CSCYouVerifyCharge: { packet = new CSCYouVerifyCharge(); } break; case MessageID.SCCYouVerifyCharge: { packet = new SCCYouVerifyCharge(); } break; case MessageID.CSPPProductList: { packet = new CSPPProductList(); } break; case MessageID.SCPPProductList: { packet = new SCPPProductList(); } break; case MessageID.CSPPVerifyCharge: { packet = new CSPPVerifyCharge(); } break; case MessageID.SCPPVerifyCharge: { packet = new SCPPVerifyCharge(); } break; case MessageID.CSBuyMoney: { packet = new CSBuyMoney(); } break; case MessageID.SCBuyMoney: { packet = new SCBuyMoney(); } break; case MessageID.CSBuyPower: { packet = new CSBuyPower(); } break; case MessageID.SCBuyPower: { packet = new SCBuyPower(); } break; case MessageID.CSSDKLoginThirdPlatform: { packet = new CSSDKLoginThirdPlatform(); } break; case MessageID.SCSDKLoginThirdPlatformRet: { packet = new SCSDKLoginThirdPlatformRet(); } break; case MessageID.CSSDKRefresh: { packet = new CSSDKRefresh(); } break; case MessageID.SCSDKRefreshRet: { packet = new SCSDKRefreshRet(); } break; case MessageID.CSCommonProductList: { packet = new CSCommonProductList(); } break; case MessageID.SCCommonProductListRet: { packet = new SCCommonProductListRet(); } break; case MessageID.CSCYouPayVerifyCharge: { packet = new CSCYouPayVerifyCharge(); } break; case MessageID.SCCYouPayVerifyChargeRet: { packet = new SCCYouPayVerifyChargeRet(); } break; case MessageID.CSGGL: { packet = new CSGGL(); } break; case MessageID.SCGGL: { packet = new SCGGL(); } break; case MessageID.CSWuxingActivation: { packet = new CSWuxingActivation(); } break; case MessageID.SCWuxingActivation: { packet = new SCWuxingActivation(); } break; case MessageID.CSWuxingLevelup: { packet = new CSWuxingLevelup(); } break; case MessageID.SCWuxingLevelup: { packet = new SCWuxingLevelup(); } break; case MessageID.CSWuxingReset: { packet = new CSWuxingReset(); } break; case MessageID.SCWuxingReset: { packet = new SCWuxingReset(); } break; case MessageID.WuxingInfo: { packet = new WuxingInfo(); } break; case MessageID.SuipianInfo: { packet = new SuipianInfo(); } break; case MessageID.FengshuiInfo: { packet = new FengshuiInfo(); } break; case MessageID.CSBGZ: { packet = new CSBGZ(); } break; case MessageID.SCBGZ: { packet = new SCBGZ(); } break; case MessageID.MonthCardInfo: { packet = new MonthCardInfo(); } break; case MessageID.CSMonthCardGetDollar: { packet = new CSMonthCardGetDollar(); } break; case MessageID.SCMonthCardGetDollar: { packet = new SCMonthCardGetDollar(); } break; case MessageID.MonthReward: { packet = new MonthReward(); } break; case MessageID.CSMonthCardInfo: { packet = new CSMonthCardInfo(); } break; case MessageID.SCMonthCardInfo: { packet = new SCMonthCardInfo(); } break; case MessageID.CSFriendMailDelete: { packet = new CSFriendMailDelete(); } break; case MessageID.SCFriendMailDelete: { packet = new SCFriendMailDelete(); } break; case MessageID.CSStudySkill: { packet = new CSStudySkill(); } break; case MessageID.SCStudySkill: { packet = new SCStudySkill(); } break; case MessageID.CSStudySkillUpdate: { packet = new CSStudySkillUpdate(); } break; case MessageID.SCStudySkillUpdate: { packet = new SCStudySkillUpdate(); } break; case MessageID.CSQxzbPVPDataAsk: { packet = new CSQxzbPVPDataAsk(); } break; case MessageID.SCQxzbPVPDataAsk: { packet = new SCQxzbPVPDataAsk(); } break; case MessageID.CSQxzbBattle: { packet = new CSQxzbBattle(); } break; case MessageID.SCQxzbBattle: { packet = new SCQxzbBattle(); } break; case MessageID.CSQxzbPVPClearCD: { packet = new CSQxzbPVPClearCD(); } break; case MessageID.SCQxzbPVPClearCD: { packet = new SCQxzbPVPClearCD(); } break; case MessageID.CSQxzbGetReward: { packet = new CSQxzbGetReward(); } break; case MessageID.SCQxzbGetReward: { packet = new SCQxzbGetReward(); } break; case MessageID.CSPaiTaBattleData: { packet = new CSPaiTaBattleData(); } break; case MessageID.SCPaiTaBattleData: { packet = new SCPaiTaBattleData(); } break; case MessageID.CSClearPaiTaBattleData: { packet = new CSClearPaiTaBattleData(); } break; case MessageID.SCClearPaiTaBattleData: { packet = new SCClearPaiTaBattleData(); } break; case MessageID.CSAskWorldBossInfo: { packet = new CSAskWorldBossInfo(); } break; case MessageID.SCAskWorldBossInfo: { packet = new SCAskWorldBossInfo(); } break; case MessageID.WorldBoss: { packet = new WorldBoss(); } break; case MessageID.WorldBossKillInfo: { packet = new WorldBossKillInfo(); } break; case MessageID.WorldBossAttInfo: { packet = new WorldBossAttInfo(); } break; case MessageID.WorldBossDamageRankInfo: { packet = new WorldBossDamageRankInfo(); } break; case MessageID.CSAskWorldBossBattle: { packet = new CSAskWorldBossBattle(); } break; case MessageID.SCAskWorldBossBattle: { packet = new SCAskWorldBossBattle(); } break; case MessageID.CSWorldBossAddZhufu: { packet = new CSWorldBossAddZhufu(); } break; case MessageID.SCWorldBossAddZhufu: { packet = new SCWorldBossAddZhufu(); } break; case MessageID.CSWorldBossResurgence: { packet = new CSWorldBossResurgence(); } break; case MessageID.SCWorldBossResurgence: { packet = new SCWorldBossResurgence(); } break; case MessageID.CSAskActivity: { packet = new CSAskActivity(); } break; case MessageID.SCAskActivity: { packet = new SCAskActivity(); } break; case MessageID.ActivityInfo: { packet = new ActivityInfo(); } break; case MessageID.ChangeCardInfo: { packet = new ChangeCardInfo(); } break; case MessageID.cardGuidAndTempleID: { packet = new cardGuidAndTempleID(); } break; case MessageID.CSAskChangeCardList: { packet = new CSAskChangeCardList(); } break; case MessageID.SCAskChangeCardList: { packet = new SCAskChangeCardList(); } break; case MessageID.CSChangeCardConfirm: { packet = new CSChangeCardConfirm(); } break; case MessageID.SCChangeCardConfirm: { packet = new SCChangeCardConfirm(); } break; case MessageID.CSWorldBossWeekRank: { packet = new CSWorldBossWeekRank(); } break; case MessageID.SCWorldBossWeekRank: { packet = new SCWorldBossWeekRank(); } break; case MessageID.CSWorldBossWeekReward: { packet = new CSWorldBossWeekReward(); } break; case MessageID.SCWorldBossWeekReward: { packet = new SCWorldBossWeekReward(); } break; case MessageID.CSTaskOver: { packet = new CSTaskOver(); } break; case MessageID.SCTaskOver: { packet = new SCTaskOver(); } break; case MessageID.PBYunyingHuodong: { packet = new PBYunyingHuodong(); } break; case MessageID.CSYunyingHuodong: { packet = new CSYunyingHuodong(); } break; case MessageID.SCYunyingHuodong: { packet = new SCYunyingHuodong(); } break; case MessageID.CSGooglePayVerifyCharge: { packet = new CSGooglePayVerifyCharge(); } break; case MessageID.SCGooglePayVerifyChargeRet: { packet = new SCGooglePayVerifyChargeRet(); } break; } if (null != packet) { packet.packetID = packetID; } //netActionTime = DateTime.Now.ToFileTimeUtc(); return(packet); }
void InitCopyNum() { List <CopyDataBase> copyList = dataManager.GetCopyListByCopyByCopyID(m_uGotoCopyID); if (copyList == null) { m_label_frequency_Plot.text = ""; return; } string frequenceLabel = "今日已完成次数:"; if (copyList.Count == 1) { CopyDataBase db = copyList[0]; CopyInfo info = dataManager.GetCopyInfoById(db.copyId); uint useNum; uint maxNum; if (DataManager.Manager <ComBatCopyDataManager>().IsCampCopy(db.copyId)) { useNum = DataManager.Manager <CampCombatManager>().EnterCampTimes; maxNum = DataManager.Manager <CampCombatManager>().CampCopyMaxNum; } else { if (info != null) { useNum = info.CopyUseNum; maxNum = info.MaxCopyNum; } else { useNum = 0; maxNum = db.numMax; } } string desStr = useNum + "/" + maxNum; m_label_frequency_Plot.text = desStr; //if (info != null) //{ // uint num = info.CopyUseNum; // string str = num + "/" + info.MaxCopyNum; // m_label_frequency_Plot.text = str; //} //else //{ // m_label_frequency_Plot.text = 0 + "/" + db.numMax; //} if (db.forbitWhat == 1) { frequenceLabel = "今日已收益次数:"; } } if (copyList.Count > 1) { CopyDataBase temp = copyList[0]; if (temp == null) { return; } int num = 0; int maxNum = (int)temp.numMax; for (int i = 0; i < copyList.Count; i++) { CopyDataBase db = copyList[i]; CopyInfo copyInfo = dataManager.GetCopyInfoById(db.copyId); if (copyInfo != null) { num = (int)copyInfo.CopyUseNum; maxNum = (int)copyInfo.MaxCopyNum; if (db.forbitWhat == 1) { frequenceLabel = "今日已收益次数:"; } break; } } string str = num + "/" + maxNum; m_label_frequency_Plot.text = str; } m_label_frequency_label.text = frequenceLabel; }
public static void Copy(int sourceRank, int targetRank, CopyInfo copyInfo) { /* validate rank of selections */ if (copyInfo.SourceSelection.Rank != sourceRank || copyInfo.TargetSelection.Rank != targetRank) { throw new RankException($"The length of each array parameter must match the rank parameter."); } /* validate selections */ if (copyInfo.SourceSelection.GetTotalCount() != copyInfo.TargetSelection.GetTotalCount()) { throw new ArgumentException("The length of the source selection and target selection are not equal."); } for (int dimension = 0; dimension < sourceRank; dimension++) { if (copyInfo.SourceSelection.GetStop(dimension) > copyInfo.SourceDims[dimension]) { throw new ArgumentException("The source selection size exceeds the limits of the source buffer."); } } for (int dimension = 0; dimension < targetRank; dimension++) { if (copyInfo.TargetSelection.GetStop(dimension) > copyInfo.TargetDims[dimension]) { throw new ArgumentException("The target selection size exceeds the limits of the target buffer."); } } /* validate rank of dims */ if (copyInfo.SourceDims.Length != copyInfo.SourceSelection.Rank || copyInfo.SourceChunkDims.Length != copyInfo.SourceSelection.Rank || copyInfo.TargetDims.Length != copyInfo.TargetSelection.Rank || copyInfo.TargetChunkDims.Length != copyInfo.TargetSelection.Rank) { throw new RankException($"The length of each array parameter must match the rank parameter."); } /* walkers */ var sourceWalker = HyperslabUtils .Walk(sourceRank, copyInfo.SourceDims, copyInfo.SourceChunkDims, copyInfo.SourceSelection) .GetEnumerator(); var targetWalker = HyperslabUtils .Walk(targetRank, copyInfo.TargetDims, copyInfo.TargetChunkDims, copyInfo.TargetSelection) .GetEnumerator(); /* select method */ if (copyInfo.GetSourceBuffer is not null) { HyperslabUtils.CopyMemory(sourceWalker, targetWalker, copyInfo); } else if (copyInfo.GetSourceStream is not null) { HyperslabUtils.CopyStream(sourceWalker, targetWalker, copyInfo); } else { new Exception($"Either GetSourceBuffer() or GetSourceStream must be non-null."); } }
private static CopyInfo[] GetCopyInfos(XmlNodeList nodes) { CopyInfo[] copyInfos = new CopyInfo[nodes.Count]; for (int index = 0; index < nodes.Count; index++) { copyInfos[index].source = GetValue(nodes[index], "source"); copyInfos[index].target = GetValue(nodes[index], "target"); copyInfos[index].mode = GetCopyModeValue(nodes[index], "mode"); copyInfos[index].recursive = GetValue(nodes[index], "recursive", false); } return copyInfos; }
private static void CopyMemory(IEnumerator <Step> sourceWalker, IEnumerator <Step> targetWalker, CopyInfo copyInfo) { /* initialize source walker */ var sourceBuffer = default(Memory <byte>); var lastSourceChunk = default(ulong[]); /* initialize target walker */ var targetBuffer = default(Memory <byte>); var lastTargetChunk = default(ulong[]); var currentTarget = default(Memory <byte>); /* walk until end */ while (sourceWalker.MoveNext()) { /* load next source buffer */ var sourceStep = sourceWalker.Current; if (sourceBuffer.Length == 0 /* if buffer not assigned yet */ || !sourceStep.Chunk.SequenceEqual(lastSourceChunk) /* or the chunk has changed */) { sourceBuffer = copyInfo.GetSourceBuffer(sourceStep.Chunk); lastSourceChunk = sourceStep.Chunk; } var currentSource = sourceBuffer.Slice( (int)sourceStep.Offset * copyInfo.TypeSize, (int)sourceStep.Length * copyInfo.TypeSize); while (currentSource.Length > 0) { /* load next target buffer */ if (currentTarget.Length == 0) { var success = targetWalker.MoveNext(); var targetStep = targetWalker.Current; if (!success || targetStep.Length == 0) { throw new UriFormatException("The target walker stopped early."); } if (targetBuffer.Length == 0 /* if buffer not assigned yet */ || !targetStep.Chunk.SequenceEqual(lastTargetChunk) /* or the chunk has changed */) { targetBuffer = copyInfo.GetTargetBuffer(targetStep.Chunk); lastTargetChunk = targetStep.Chunk; } currentTarget = targetBuffer.Slice( (int)targetStep.Offset * copyInfo.TypeSize, (int)targetStep.Length * copyInfo.TypeSize); } /* copy */ var length = Math.Min(currentSource.Length, currentTarget.Length); currentSource .Slice(0, length) .CopyTo(currentTarget); currentSource = currentSource.Slice(length); currentTarget = currentTarget.Slice(length); } } }
void handleMsg(KBEngine.Packet packet) { var receivePkg = packet.protoBody.GetType().FullName; Debug.Log("Server Receive " + receivePkg); var className = receivePkg.Split(char.Parse(".")) [1]; IBuilderLite retPb = null; uint flowId = packet.flowId; bool findHandler = false; if (className == "CGAutoRegisterAccount") { var au = GCAutoRegisterAccount.CreateBuilder(); au.Username = "******"; retPb = au; } else if (className == "CGRegisterAccount") { var au = GCRegisterAccount.CreateBuilder(); retPb = au; } else if (className == "CGLoginAccount") { var au = GCLoginAccount.CreateBuilder(); var playerInfo = ServerData.Instance.playerInfo; if (playerInfo.HasRoles) { var role = RolesInfo.CreateBuilder().MergeFrom(playerInfo.Roles); au.AddRolesInfos(role); } retPb = au; } else if (className == "CGSelectCharacter") { var inpb = packet.protoBody as CGSelectCharacter; if (inpb.PlayerId == 101) { selectPlayerJob = 4; } else if (inpb.PlayerId == 102) { selectPlayerJob = 2; } else { selectPlayerJob = 1; } var au = GCSelectCharacter.CreateBuilder(); au.TokenId = "12345"; retPb = au; } else if (className == "CGBindingSession") { var au = GCBindingSession.CreateBuilder(); au.X = 22; au.Y = 1; au.Z = 17; au.Direction = 10; au.MapId = 0; au.DungeonBaseId = 0; au.DungeonId = 0; retPb = au; } else if (className == "CGEnterScene") { var inpb = packet.protoBody as CGEnterScene; var au = GCEnterScene.CreateBuilder(); au.Id = inpb.Id; retPb = au; } else if (className == "CGListBranchinges") { var au = GCListBranchinges.CreateBuilder(); var bran = Branching.CreateBuilder(); bran.Line = 1; bran.PlayerCount = 2; au.AddBranching(bran); retPb = au; } else if (className == "CGHeartBeat") { } else if (className == "CGCopyInfo") { var pinfo = ServerData.Instance.playerInfo; if (pinfo.HasCopyInfos) { retPb = GCCopyInfo.CreateBuilder().MergeFrom(pinfo.CopyInfos); } else { //First Fetch Login Info var au = GCCopyInfo.CreateBuilder(); var cin = CopyInfo.CreateBuilder(); cin.Id = 101; cin.IsPass = false; au.AddCopyInfo(cin); var msg = au.Build(); pinfo.CopyInfos = msg; retPb = GCCopyInfo.CreateBuilder().MergeFrom(msg); } } else if (className == "CGUserDressEquip") { PlayerData.UserDressEquip(packet); findHandler = true; } else if (className == "CGAutoRegisterAccount") { var au = GCAutoRegisterAccount.CreateBuilder(); au.Username = "******" + random.Next(); retPb = au; } else if (className == "CGRegisterAccount") { var inpb = packet.protoBody as CGRegisterAccount; ServerData.Instance.playerInfo.Username = inpb.Username; var au = GCRegisterAccount.CreateBuilder(); retPb = au; } else if (className == "CGPlayerMove") { var au = GCPlayerMove.CreateBuilder(); retPb = au; } else { var fullName = packet.protoBody.GetType().FullName; var handlerName = fullName.Replace("MyLib", "ServerPacketHandler"); var tp = Type.GetType(handlerName); if (tp == null) { if (ServerPacketHandler.HoldCode.staticTypeMap.ContainsKey(handlerName)) { tp = ServerPacketHandler.HoldCode.staticTypeMap [handlerName]; } } if (tp == null) { Debug.LogError("PushMessage noHandler " + handlerName); } else { findHandler = true; var ph = (ServerPacketHandler.IPacketHandler)Activator.CreateInstance(tp); ph.HandlePacket(packet); } } if (retPb != null) { SendPacket(retPb, flowId); } else { if (className != "CGHeartBeat" && !findHandler) { Debug.LogError("DemoServer::not Handle Message " + className); } } }
private static void CopyStream(IEnumerator <Step> sourceWalker, IEnumerator <Step> targetWalker, CopyInfo copyInfo) { /* initialize source walker */ var sourceStream = default(Stream); var lastSourceChunk = default(ulong[]); /* initialize target walker */ var targetBuffer = default(Memory <byte>); var lastTargetChunk = default(ulong[]); var currentTarget = default(Memory <byte>); /* walk until end */ while (sourceWalker.MoveNext()) { /* load next source stream */ var sourceStep = sourceWalker.Current; if (sourceStream is null /* if stream not assigned yet */ || !sourceStep.Chunk.SequenceEqual(lastSourceChunk) /* or the chunk has changed */) { sourceStream = copyInfo.GetSourceStream(sourceStep.Chunk); lastSourceChunk = sourceStep.Chunk; } sourceStream?.Seek((int)sourceStep.Offset * copyInfo.TypeSize, SeekOrigin.Begin); // corresponds to var currentLength = (int)sourceStep.Length * copyInfo.TypeSize; // sourceBuffer.Slice() while (currentLength > 0) { /* load next target buffer */ if (currentTarget.Length == 0) { var success = targetWalker.MoveNext(); var targetStep = targetWalker.Current; if (!success || targetStep.Length == 0) { throw new UriFormatException("The target walker stopped early."); } if (targetBuffer.Length == 0 /* if buffer not assigned yet */ || !targetStep.Chunk.SequenceEqual(lastTargetChunk) /* or the chunk has changed */) { targetBuffer = copyInfo.GetTargetBuffer(targetStep.Chunk); lastTargetChunk = targetStep.Chunk; } currentTarget = targetBuffer.Slice( (int)targetStep.Offset * copyInfo.TypeSize, (int)targetStep.Length * copyInfo.TypeSize); } /* copy */ var length = Math.Min(currentLength, currentTarget.Length); sourceStream?.Read(currentTarget.Slice(0, length).Span); // corresponds to span.CopyTo sourceStream?.Seek((int)sourceStep.Offset * copyInfo.TypeSize, SeekOrigin.Begin); // corresponds to currentLength -= (int)sourceStep.Length * copyInfo.TypeSize; // sourceBuffer.Slice() currentTarget = currentTarget.Slice(length); } } }
/// <summary> /// Copy the <paramref name="sourceThing"/> into the target <paramref name="partition"/> /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="partition">The current partition</param> /// <param name="sourceThing">The source <see cref="Thing"/> to copy</param> /// <param name="targetContainer">The target container <see cref="Thing"/></param> /// <param name="allSourceThings">All source <see cref="Thing"/>s in the current copy operation</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="sourceToCopyMap">A dictionary mapping identifiers of original to copy</param> /// <param name="rdls">The <see cref="ReferenceDataLibrary"/></param> /// <param name="targetEngineeringModelSetup"></param> /// <param name="securityContext">The <see cref="ISecurityContext"/></param> public override void Copy(NpgsqlTransaction transaction, string partition, Thing sourceThing, Thing targetContainer, IReadOnlyList <Thing> allSourceThings, CopyInfo copyinfo, Dictionary <Guid, Guid> sourceToCopyMap, IReadOnlyList <ReferenceDataLibrary> rdls, EngineeringModelSetup targetEngineeringModelSetup, ISecurityContext securityContext) { if (!(sourceThing is ParameterOverride sourceParameterOverride)) { throw new InvalidOperationException("The source is not of the right type"); } var copy = sourceParameterOverride.DeepClone <ParameterOverride>(); copy.Iid = sourceToCopyMap[sourceParameterOverride.Iid]; if (copyinfo.Options.KeepOwner.HasValue && (!copyinfo.Options.KeepOwner.Value || copyinfo.Options.KeepOwner.Value && !targetEngineeringModelSetup.ActiveDomain.Contains(copy.Owner) ) ) { copy.Owner = copyinfo.ActiveOwner; } if (copyinfo.Source.IterationId.Value != copyinfo.Target.IterationId.Value) { copy.Parameter = sourceToCopyMap[sourceParameterOverride.Parameter]; } if (!this.OperationSideEffectProcessor.BeforeCreate(copy, targetContainer, transaction, partition, securityContext)) { return; } this.ParameterOverrideDao.Write(transaction, partition, copy, targetContainer); this.OperationSideEffectProcessor.AfterCreate(copy, targetContainer, null, transaction, partition, securityContext); var newparameterOverride = this.ParameterOverrideDao.Read(transaction, partition, new[] { copy.Iid }).Single(); if (copyinfo.Options.KeepValues.HasValue && copyinfo.Options.KeepValues.Value) { var valuesets = this.ValueSetService .GetShallow(transaction, partition, newparameterOverride.ValueSet, securityContext) .OfType <ParameterOverrideValueSet>().ToList(); // update all value-set foreach (var valueset in valuesets) { var sourceToCopyOverridenValueSetPair = sourceToCopyMap.SingleOrDefault(x => x.Value == valueset.ParameterValueSet); var sourceOverridenValueSet = allSourceThings.OfType <ParameterOverrideValueSet>() .FirstOrDefault(x => x.ParameterValueSet == sourceToCopyOverridenValueSetPair.Key && sourceParameterOverride.ValueSet.Contains(x.Iid) || x.ParameterValueSet == valueset.ParameterValueSet); // an override may be copied without its parameter (secod condition) if (sourceOverridenValueSet == null) { continue; } sourceToCopyMap[sourceOverridenValueSet.Iid] = valueset.Iid; valueset.Manual = sourceOverridenValueSet.Manual; valueset.Computed = sourceOverridenValueSet.Computed; valueset.Reference = sourceOverridenValueSet.Reference; valueset.Published = new ValueArray <string>(Enumerable.Repeat("-", valueset.Manual.Count)); valueset.ValueSwitch = sourceOverridenValueSet.ValueSwitch; this.ValueSetService.UpdateConcept(transaction, partition, valueset, copy); } } var sourceSubscriptions = allSourceThings.OfType <ParameterSubscription>().Where(x => sourceParameterOverride.ParameterSubscription.Contains(x.Iid)).ToList(); foreach (var sourceSubscription in sourceSubscriptions) { if (sourceSubscription.Owner == newparameterOverride.Owner) { // do not create subscriptions continue; } ((ServiceBase)this.ParameterSubscriptionService).Copy(transaction, partition, sourceSubscription, newparameterOverride, allSourceThings, copyinfo, sourceToCopyMap, rdls, targetEngineeringModelSetup, securityContext); } }
/// <summary> /// Copy the <paramref name="sourceThing"/> into the target <paramref name="partition"/> /// </summary> /// <param name="transaction">The current transaction</param> /// <param name="partition">The current partition</param> /// <param name="sourceThing">The source <see cref="Thing"/> to copy</param> /// <param name="targetContainer">The target container <see cref="Thing"/></param> /// <param name="allSourceThings">All source <see cref="Thing"/>s in the current copy operation</param> /// <param name="copyinfo">The <see cref="CopyInfo"/></param> /// <param name="sourceToCopyMap">A dictionary mapping identifiers of original to copy</param> /// <param name="rdls">The <see cref="ReferenceDataLibrary"/></param> /// <param name="targetEngineeringModelSetup">The target <see cref="EngineeringModelSetup"/></param> /// <param name="securityContext">The <see cref="ISecurityContext"/></param> public override void Copy(NpgsqlTransaction transaction, string partition, Thing sourceThing, Thing targetContainer, IReadOnlyList <Thing> allSourceThings, CopyInfo copyinfo, Dictionary <Guid, Guid> sourceToCopyMap, IReadOnlyList <ReferenceDataLibrary> rdls, EngineeringModelSetup targetEngineeringModelSetup, ISecurityContext securityContext) { if (!(sourceThing is ElementDefinition sourceElementDef)) { throw new InvalidOperationException("The source is not of the right type"); } var copy = sourceElementDef.DeepClone <ElementDefinition>(); copy.Iid = sourceToCopyMap[sourceElementDef.Iid]; // remove references that are not being copied over copy.ReferencedElement.Clear(); // check reference data validity in target iteration if models are different if (copyinfo.Source.TopContainer.Iid != copyinfo.Target.TopContainer.Iid) { var possibleCats = rdls.SelectMany(x => x.DefinedCategory).ToList(); var ignoredCategories = copy.Category.Except(possibleCats).ToList(); foreach (var ignoredCategory in ignoredCategories) { copy.Category.Remove(ignoredCategory); } } if (copyinfo.Options.KeepOwner.HasValue && (!copyinfo.Options.KeepOwner.Value || copyinfo.Options.KeepOwner.Value && !targetEngineeringModelSetup.ActiveDomain.Contains(copy.Owner) ) ) { copy.Owner = copyinfo.ActiveOwner; } if (!this.OperationSideEffectProcessor.BeforeCreate(copy, targetContainer, transaction, partition, securityContext)) { return; } this.ElementDefinitionDao.Write(transaction, partition, copy, targetContainer); this.OperationSideEffectProcessor.AfterCreate(copy, targetContainer, null, transaction, partition, securityContext); // copy contained things foreach (var group in allSourceThings.Where(x => sourceElementDef.ParameterGroup.Contains(x.Iid))) { ((ServiceBase)this.ParameterGroupService).Copy(transaction, partition, @group, copy, allSourceThings, copyinfo, sourceToCopyMap, rdls, targetEngineeringModelSetup, securityContext); } foreach (var parameter in allSourceThings.Where(x => sourceElementDef.Parameter.Contains(x.Iid))) { ((ServiceBase)this.ParameterService).Copy(transaction, partition, parameter, copy, allSourceThings, copyinfo, sourceToCopyMap, rdls, targetEngineeringModelSetup, securityContext); } // only copy directly usage if in same iteration, otherwise extra actions are required at a higher level if (copyinfo.Source.IterationId.Value == copyinfo.Target.IterationId.Value) { foreach (var usage in allSourceThings.Where(x => sourceElementDef.ContainedElement.Contains(x.Iid))) { ((ServiceBase)this.ContainedElementService).Copy(transaction, partition, usage, copy, allSourceThings, copyinfo, sourceToCopyMap, rdls, targetEngineeringModelSetup, securityContext); } } }
public void VerifyCopyElementDefWorks() { var modelSetupService = new Mock <IEngineeringModelSetupService>(); var modelSetup = new EngineeringModelSetup(Guid.NewGuid(), 0); modelSetupService.Setup(x => x.GetEngineeringModelSetup(It.IsAny <NpgsqlTransaction>(), It.IsAny <Guid>())).Returns(modelSetup); this.copySourceDtos = new List <Thing>(); var boolParamTypeId = Guid.NewGuid(); var mrdl = new ModelReferenceDataLibrary(Guid.NewGuid(), 1); mrdl.ParameterType.Add(boolParamTypeId); var sourceIteration = new Iteration(Guid.NewGuid(), 1); var sourceElementDef1 = new ElementDefinition(Guid.NewGuid(), 1); var sourceElementDef2 = new ElementDefinition(Guid.NewGuid(), 1); var sourceUsage1 = new ElementUsage(Guid.NewGuid(), 1) { ElementDefinition = sourceElementDef2.Iid }; sourceElementDef1.ContainedElement.Add(sourceUsage1.Iid); sourceIteration.Element.Add(sourceElementDef1.Iid); sourceIteration.Element.Add(sourceElementDef2.Iid); var parameter1 = new Parameter(Guid.NewGuid(), 1) { ParameterType = boolParamTypeId }; var pvs1 = new ParameterValueSet(Guid.NewGuid(), 1) { Manual = new ValueArray <string>(new[] { "true" }), Computed = new ValueArray <string>(new[] { "-" }), Reference = new ValueArray <string>(new[] { "-" }), Published = new ValueArray <string>(new[] { "-" }), ValueSwitch = ParameterSwitchKind.MANUAL }; var parameter2 = new Parameter(Guid.NewGuid(), 1) { ParameterType = boolParamTypeId }; var pvs2 = new ParameterValueSet(Guid.NewGuid(), 1) { Manual = new ValueArray <string>(new[] { "true" }), Computed = new ValueArray <string>(new[] { "-" }), Reference = new ValueArray <string>(new[] { "-" }), Published = new ValueArray <string>(new[] { "-" }), ValueSwitch = ParameterSwitchKind.MANUAL }; parameter1.ValueSet.Add(pvs1.Iid); sourceElementDef1.Parameter.Add(parameter1.Iid); parameter2.ValueSet.Add(pvs2.Iid); sourceElementDef2.Parameter.Add(parameter2.Iid); var override2 = new ParameterOverride(Guid.NewGuid(), 1); override2.Parameter = parameter2.Iid; var ovs = new ParameterOverrideValueSet(Guid.NewGuid(), 1) { ParameterValueSet = pvs2.Iid }; override2.ValueSet.Add(ovs.Iid); sourceUsage1.ParameterOverride.Add(override2.Iid); this.copySourceDtos.Add(sourceIteration); this.copySourceDtos.Add(sourceElementDef1); this.copySourceDtos.Add(sourceElementDef2); this.copySourceDtos.Add(sourceUsage1); this.copySourceDtos.Add(parameter1); this.copySourceDtos.Add(pvs1); this.copySourceDtos.Add(parameter2); this.copySourceDtos.Add(pvs2); this.copySourceDtos.Add(override2); this.copySourceDtos.Add(ovs); var targetIteration = new Iteration(Guid.NewGuid(), 1); this.serviceProvider.Setup(x => x.MapToReadService(It.IsAny <string>())).Returns <string>(x => new TestSourceService(this.copySourceDtos, x)); this.serviceProvider.Setup(x => x.MapToReadService(It.Is <string>(t => t == ClassKind.ModelReferenceDataLibrary.ToString()))) .Returns <string>(x => new TestSourceService(new List <Thing> { mrdl }, x)); this.serviceProvider.Setup(x => x.MapToReadService(It.Is <string>(t => t == ClassKind.Iteration.ToString()))) .Returns <string>(x => new TestSourceService(new List <Thing> { sourceIteration, targetIteration }, x)); var customOperationSideEffectProcessor = new Mock <IOperationSideEffectProcessor>(); customOperationSideEffectProcessor.Setup(x => x.BeforeCreate(It.IsAny <Thing>(), It.IsAny <Thing>(), It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <ISecurityContext>())). Returns(true); var paramSubscriptionService = new ParameterSubscriptionService { ParameterSubscriptionDao = new Mock <IParameterSubscriptionDao>().Object, PermissionService = this.permissionService.Object, }; var parameterContextProvider = new OldParameterContextProvider { ParameterValueSetService = new TestSourceService(this.copySourceDtos, ClassKind.ParameterValueSet.ToString()) }; var paramGroupService = new ParameterGroupService { PermissionService = this.permissionService.Object, TransactionManager = this.transactionManager.Object, ParameterGroupDao = new Mock <IParameterGroupDao>().Object }; var valueSetService = new Mock <IParameterValueSetService>(); valueSetService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>())) .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>((a, b, c, d) => { var list = new List <ParameterValueSet>(); foreach (var guid in c) { var vs = new ParameterValueSet(guid, 1) { Manual = new ValueArray <string>(new [] { "-" }), Computed = new ValueArray <string>(new [] { "-" }), Reference = new ValueArray <string>(new [] { "-" }), Published = new ValueArray <string>(new [] { "-" }) }; list.Add(vs); } return(list); }); var overrideValueSetService = new Mock <IParameterOverrideValueSetService>(); overrideValueSetService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>())) .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>((a, b, c, d) => { var list = new List <ParameterOverrideValueSet>(); foreach (var guid in c) { var vs = new ParameterOverrideValueSet(guid, 1) { Manual = new ValueArray <string>(new[] { "-" }), Computed = new ValueArray <string>(new[] { "-" }), Reference = new ValueArray <string>(new[] { "-" }), Published = new ValueArray <string>(new[] { "-" }) }; list.Add(vs); } return(list); }); var paramDao = new TestParameterDao(); var paramService = new ParameterService { PermissionService = this.permissionService.Object, ParameterDao = paramDao, OperationSideEffectProcessor = customOperationSideEffectProcessor.Object, TransactionManager = this.transactionManager.Object, OldParameterContextProvider = parameterContextProvider, ParameterSubscriptionService = paramSubscriptionService, ParameterValueSetService = valueSetService.Object }; var paramOverrideDao = new TestParameterOverrideDao(); var paramOverrideService = new ParameterOverrideService { PermissionService = this.permissionService.Object, ParameterOverrideDao = paramOverrideDao, TransactionManager = this.transactionManager.Object, OperationSideEffectProcessor = customOperationSideEffectProcessor.Object, ParameterSubscriptionService = paramSubscriptionService, ParameterOverrideValueSetService = overrideValueSetService.Object }; var usageDao = new Mock <IElementUsageDao>(); var usageService = new ElementUsageService { PermissionService = this.permissionService.Object, ParameterOverrideService = paramOverrideService, ElementUsageDao = usageDao.Object, TransactionManager = this.transactionManager.Object, OperationSideEffectProcessor = customOperationSideEffectProcessor.Object }; var edDao = new TestElementDefinitionDao(); var edService = new ElementDefinitionService { PermissionService = this.permissionService.Object, ElementDefinitionDao = edDao, ElementUsageService = usageService, ParameterService = paramService, TransactionManager = this.transactionManager.Object, OperationSideEffectProcessor = customOperationSideEffectProcessor.Object, ParameterGroupService = paramGroupService }; this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ElementDefinition.ToString())).Returns(edService); this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ElementUsage.ToString())).Returns(usageService); this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.Parameter.ToString())).Returns(paramService); this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterOverride.ToString())).Returns(paramOverrideService); this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterSubscription.ToString())).Returns(paramSubscriptionService); this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterGroup.ToString())).Returns(paramGroupService); var postOperation = new CdpPostOperation(); var copyinfo = new CopyInfo { ActiveOwner = Guid.NewGuid(), Options = new CopyInfoOptions { CopyKind = CopyKind.Deep, KeepOwner = true, KeepValues = true }, Source = new CopySource { IterationId = sourceIteration.Iid, Thing = new CopyReference { Iid = sourceElementDef1.Iid, ClassKind = ClassKind.ElementDefinition }, TopContainer = new CopyReference { Iid = Guid.NewGuid(), ClassKind = ClassKind.EngineeringModel } }, Target = new CopyTarget { IterationId = targetIteration.Iid, Container = new CopyReference { Iid = targetIteration.Iid, ClassKind = ClassKind.Iteration }, TopContainer = new CopyReference { Iid = Guid.NewGuid(), ClassKind = ClassKind.EngineeringModel } } }; postOperation.Copy.Add(copyinfo); this.serviceProvider.Setup(x => x.MapToReadService(ClassKind.EngineeringModelSetup.ToString())).Returns(modelSetupService.Object); this.operationProcessor.Process(postOperation, null, $"Iteration_{targetIteration.Iid.ToString().Replace("-", "_")}", null); Assert.AreEqual(2, edDao.WrittenThingCount); Assert.AreEqual(2, paramDao.WrittenThingCount); Assert.AreEqual(1, paramOverrideDao.WrittenThingCount); usageDao.Verify(x => x.Write(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <ElementUsage>(), It.IsAny <Thing>()), Times.Once); }
/// <summary> /// Resolves the copy operations /// </summary> /// <param name="operation">The <see cref="Operation"/></param> private void ResolveCopy(Operation operation) { if (!operation.OperationKind.IsCopyOperation()) { return; } var options = new CopyInfoOptions { CopyKind = CopyKind.Deep, KeepOwner = operation.OperationKind == OperationKind.Copy || operation.OperationKind == OperationKind.CopyKeepValues, KeepValues = operation.OperationKind == OperationKind.CopyKeepValues || operation.OperationKind == OperationKind.CopyKeepValuesChangeOwner }; var sourcepoco = operation.OriginalThing.QuerySourceThing(); var sourceIteration = sourcepoco.GetContainerOfType <Iteration>(); var source = new CopySource { Thing = new CopyReference { Iid = operation.OriginalThing.Iid, ClassKind = operation.OriginalThing.ClassKind }, TopContainer = new CopyReference { Iid = sourcepoco.TopContainer.Iid, ClassKind = sourcepoco.TopContainer.ClassKind }, IterationId = sourceIteration?.Iid }; var poco = operation.ModifiedThing.QuerySourceThing(); if (poco.Container == null) { throw new InvalidOperationException("The container cannot be null."); } var targetIteration = poco.GetContainerOfType <Iteration>(); var target = new CopyTarget { Container = new CopyReference { Iid = poco.Container.Iid, ClassKind = poco.Container.ClassKind }, TopContainer = new CopyReference { Iid = poco.TopContainer.Iid, ClassKind = poco.TopContainer.ClassKind }, IterationId = targetIteration?.Iid }; var copyInfo = new CopyInfo { Source = source, Target = target, Options = options }; if (targetIteration != null) { var participation = this.session.OpenIterations.FirstOrDefault(x => x.Key.Iid == targetIteration.Iid).Value; copyInfo.ActiveOwner = participation.Item1?.Iid ?? Guid.Empty; } this.Copy.Add(copyInfo); }