/// <summary> /// If we do not have enterprise enabled, copy the book and remove all enterprise level features. /// </summary> internal static bool PrepareBookForUpload(ref Book.Book book, BookServer bookServer, string tempFolderPath, IProgress progress) { if (book.CollectionSettings.HaveEnterpriseFeatures) { return(false); } // We need to be sure that any in-memory changes have been written to disk // before we start copying/loading the new book to/from disk book.Save(); Directory.CreateDirectory(tempFolderPath); BookStorage.CopyDirectory(book.FolderPath, tempFolderPath); var bookInfo = new BookInfo(tempFolderPath, true); var copiedBook = bookServer.GetBookFromBookInfo(bookInfo); copiedBook.BringBookUpToDate(new NullProgress(), true); var pages = new List <XmlElement>(); foreach (XmlElement page in copiedBook.GetPageElements()) { pages.Add(page); } ISet <string> warningMessages = new HashSet <string>(); PublishHelper.RemoveEnterpriseFeaturesIfNeeded(copiedBook, pages, warningMessages); PublishHelper.SendBatchedWarningMessagesToProgress(warningMessages, progress); copiedBook.Save(); copiedBook.Storage.UpdateSupportFiles(); book = copiedBook; return(true); }
private bool ProcessOneMsg(byte[] msgBytes) { var head = SiMsgHelper.GetSiMsgHead(msgBytes); switch (head.u16MsgType) { case SiMacroDef.O_SILMTENB_GETFILEINFO_RES: PublishHelper.PublishMsg("topic", msgBytes); //TODO topic协商 break; case SiMacroDef.O_SILMTENB_GETFILEATTRIB_RES: break; case SiMacroDef.O_SILMTENB_SETRDWRATTRIB_RES: break; case SiMacroDef.O_SILMTENB_DELFILE_RES: break; case SiMacroDef.O_SILMTENB_GETCAPACITY_RES: break; default: //TODO 不知道是什么啊,老铁 break; } return(true); }
/// <summary>Called when the item is saving.</summary> protected void OnItemSaving(object sender, EventArgs args) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull((object)args, "args"); // Do not run rules when installting Sitecore packages if (Sitecore.Context.Job?.Name == "Install") { return; } // Do not run rules when publishing if (!Settings.Rules.ItemEventHandlers.RunDuringPublishing && PublishHelper.IsPublishing()) { return; } Item obj = Event.ExtractParameter(args, 0) as Item; if (obj == null) { return; } this.RunItemSavingRules(obj); }
/// <summary> /// 发送开关按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click(object sender, RoutedEventArgs e) { IList <TraceSetTreeModel> selectList = GetCheckedItems(); List <string> lstrSelectName = new List <string>(); string strTest = string.Empty; byte[] arrySwitch = new byte[256]; for (int i = 0; i < 256; i++) { arrySwitch[i] = 0; } for (int i = 0; i < selectList.Count; i++) { //lstrSelectName.Add(selectList[i].Name); int nID = GetIDByName(selectList[i].Name); arrySwitch[nID] = 1; strTest += nID.ToString() + ": " + arrySwitch[nID].ToString() + "\n"; } PublishHelper.PublishMsg("/AtpBack/TraceConfig/StartTrace", arrySwitch); ParseMessageWindow Pw = new ParseMessageWindow(); Pw.Show(); }
private void ParseUdpData(UdpDataInfo data) { //TODO 需要确定是否要去掉其他的数据 //处理完成后,通过接口发送给CDL PublishHelper.PublishMsg("/AtpBack/CDLParse/MsgParse", data.UdpDataBytes); }
/// <summary> /// 发送数据,为登录和注销使用。 /// 登录时,SerssionService需要创建连接;注销时,则删除连接 /// </summary> /// <param name="dataBytes">要发送板卡的数据</param> /// <param name="isLogon">是否登陆操作</param> /// <returns></returns> public int SendPackets(byte[] dataBytes, bool isLogon) { if (null == dataBytes) { throw new ArgumentNullException("dataBytes is null"); } SessionData sessionData = new SessionData(dataBytes.Length) { target = { raddr = _netElementConfig.TargetIp, rport = CommonPort.AtpLinkPort, laddr = _netElementConfig.TraceIp }, data = dataBytes }; string sendBytes = JsonHelper.SerializeObjectToString(sessionData); //创建和断开连接的topic比较特殊 string act = (isLogon ? "Create" : "Delete"); string topic = string.Format($"/SessionService/{act}/UDP"); PublishHelper.PublishMsg(topic, sendBytes); return(sendBytes.Length); }
public async Task <DeployStatus> PerformServerSideBuild(Site functionApp, Func <Task <Stream> > zipFileFactory, Func <HttpClient, Task <DeployStatus> > deploymentStatusPollTask) { using (var handler = new ProgressMessageHandler(new HttpClientHandler())) using (var client = GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}"), handler)) using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri( $"api/zipdeploy?isAsync=true&author={Environment.MachineName}", UriKind.Relative))) { ColoredConsole.WriteLine("Creating archive for current directory..."); request.Headers.IfMatch.Add(EntityTagHeaderValue.Any); (var content, var length) = CreateStreamContentZip(await zipFileFactory()); request.Content = content; HttpResponseMessage response = await PublishHelper.InvokeLongRunningRequest(client, handler, request, length, "Uploading"); await PublishHelper.CheckResponseStatusAsync(response, "Uploading archive..."); // Streaming deployment status for Linux Server Side Build DeployStatus status = await deploymentStatusPollTask(client); if (status == DeployStatus.Success) { ColoredConsole.WriteLine(Green("Remote build succeeded!")); } else if (status == DeployStatus.Failed) { throw new CliException("Remote build failed!"); } else if (status == DeployStatus.Unknown) { ColoredConsole.WriteLine(Yellow($"Failed to retrieve remote build status, please visit https://{functionApp.ScmUri}/api/deployments")); } return(status); } }
public override async Task RunAsync() { // Get function app var functionApp = await AzureHelper.GetFunctionApp(FunctionAppName, AccessToken, ManagementURL); // Get the GitIgnoreParser from the functionApp root var functionAppRoot = ScriptHostHelpers.GetFunctionAppRootDirectory(Environment.CurrentDirectory); var ignoreParser = PublishHelper.GetIgnoreParser(functionAppRoot); // Get the WorkerRuntime var workerRuntime = WorkerRuntimeLanguageHelper.GetCurrentWorkerRuntimeLanguage(_secretsManager); // Check for any additional conditions or app settings that need to change // before starting any of the publish activity. var additionalAppSettings = await ValidateFunctionAppPublish(functionApp, workerRuntime); if (workerRuntime == WorkerRuntime.dotnet && !Csx && !NoBuild) { if (DotnetHelpers.CanDotnetBuild()) { var outputPath = Path.Combine("bin", "publish"); await DotnetHelpers.BuildDotnetProject(outputPath, DotnetCliParameters); Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, outputPath); } else if (StaticSettings.IsDebug) { ColoredConsole.WriteLine("Could not find a valid .csproj file. Skipping the build."); } } if (workerRuntime != WorkerRuntime.dotnet || Csx) { // Restore all valid extensions var installExtensionAction = new InstallExtensionAction(_secretsManager, false); await installExtensionAction.RunAsync(); } if (ListIncludedFiles) { InternalListIncludedFiles(ignoreParser); } else if (ListIgnoredFiles) { InternalListIgnoredFiles(ignoreParser); } else { if (PublishLocalSettingsOnly) { await PublishLocalAppSettings(functionApp, additionalAppSettings); } else { await PublishFunctionApp(functionApp, ignoreParser, additionalAppSettings); } } }
public void OnAcceptButton() { PublishHelper _publishHelper = FindObjectOfType <PublishHelper>(); _publishHelper.SerializeUser(); mainPanel.SetActive(true); confirmCapPanel.SetActive(false); }
public int SendPackets(byte[] dataBytes) { if (null == dataBytes) { throw new ArgumentNullException("dataBytes is null"); } PublishHelper.PublishMsg($"udp-send://{_netElementConfig.TargetIp}:{CommonPort.AtpLinkPort}", dataBytes); return(dataBytes.Length); }
/// <summary> /// 发送报文。直接调用了PublishHelper /// </summary> /// <param name="dataBytes">要发送的数据流</param> /// <param name="topic">该数据流对应的topic</param> /// <returns>发送的字节数</returns> public int SendPackets(byte[] dataBytes, string topic) { if (null == dataBytes) { throw new ArgumentNullException("dataBytes is null"); } PublishHelper.PublishMsg(topic, dataBytes); return(dataBytes.Length); }
/// <summary> /// 主界面进行隐藏时调用,清空所有信息,并发送停止消息 /// </summary> public void ClearAll() { UE_List.Clear(); ENB_List.Clear(); GNB_List.Clear(); lbUE.Items.Clear(); lbeNB.Items.Clear(); lbgNB.Items.Clear(); PublishHelper.PublishMsg("StopTraceHlSignal", ""); }
private void Updater() { DateTime initialTruncationTime = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(LogTruncateInterval)); DateTime initialDiagnosticLogTime = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(DiagnosticLogIntervalInMinutes)); while (true) { int eventId = WaitHandle.WaitAny(_waitHandleArray, Interval); if (eventId == 0) { //If exitevent is signalled, the process is exiting. break; } #region Update Operations PublishHelper.LogVerboseInformation("UpdaterThread: Found {0} completed operations to update", _completedOperations.Count); if (_completedOperations.Count > 0) { lock (_completedOperations) { while (_completedOperations.Count > 0) { var operation = _completedOperations.Dequeue(); PublishHelper.UpdatePublishOperation(operation.OperationId, operation.SiteName, operation.Status); } } } #endregion #region Remove Stale Operations if ((DateTime.UtcNow - initialTruncationTime).TotalMinutes > LogTruncateInterval) { initialTruncationTime = DateTime.UtcNow; PublishHelper.LogVerboseInformation("LogTruncaterThread: Removing Stale Operations"); PublishHelper.RemoveStalePublishOperations(); } #endregion #region Log Diagnostic Data if ((DateTime.UtcNow - initialDiagnosticLogTime).TotalMinutes > DiagnosticLogIntervalInMinutes) { initialDiagnosticLogTime = DateTime.UtcNow; PublishHelper.LogOperationCount(); } #endregion } }
internal PublishManager(string serviceName) { _exitEvent = new AutoResetEvent(false); _continueEvent = new AutoResetEvent(false); _waitHandleArray = new WaitHandle[] { _exitEvent, _continueEvent }; _pendingPublishOperations = new Queue <Operation>(); _completedOperations = new Queue <Operation>(); _pendingDeleteOperations = new Queue <Operation>(); _operationsInProgress = new HashSet <string>(); PublishHelper.LogVerboseInformation("PublishManager initialized"); ServicePointManager.ServerCertificateValidationCallback += CertificateHelper.CertificateValidationCallback; }
public void ReportTechnologyPollingAssignmentIndication( ITechnologyPolling technologyPolling, int[] netObjectsInstanceIDs, bool enabledStateChangedTo) { if (technologyPolling == null) { throw new ArgumentNullException(nameof(technologyPolling)); } if (netObjectsInstanceIDs == null) { throw new ArgumentNullException(nameof(netObjectsInstanceIDs)); } if (netObjectsInstanceIDs.Length == 0) { return; } ITechnology technology = TechnologyManager.Instance.TechnologyFactory.GetTechnology(technologyPolling.get_TechnologyID()); string netObjectPrefix = NetObjectTypesDAL.GetNetObjectPrefix(this.swisFactory, technology.get_TargetEntity()); string entityName = NetObjectTypesDAL.GetEntityName(this.swisFactory, technology.get_TargetEntity()); Dictionary <int, string> netObjectsCaptions = NetObjectTypesDAL.GetNetObjectsCaptions(this.swisFactory, technology.get_TargetEntity(), netObjectsInstanceIDs); foreach (int objectsInstanceId in netObjectsInstanceIDs) { PropertyBag propertyBag1 = new PropertyBag(); ((Dictionary <string, object>)propertyBag1).Add("InstanceType", (object)"Orion.TechnologyPollingAssignments"); ((Dictionary <string, object>)propertyBag1).Add("InstanceID", (object)objectsInstanceId.ToString()); ((Dictionary <string, object>)propertyBag1).Add("TechnologyPollingID", (object)technologyPolling.get_TechnologyPollingID()); ((Dictionary <string, object>)propertyBag1).Add("Enabled", (object)enabledStateChangedTo); ((Dictionary <string, object>)propertyBag1).Add("TargetEntity", (object)technology.get_TargetEntity()); ((Dictionary <string, object>)propertyBag1).Add("TechPollingDispName", (object)technologyPolling.get_DisplayName()); ((Dictionary <string, object>)propertyBag1).Add("TechnologyDispName", (object)technology.get_DisplayName()); PropertyBag propertyBag2 = propertyBag1; string str; if (netObjectsCaptions.TryGetValue(objectsInstanceId, out str)) { ((Dictionary <string, object>)propertyBag2).Add("NetObjectCaption", (object)str); } if (netObjectPrefix != null) { ((Dictionary <string, object>)propertyBag2).Add("NetObjectPrefix", (object)netObjectPrefix); ((Dictionary <string, object>)propertyBag2).Add((string)KnownKeys.NetObject, (object)string.Format("{0}:{1}", (object)netObjectPrefix, (object)objectsInstanceId)); } if (entityName != null) { ((Dictionary <string, object>)propertyBag2).Add("NetObjectName", (object)entityName); } this.publishManager.Publish(PublishHelper.ConvertIndication((IIndication) new TechnologyPollingAssignmentIndication((IndicationType)2, propertyBag2))); } }
public async Task <DeployStatus> PerformServerSideBuild(Site functionApp, Func <Task <Stream> > zipFileFactory, Func <HttpClient, Task <DeployStatus> > deploymentStatusPollTask, bool attachRestrictedToken = true) { if (string.IsNullOrEmpty(functionApp.ScmUri)) { throw new CliException("Remote build is a new feature added to function apps. " + $"Your function app {functionApp.SiteName} does not support remote build as it was created before August 1st, 2019."); } using (var handler = new ProgressMessageHandler(new HttpClientHandler())) using (var client = GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}"), handler)) using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri( $"api/zipdeploy?isAsync=true&author={Environment.MachineName}", UriKind.Relative))) { ColoredConsole.WriteLine("Creating archive for current directory..."); request.Headers.IfMatch.Add(EntityTagHeaderValue.Any); (var content, var length) = CreateStreamContentZip(await zipFileFactory()); request.Content = content; if (attachRestrictedToken) { // Attach x-ms-site-restricted-token for Linux Consumption remote build string restrictedToken = await KuduLiteDeploymentHelpers.GetRestrictedToken(functionApp, AccessToken, ManagementURL); request.Headers.Add("x-ms-site-restricted-token", restrictedToken); } HttpResponseMessage response = await PublishHelper.InvokeLongRunningRequest(client, handler, request, length, "Uploading"); await PublishHelper.CheckResponseStatusAsync(response, "Uploading archive..."); // Streaming deployment status for Linux Server Side Build DeployStatus status = await deploymentStatusPollTask(client); if (status == DeployStatus.Success) { ColoredConsole.WriteLine(Green("Remote build succeeded!")); } else if (status == DeployStatus.Failed) { throw new CliException("Remote build failed!"); } return(status); } }
private void DealSendTraceSwitchRsp(string ip, byte[] dataBytes) { if (string.IsNullOrWhiteSpace(ip) || string.IsNullOrEmpty(ip)) { throw new ArgumentNullException(); } if (!HasLinkWithSameIp(ip)) { return; } MsgGtsa2GtsmTraceCtrlRsp rsp = (MsgGtsa2GtsmTraceCtrlRsp)SerializeHelper.BytesToStruct(dataBytes, typeof(MsgGtsa2GtsmTraceCtrlRsp)); byte[] rspBytes = new byte[] { rsp.u8Complete }; PublishHelper.PublishMsg("/AtpFront/TraceConfig/TraceActRsp", rspBytes); }
/// <summary> /// 发送消息跟踪控制开关 /// </summary> /// <param name="switchs">前台已经处理好的开关</param> /// <returns></returns> public bool SendTraceSwitch(byte[] switchs) { //创建IP连接 SessionData sessionData = new SessionData(10) { target = { raddr = _netElementConfig.TargetIp, rport = CommonPort.AtpLinkPort, laddr = _netElementConfig.TraceIp } }; string sendBytes = JsonHelper.SerializeObjectToString(sessionData); PublishHelper.PublishMsg("/SessionService/Create/IP", sendBytes); return(SendTSwitchs(switchs, _netElementConfig)); }
public override async Task RunAsync() { // Get function app var functionApp = await AzureHelper.GetFunctionApp(FunctionAppName, AccessToken); // Get the GitIgnoreParser from the functionApp root var functionAppRoot = ScriptHostHelpers.GetFunctionAppRootDirectory(Environment.CurrentDirectory); var ignoreParser = PublishHelper.GetIgnoreParser(functionAppRoot); // Get the WorkerRuntime var workerRuntime = WorkerRuntimeLanguageHelper.GetCurrentWorkerRuntimeLanguage(_secretsManager); // Check for any additional conditions or app settings that need to change // before starting any of the publish activity. var additionalAppSettings = ValidateFunctionAppPublish(functionApp, workerRuntime); if (workerRuntime == WorkerRuntime.dotnet && !Csx && !NoBuild) { const string outputPath = "bin/publish"; await DotnetHelpers.BuildDotnetProject(outputPath, DotnetCliParameters); Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, outputPath); } if (ListIncludedFiles) { InternalListIncludedFiles(ignoreParser); } else if (ListIgnoredFiles) { InternalListIgnoredFiles(ignoreParser); } else { if (PublishLocalSettingsOnly) { await PublishLocalAppSettings(functionApp, additionalAppSettings); } else { await PublishFunctionApp(functionApp, ignoreParser, additionalAppSettings); } } }
//接收数据线程函数 private void RecvFromBoard(object obj) { while (true) { try { var revBytes = _udpClient.Receive(ref _ipTargetEp); var header = GetHeaderFromBytes.GetHeader(revBytes); PublishHelper.PublishMsg($"udp-recv://{_prefix}", revBytes); } catch (SocketException e) { if (SocketError.Interrupted == e.SocketErrorCode) { break; } } } }
private void Bind_PublishContentStart() { if (modelTask.IsPublishContent == 1) { PublishHelper publich = new PublishHelper(); publich.ModelTask = modelTask; publich.PublishCompalteDelegate = GatherWorkDelegate; MessageOut("正在开始发布数据!"); publich.PublishCompalteDelegate = PublishCompalteDelegate; ThreadPool.QueueUserWorkItem(new WaitCallback(publich.Start)); } else { GatherComplateDelegate(modelTask); MessageOut("发布数据没有开启!不需要发布数据!"); this.Stop(); } }
/// <summary> /// Given a book, typically one in a temporary folder made just for exporting (or testing), /// and given the set of fonts found while creating that book and removing hidden elements, /// find the files needed for those fonts. /// Copy the font file for the normal style of that font family from the system font folder, /// if permitted; or post a warning in progress if we can't embed it. /// Create an extra css file (fonts.css) which tells the book to find the font files for those font families /// in the local folder, and insert a link to it into the book. /// </summary> /// <param name="fontFileFinder">use new FontFinder() for real, or a stub in testing</param> public static void EmbedFonts(Book.Book book, IWebSocketProgress progress, HashSet <string> fontsWanted, IFontFinder fontFileFinder) { const string defaultFont = "Andika New Basic"; // already in BR, don't need to embed or make rule. fontsWanted.Remove(defaultFont); PublishHelper.CheckFontsForEmbedding(progress, fontsWanted, fontFileFinder, out List <string> filesToEmbed, out HashSet <string> badFonts); foreach (var file in filesToEmbed) { // Enhance: do we need to worry about problem characters in font file names? var dest = Path.Combine(book.FolderPath, Path.GetFileName(file)); RobustFile.Copy(file, dest); } // Create the fonts.css file, which tells the browser where to find the fonts for those families. var sb = new StringBuilder(); foreach (var font in fontsWanted) { if (badFonts.Contains(font)) { continue; } var group = fontFileFinder.GetGroupForFont(font); if (group != null) { EpubMaker.AddFontFace(sb, font, "normal", "normal", group.Normal); } // We don't need (or want) a rule to use Andika instead. // The reader typically WILL use Andika, because we have a rule making it the default font // for the whole body of the document, and BloomReader always has it available. // However, it's possible that although we aren't allowed to embed the desired font, // the device actually has it installed. In that case, we want to use it. } RobustFile.WriteAllText(Path.Combine(book.FolderPath, "fonts.css"), sb.ToString()); // Tell the document to use the new stylesheet. book.OurHtmlDom.AddStyleSheet("fonts.css"); // Repair defaultLangStyles.css and other places in the output book if needed. if (badFonts.Any()) { PublishHelper.FixCssReferencesForBadFonts(book.FolderPath, defaultFont, badFonts); PublishHelper.FixXmlDomReferencesForBadFonts(book.OurHtmlDom.RawDom, defaultFont, badFonts); } }
/// <summary> /// Handler for Linux Consumption publish event /// </summary> /// <param name="functionAppRoot">Function App project path in local machine</param> /// <param name="functionApp">Function App in Azure</param> /// <param name="fileNameNoExtension">Name of the file to be uploaded</param> /// <returns>ShouldSyncTrigger value</returns> private async Task <bool> HandleLinuxConsumptionPublish(string functionAppRoot, Site functionApp, string fileNameNoExtension) { // Choose if the content need to use remote build BuildOption buildOption = PublishHelper.UpdateLinuxConsumptionBuildOption(PublishBuildOption); GitIgnoreParser ignoreParser = PublishHelper.GetIgnoreParser(functionAppRoot); // We update the buildOption, so we need to update the zipFileStream factory as well Func <Task <Stream> > zipFileStreamTask = () => ZipHelper.GetAppZipFile(functionAppRoot, BuildNativeDeps, buildOption, NoBuild, ignoreParser, AdditionalPackages, ignoreDotNetCheck: true); // Consumption Linux, try squashfs as a package format. if (GlobalCoreToolsSettings.CurrentWorkerRuntimeOrNone == WorkerRuntime.python && !NoBuild && (BuildNativeDeps || buildOption == BuildOption.Remote)) { if (BuildNativeDeps) { await PublishRunFromPackage(functionApp, await PythonHelpers.ZipToSquashfsStream(await zipFileStreamTask()), $"{fileNameNoExtension}.squashfs"); return(true); } // Remote build don't need sync trigger, container will be deallocated once the build is finished if (buildOption == BuildOption.Remote) { await RemoveFunctionAppAppSetting(functionApp, "WEBSITE_RUN_FROM_PACKAGE", "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING", "WEBSITE_CONTENTSHARE"); Task <DeployStatus> pollConsumptionBuild(HttpClient client) => KuduLiteDeploymentHelpers.WaitForConsumptionServerSideBuild(client, functionApp, AccessToken, ManagementURL); var deployStatus = await PerformServerSideBuild(functionApp, zipFileStreamTask, pollConsumptionBuild); return(deployStatus == DeployStatus.Success); } } else { await PublishRunFromPackage(functionApp, await zipFileStreamTask(), $"{fileNameNoExtension}.zip"); return(true); } return(true); }
public async Task PublishZipDeploy(Site functionApp, Func <Task <Stream> > zipFileFactory) { await RetryHelper.Retry(async() => { using (var handler = new ProgressMessageHandler(new HttpClientHandler())) using (var client = GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}"), handler)) using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri("api/zipdeploy", UriKind.Relative))) { request.Headers.IfMatch.Add(EntityTagHeaderValue.Any); ColoredConsole.WriteLine("Creating archive for current directory..."); (var content, var length) = CreateStreamContentZip(await zipFileFactory()); request.Content = content; HttpResponseMessage response = await PublishHelper.InvokeLongRunningRequest(client, handler, request, length, "Uploading"); await PublishHelper.CheckResponseStatusAsync(response, "uploading archive"); ColoredConsole.WriteLine("Upload completed successfully."); } }, 2); }
public async Task <DeployStatus> PerformServerSideBuild(Site functionApp, Func <Task <Stream> > zipFileFactory, Func <HttpClient, Task <DeployStatus> > deploymentStatusPollTask) { if (string.IsNullOrEmpty(functionApp.ScmUri)) { throw new CliException($"Remote build is a new feature added to function apps.{Environment.NewLine}" + $"Your function app {functionApp.SiteName} does not support remote build as it was created before August 1st, 2019.{Environment.NewLine}" + $"Please use '--build local', '--build-native-deps' or manually enable remote build.{Environment.NewLine}" + $"For more information, please visit https://aka.ms/remotebuild"); } using (var handler = new ProgressMessageHandler(new HttpClientHandler())) using (var client = GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}"), handler)) using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri( $"api/zipdeploy?isAsync=true&author={Environment.MachineName}", UriKind.Relative))) { ColoredConsole.WriteLine("Creating archive for current directory..."); request.Headers.IfMatch.Add(EntityTagHeaderValue.Any); (var content, var length) = CreateStreamContentZip(await zipFileFactory()); request.Content = content; HttpResponseMessage response = await PublishHelper.InvokeLongRunningRequest(client, handler, request, length, "Uploading"); await PublishHelper.CheckResponseStatusAsync(response, "Uploading archive..."); // Streaming deployment status for Linux Server Side Build DeployStatus status = await deploymentStatusPollTask(client); if (status == DeployStatus.Success) { ColoredConsole.WriteLine(Green("Remote build succeeded!")); } else if (status == DeployStatus.Failed) { throw new CliException("Remote build failed!"); } return(status); } }
public void SendHlMessageToUI(ScriptMessage inputMessage) { //作一个随机延时20ms~50ms TimeDelay(); //添加时间戳 inputMessage.time = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff"); string originUI = inputMessage.UI; //区分三类消息,对应于界面呈现使用 if (-1 != originUI.IndexOf("UE")) { inputMessage.NO = UENo++; inputMessage.UI = "UE"; string msg = JsonConvert.SerializeObject(inputMessage); PublishHelper.PublishMsg("HlSignalMsg", msg); //记录日志 logMsg.WriteLog(LogOfType.UE_MSGLOG, msg); } if (-1 != originUI.IndexOf("eNB")) { inputMessage.NO = eNBNo++; inputMessage.UI = "eNB"; string msg = JsonConvert.SerializeObject(inputMessage); PublishHelper.PublishMsg("HlSignalMsg", msg); //记录日志 logMsg.WriteLog(LogOfType.eNB_MSGLOG, msg); } if (-1 != originUI.IndexOf("gNB")) { inputMessage.NO = gNBNo++; inputMessage.UI = "gNB"; string msg = JsonConvert.SerializeObject(inputMessage); PublishHelper.PublishMsg("HlSignalMsg", msg); //记录日志 logMsg.WriteLog(LogOfType.gNB_MSGLOG, msg); } }
public async Task <DeployStatus> PerformServerSideBuild(Site functionApp, Func <Task <Stream> > zipFileFactory) { using (var handler = new ProgressMessageHandler(new HttpClientHandler())) using (var client = GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}"), handler)) using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri( $"api/zipdeploy?isAsync=true&author={Environment.MachineName}", UriKind.Relative))) { ColoredConsole.WriteLine("Creating archive for current directory..."); request.Headers.IfMatch.Add(EntityTagHeaderValue.Any); // Attach x-ms-site-restricted-token for Linux Consumption remote build string restrictedToken = await KuduLiteDeploymentHelpers.GetRestrictedToken(functionApp, AccessToken, ManagementURL); (var content, var length) = CreateStreamContentZip(await zipFileFactory()); request.Content = content; request.Headers.Add("x-ms-site-restricted-token", restrictedToken); HttpResponseMessage response = await PublishHelper.InvokeLongRunningRequest(client, handler, request, length, "Uploading"); await PublishHelper.CheckResponseStatusAsync(response, "uploading archive"); // Streaming deployment status for Linux Dynamic Server Side Build DeployStatus status = await KuduLiteDeploymentHelpers.WaitForServerSideBuild(client, functionApp, AccessToken, ManagementURL); if (status == DeployStatus.Success) { ColoredConsole.WriteLine(Green("Server side build succeeded!")); } else if (status == DeployStatus.Failed) { ColoredConsole.WriteLine(Red("Server side build failed!")); } return(status); } }
private async Task <IDictionary <string, string> > ValidateFunctionAppPublish(Site functionApp, WorkerRuntime workerRuntime) { var result = new Dictionary <string, string>(); // Check version if (!functionApp.IsLinux) { if (functionApp.AzureAppSettings.TryGetValue(Constants.FunctionsExtensionVersion, out string version)) { // v2 can be either "~2", "beta", or an exact match like "2.0.11961-alpha" if (!version.Equals("~2") && !version.StartsWith("2.0") && !version.Equals("beta", StringComparison.OrdinalIgnoreCase)) { if (Force) { result.Add(Constants.FunctionsExtensionVersion, "~2"); } else { throw new CliException("You're trying to publish to a non-v2 function app from v2 tooling.\n" + "You can pass --force to force update the app to v2, or switch to v1 or v3 tooling for publishing"); } } } } if (functionApp.AzureAppSettings.TryGetValue(Constants.FunctionsWorkerRuntime, out string workerRuntimeStr)) { var resolution = $"You can pass --force to update your Azure app with '{workerRuntime}' as a '{Constants.FunctionsWorkerRuntime}'"; try { var azureWorkerRuntime = WorkerRuntimeLanguageHelper.NormalizeWorkerRuntime(workerRuntimeStr); if (azureWorkerRuntime != workerRuntime) { if (Force) { ColoredConsole.WriteLine(WarningColor($"Setting '{Constants.FunctionsWorkerRuntime}' to '{workerRuntime}' because --force was passed")); result[Constants.FunctionsWorkerRuntime] = workerRuntime.ToString(); } else { throw new CliException($"Your Azure Function App has '{Constants.FunctionsWorkerRuntime}' set to '{azureWorkerRuntime}' while your local project is set to '{workerRuntime}'.\n" + resolution); } } } catch (ArgumentException) when(Force) { result[Constants.FunctionsWorkerRuntime] = workerRuntime.ToString(); } catch (ArgumentException) when(!Force) { throw new CliException($"Your app has an unknown {Constants.FunctionsWorkerRuntime} defined '{workerRuntimeStr}'. Only {WorkerRuntimeLanguageHelper.AvailableWorkersRuntimeString} are supported.\n" + resolution); } } if (!functionApp.AzureAppSettings.ContainsKey("AzureWebJobsStorage") && functionApp.IsDynamic) { throw new CliException($"'{FunctionAppName}' app is missing AzureWebJobsStorage app setting. That setting is required for publishing consumption linux apps."); } if (functionApp.IsLinux && !functionApp.IsDynamic && !string.IsNullOrEmpty(functionApp.LinuxFxVersion)) { // If linuxFxVersion does not match any of our images if (PublishHelper.IsLinuxFxVersionUsingCustomImage(functionApp.LinuxFxVersion)) { ColoredConsole.WriteLine($"Your functionapp is using a custom image {functionApp.LinuxFxVersion}.\nAssuming that the image contains the correct framework.\n"); } // If there the functionapp is our image but does not match the worker runtime image, we either fail or force update else if (!PublishHelper.IsLinuxFxVersionRuntimeMatched(functionApp.LinuxFxVersion, workerRuntime)) { if (Force) { var updatedSettings = new Dictionary <string, string> { [Constants.LinuxFxVersion] = $"DOCKER|{Constants.WorkerRuntimeImages.GetValueOrDefault(workerRuntime).FirstOrDefault()}" }; var settingsResult = await AzureHelper.UpdateWebSettings(functionApp, updatedSettings, AccessToken, ManagementURL); if (!settingsResult.IsSuccessful) { ColoredConsole.Error .WriteLine(ErrorColor("Error updating linux image version:")) .WriteLine(ErrorColor(settingsResult.ErrorResult)); } } else { throw new CliException($"Your Linux dedicated app has the container image version (LinuxFxVersion) set to {functionApp.LinuxFxVersion} which is not expected for the worker runtime {workerRuntime}. " + $"To force publish use --force. This will update your app to the expected image for worker runtime {workerRuntime}\n"); } } } return(result); }
/// <summary> /// gtsa发送过来的跟踪消息,直接publish /// </summary> /// <param name="msgData"></param> private void DealTraceMsg(byte[] msgData) { PublishHelper.PublishMsg("/GtsMsgParseService/GtsaSend", msgData); }
public void IsLinuxFxVersionRuntimeMatchedTest(string linuxFxVersion, WorkerRuntime runtime, bool expected) { Assert.Equal(expected, PublishHelper.IsLinuxFxVersionRuntimeMatched(linuxFxVersion, runtime)); }