public byte[] AddCode(CodePackage pkg) { //Load ZipTemplate file into Zip Stream string zipFilePath = Path.Combine(env.ContentRootPath, APP_DATA_FOLDER, ZIP_TEMPLATE_FILE); using (MemoryStream ms = new MemoryStream()) { var templateContent = File.ReadAllBytes(zipFilePath); ms.Write(templateContent, 0, templateContent.Length); using (var archive = new ZipArchive(ms, ZipArchiveMode.Update, true)) { //Write run.csx file into zip var codeEntry = archive.CreateEntry(FUNCTION_ZIP_FOLDER + @"/run.csx"); using (var writer = new StreamWriter(codeEntry.Open())) { writer.WriteLine(GetCodeFileHeader()); writer.WriteLine(); writer.Write(pkg.Code); } //Write DotNetFunction.dll into zip var binaryEntry = archive.CreateEntry(FUNCTION_ZIP_FOLDER + @"/DotNetFunction.dll"); using (var binStream = binaryEntry.Open()) { binStream.Write(pkg.OutputBinary, 0, pkg.OutputBinary.Length); } } ms.Flush(); return(ms.ToArray()); } }
private static unsafe void ParseCodePackages(NativeRuntime.IFabricCodePackageActivationContext nativeContext, ServiceManifest manifest) { IList <string> names = new List <string>(); NativeCommon.IFabricStringListResult nativeResult = nativeContext.GetCodePackageNames(); uint count; IntPtr nativeNames = nativeResult.GetStrings(out count); for (int i = 0; i < count; i++) { NativeRuntime.IFabricCodePackage codePackageResult = nativeContext.GetCodePackage(Marshal.ReadIntPtr((IntPtr)(nativeNames + i))); NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION nativeDescription = *(NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION *)(codePackageResult.get_Description()); NativeRuntime.IFabricCodePackage nativePackage = null; string packageName = NativeTypes.FromNativeString(nativeDescription.Name); using (var pin = new PinBlittable(packageName)) { nativePackage = nativeContext.GetCodePackage(pin.AddrOfPinnedObject()); } manifest.CodePackages.Add(CodePackage.CreateFromNative(nativePackage)); GC.KeepAlive(codePackageResult); } GC.KeepAlive(nativeResult); }
public override int GetHashCode() { int hash = 1; if (chaincodeSpec_ != null) { hash ^= ChaincodeSpec.GetHashCode(); } if (CodePackage.Length != 0) { hash ^= CodePackage.GetHashCode(); } if (ExecEnv != global::Protos.ChaincodeDeploymentSpec.Types.ExecutionEnvironment.Docker) { hash ^= ExecEnv.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public override int GetHashCode() { int hash = 1; if (chaincodeSpec_ != null) { hash ^= ChaincodeSpec.GetHashCode(); } if (effectiveDate_ != null) { hash ^= EffectiveDate.GetHashCode(); } if (CodePackage.Length != 0) { hash ^= CodePackage.GetHashCode(); } if (ExecEnv != 0) { hash ^= ExecEnv.GetHashCode(); } return(hash); }
public static void OnTimedEvent(object obj, ElapsedEventArgs args) { //Set run interval as 10 minutes serviceTimer.Interval = 600000; Logger.WriteInfo("OnTime event, start query active reviews"); try { _initMonitorUserList(); bool isNew = false; ReviewServiceClient client = new ReviewServiceClient(); GorillaWebAPI webapi = new GorillaWebAPI("CFMonitor", "User@123"); foreach (string username in _userlist) { if (!_MonitoredReviewDict.Keys.Contains(username)) { _MonitoredReviewDict.Add(username, new Dictionary <string, int>()); isNew = true; } //get all active reviews CodeReviewSummary[] reviews = client.GetActiveReviewsForAuthor(username); if (reviews != null) { //scan each review foreach (var codeReviewSummary in reviews) { _cfTrendStatus.AddReviewCount(codeReviewSummary.Author.Name); CodeReview r = client.GetReview(codeReviewSummary.Key); if (!_MonitoredReviewDict[username].Keys.Contains(r.Key)) { _MonitoredReviewDict[username].Add(r.Key, 0); //A new submit, add to today's total Review count _cfTrendStatus.AddReviewCount(r.Author.Name); isNew = true; } if (_MonitoredReviewDict[username][r.Key] < r.codePackages.Length) { isNew = true; } if (isNew) { for (int i = _MonitoredReviewDict[username][r.Key]; i < r.codePackages.Length; i++) { CodePackage pkg = r.codePackages[i]; #region Generate review string StringBuilder reviewers = new StringBuilder("<table><tr style=\"border: 1px solid; border-top: none; border-left: none;border-right: none;\"><td width=\"40%\"><b>Reviewer</b></td><td width=\"30%\"><b>Type</b></td><td width=\"30%\"><b>Status</b></td></tr>"); StringBuilder reviewerstr = new StringBuilder(); foreach (var reviewer in r.reviewers) { reviewers.Append(string.Format("<tr><td><b>{3}</b>({0})</td><td>{1}</td><td>{2}</td></tr>", reviewer.Name, reviewer.Required ? "<b>Required</b>" : "Optional", reviewer.Status == ReviewerStatus.SignedOff ? "<font color=\"green\">SignedOff</font>" : reviewer.Status.ToString(), reviewer.DisplayName)); reviewerstr.Append(string.Format(" @{0},", reviewer.Name.Substring(reviewer.Name.IndexOf('\\') + 1))); } reviewers.Append("</table>"); #endregion #region Generate changed file StringBuilder changedfiles = new StringBuilder("<table><tr style=\"border: 1px solid; border-top: none; border-left: none;border-right: none;\"><td width=\"50px\"><b>Change</b></td><td width=\"30%\"><b>Type</b></td><td><b>FilePath</b></td></tr>"); foreach (var file in pkg.FileChanges) { changedfiles.Append(string.Format("<tr><td><b>{0}</b></td><td>{1}</td></tr>", file.ChangeType, file.DepotFilePath)); } changedfiles.Append("</table>"); string description = pkg.Description; string newDescription = description; string pat = @"(\d{4,})"; #endregion #region replace tfs number with topic // Instantiate the regular expression object. Regex reg = new Regex(pat, RegexOptions.IgnoreCase); // Match the regular expression pattern against a text string. Match m = reg.Match(description); List <string> replacedValueList = new List <string>(); while (m.Success) { //Console.WriteLine("Match" + (++matchCount)); if (!replacedValueList.Contains(m.Value)) { newDescription = newDescription.Replace(m.Value, string.Format(" #WOSS TFS {0}# ", m.Value)); replacedValueList.Add(m.Value); } m = m.NextMatch(); } #endregion string title = string.Format("Code Review: ({0}){1}", pkg.Author.Substring(pkg.Author.IndexOf('\\') + 1), r.Name); #region Iteration Title string iteration = ""; if (i == 0) { iteration = "New review submitted"; } else if (string.IsNullOrEmpty(r.CompletionMessage)) { iteration = "Author started new iteration"; } else { iteration = "Review completed"; } #endregion string link = "http://codeflow/Client/CodeFlow2010.application?server=http://codeflow/Services/DiscoveryService.svc&review=" + codeReviewSummary.Key; string richMessage = string.Format("<h3>{0}</h3><br/><h4><b>{1}</b></h4><br/><b>Open in: [<a href=\"{2}\">CodeFlow</a>]</b><br/><b>Author: {3}</b><br/>{4}<br/><b>Description:</b><br/>{5}<br/><h4><b>Affected Files</b></h4>{6}", title, iteration, link, pkg.Author, reviewers.ToString(), pkg.Description.Trim(), changedfiles.ToString()); string message = string.Format("#WOSS Codeflow# {0}\nIteration {2} {4}\nAuthor: {1}\nReviewer: {3}\n#WOSS Change {5}#\nReview: {6}", newDescription.Trim(), pkg.Author.Substring(pkg.Author.IndexOf('\\') + 1), pkg.Revision, reviewerstr.ToString().TrimEnd(new char[] { ',' }), pkg.IterationComment, pkg.SourceInfo.SourceName, link); Logger.WriteInfo(message); webapi.PostMessage(message, null, "none", r.Key, new string[] { "WOSS Codeflow" }, new string[] { pkg.Author.Substring(pkg.Author.IndexOf('\\') + 1) }, new string[] { }, richMessage); } _MonitoredReviewDict[username][r.Key] = r.codePackages.Length; } else { Logger.WriteInfo("no new reviews for user " + username); } } } } } catch (Exception e) { Logger.WriteInfo("Exception happened, try get the codeflow info in next run"); Logger.WriteInfo(e.Message); } //Check wether it's time to send trend data if (DateTime.Now.TimeOfDay > new TimeSpan(23, 30, 0)) { if (!_isTrendStatusSend) { GorillaWebAPI webapi = new GorillaWebAPI("CFMonitor", "User@123"); if (DateTime.Now.DayOfWeek == DayOfWeek.Friday) { var winner = _cfTrendStatus.ReviewCountPeople.OrderByDescending(p => p.Value).First(); string winnerThisWeek = string.Format("This Week's CodeFlow winner is @{0}, who submitted {1} CodeReviews!!!", winner.Key, winner.Value); webapi.PostMessage(winnerThisWeek, null, "none", "none", new string[] { "WOSS CodeFlow" }); } StringBuilder dailyTrendValue = new StringBuilder(); foreach (var value in _cfTrendStatus.ReviewCountHistory.OrderBy(t => t.Key).Select(t => t.Value)) { dailyTrendValue.AppendFormat("{0},", value); } string dTrendValue = dailyTrendValue.ToString().TrimEnd(','); StringBuilder dailyTrendDate = new StringBuilder(); foreach (var value in _cfTrendStatus.ReviewCountHistory.OrderBy(t => t.Key).Select(t => t.Key)) { dailyTrendDate.AppendFormat("'{0}',", value.ToShortDateString()); } string dTrendDate = dailyTrendDate.ToString().TrimEnd(','); string dailyTrend = string.Format("{{title:'WOSS Daily New CodeReview Number',legend:['New CodeRview Number'],xAxis:[{0}],yAxis:[{{name:'New CodeRview Number',type:'line',data:[{1}]}}]}}", dTrendDate, dTrendValue); webapi.PostMessage(dailyTrend, null, "chart-axis-singleaxis", "none", new string[] { "WOSS CodeFlow" }); _isTrendStatusSend = true; } } if (DateTime.Now.TimeOfDay < new TimeSpan(23, 00, 0)) { _isTrendStatusSend = false; } _recordMonitorStatus(); }
public static int Main(string[] args) { FabricEvents.ExtensionsEvents traceSource = new FabricEvents.ExtensionsEvents(FabricEvents.Tasks.BackupRestoreService); int status = 0; var codePackageActivationContext = FabricRuntime.GetActivationContext(); var configStore = NativeConfigStore.FabricGetConfigStore(); var serverAuthCredentialTypeName = configStore.ReadUnencryptedString(BackupRestoreContants.SecurityConfigSectionName, BackupRestoreContants.ServerAuthCredentialTypeName); var serverAuthCredentialType = CredentialType.None; EndpointResourceDescription endpoint = null; try { endpoint = codePackageActivationContext.GetEndpoint(BackupRestoreContants.RestEndPointName); } catch (FabricElementNotFoundException) { traceSource.WriteWarning(TraceType, "Endpoint not found for EndpointName{0}", BackupRestoreContants.RestEndPointName); throw; } if (!string.IsNullOrEmpty(serverAuthCredentialTypeName) && !Enum.TryParse(serverAuthCredentialTypeName, out serverAuthCredentialType)) { traceSource.WriteWarning(TraceType, "Unable to convert configuration value serverAuthCredentialTypeName {0} for {1} type.", serverAuthCredentialTypeName, serverAuthCredentialType); } if (serverAuthCredentialType == CredentialType.X509 || serverAuthCredentialType == CredentialType.Claims) { // Get server auth details var aclServerAuthX509StoreName = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509StoreName); var aclCertValueFindTypeName = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509FindType); var aclCertValue = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509FindValue); var aclCertValueSecondary = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeConfigSectionName, BackupRestoreContants.ServerAuthX509FindValueSecondary); var storeName = StoreName.My; var x509FindType = X509FindType.FindByThumbprint; X509Certificate2 certificate = null; if (!string.IsNullOrEmpty(aclServerAuthX509StoreName) && !Enum.TryParse(aclServerAuthX509StoreName, out storeName)) { traceSource.WriteWarning(TraceType, "Unable to Convert configuration aclServerAuthX509StoreName value {0} for {1} type.", aclServerAuthX509StoreName, storeName.GetType().ToString()); throw new InvalidEnumArgumentException(string.Format("Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType())); } if (!string.IsNullOrEmpty(aclCertValueFindTypeName) && !Enum.TryParse(aclCertValueFindTypeName, out x509FindType)) { traceSource.WriteWarning(TraceType, "Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType().ToString()); throw new InvalidEnumArgumentException(string.Format("Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType())); } if (!string.IsNullOrWhiteSpace(aclCertValue)) { // Get certificate. var store = new X509Store(storeName, StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadOnly); traceSource.WriteInfo( TraceType, "Finding applicable certificate for Acling. StoreName: {0}, StoreLocation: LocalMachine, X509FindType: {1}, X509FindValue: {2}.", storeName, x509FindType, aclCertValue); var certCollections = store.Certificates.Find(x509FindType, aclCertValue, false /*load self-signed cert*/); if (certCollections.Count > 0) { certificate = certCollections[0]; } else if (!string.IsNullOrWhiteSpace(aclCertValueSecondary)) { traceSource.WriteInfo( TraceType, "Finding applicable certificate for Acling using Secondary cert config. StoreName: {0}, StoreLocation: LocalMachine, X509FindType: {1}, X509FindValue: {2}.", storeName, x509FindType, aclCertValueSecondary); var certCollectionsSecondary = store.Certificates.Find(x509FindType, aclCertValueSecondary, false /*load self-signed cert*/); if (certCollectionsSecondary.Count > 0) { certificate = certCollectionsSecondary[0]; } } else { traceSource.WriteWarning(TraceType, "No matching certificate found. Thumbprint value: {0}, StoreName: {1}, StoreLocation: {2}", aclCertValue, aclServerAuthX509StoreName, StoreLocation.LocalMachine); } } finally { store.Close(); } } else { traceSource.WriteWarning(TraceType, "Invalid configuration for certificate. Thumbprint value: {0}, StoreName: {1}, StoreLocation: {2}", aclCertValue, aclServerAuthX509StoreName, StoreLocation.LocalMachine); } if (certificate != null) { PortAclUtility.BindCertificate(endpoint.IpAddressOrFqdn, endpoint.Port, certificate.GetCertHash()); } } // Do URL ACLing CodePackage codePackage = codePackageActivationContext.GetCodePackageObject("Code"); string daclString = "D:(A;;GX;;;NS)"; try { var runAsAccountName = configStore.ReadUnencryptedString(BackupRestoreContants.FabricNodeRunAsSectionName, BackupRestoreContants.RunAsAccountNameConfig); if (!string.IsNullOrEmpty(runAsAccountName)) { traceSource.WriteInfo(TraceType, "runAsAccountName for ACLing: {0} for CredentialType Windows", runAsAccountName); daclString = GetAllowDaclFromUserName(runAsAccountName); } } catch (IdentityNotMappedException ex) { traceSource.WriteWarning(TraceType, "Failed to resolve NTAccount: {0}, Exception: {1}", codePackage.EntryPointRunAsPolicy.UserName, ex); throw; } catch (SystemException ex) { traceSource.WriteWarning(TraceType, "Failed to resolve NTAccount: {0}, Exception: {1}", codePackage.EntryPointRunAsPolicy.UserName, ex); throw; } var fabricBrsSecuritySetting = SecuritySetting.GetClusterSecurityDetails(); var listeningAddress = String.Format(CultureInfo.InvariantCulture, "{0}://+:{1}/", fabricBrsSecuritySetting.EndpointProtocol, endpoint.Port); traceSource.WriteInfo(TraceType, "ListeningAddress: {0} ,DaclString: {1} for ACLing", listeningAddress, daclString); PortAclUtility.ReserveUrl(listeningAddress, daclString); return(status); }
/// <summary> /// Step 2.2 - Add code package to review. /// </summary> /// <param name="client">An instance of <see cref="ReviewServiceClient" />.</param> /// <param name="reviewId">Id of the review to be added.</param> /// <param name="codePackage">Code package to be added.</param> public static void AddCodePackage(ReviewServiceClient client, string reviewId, CodePackage codePackage) { client.AddCodePackage(reviewId, codePackage); }
public static int Main(string[] args) { var codePackageActivationContext = FabricRuntime.GetActivationContext(); var configStore = NativeConfigStore.FabricGetConfigStore(); var serverAuthCredentialTypeName = configStore.ReadUnencryptedString(SecurityConfigSectionName, ServerAuthCredentialTypeName); var serverAuthCredentialType = CredentialType.None; EndpointResourceDescription endpoint = null; try { endpoint = codePackageActivationContext.GetEndpoint(EventStoreServiceRESTEndpoint); } catch (FabricElementNotFoundException) { Console.WriteLine("Endpoint not found for EndpointName{0}", EventStoreServiceRESTEndpoint); throw; } if (!string.IsNullOrEmpty(serverAuthCredentialTypeName) && !Enum.TryParse(serverAuthCredentialTypeName, out serverAuthCredentialType)) { Console.WriteLine("Unable to convert configuration value serverAuthCredentialTypeName {0} for {1} type.", serverAuthCredentialTypeName, serverAuthCredentialType); } if (serverAuthCredentialType == CredentialType.X509 || serverAuthCredentialType == CredentialType.Claims) { var aclServerAuthX509StoreName = configStore.ReadUnencryptedString(FabricNodeConfigSectionName, ServerAuthX509StoreName); var aclCertValueFindTypeName = configStore.ReadUnencryptedString(FabricNodeConfigSectionName, ServerAuthX509FindType); var aclCertValue = configStore.ReadUnencryptedString(FabricNodeConfigSectionName, ServerAuthX509FindValue); var aclCertValueSecondary = configStore.ReadUnencryptedString(FabricNodeConfigSectionName, ServerAuthX509FindValueSecondary); var storeName = StoreName.My; var x509FindType = X509FindType.FindByThumbprint; X509Certificate2 certificate = null; if (!string.IsNullOrEmpty(aclServerAuthX509StoreName) && !Enum.TryParse(aclServerAuthX509StoreName, out storeName)) { Console.WriteLine("Unable to Convert configuration aclServerAuthX509StoreName value {0} for {1} type.", aclServerAuthX509StoreName, storeName.GetType().ToString()); throw new InvalidEnumArgumentException(string.Format("Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType())); } if (!string.IsNullOrEmpty(aclCertValueFindTypeName) && !Enum.TryParse(aclCertValueFindTypeName, out x509FindType)) { Console.WriteLine("Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType().ToString()); throw new InvalidEnumArgumentException(string.Format("Unable to Convert configuration aclCertValueFindTypeName value {0} for {1} type.", aclServerAuthX509StoreName, x509FindType.GetType())); } if (!string.IsNullOrWhiteSpace(aclCertValue)) { // Get certificate. var store = new X509Store(storeName, StoreLocation.LocalMachine); try { store.Open(OpenFlags.ReadOnly); var certCollections = store.Certificates.Find(x509FindType, aclCertValue, false /*load self-signed cert*/); if (certCollections.Count > 0) { certificate = certCollections[0]; } else if (!string.IsNullOrWhiteSpace(aclCertValueSecondary)) { var certCollectionsSecondary = store.Certificates.Find(x509FindType, aclCertValueSecondary, false /*load self-signed cert*/); if (certCollectionsSecondary.Count > 0) { certificate = certCollectionsSecondary[0]; } } else { Console.WriteLine("No matching certificate found. Thumbprint value: {0}, StoreName: {1}, StoreLocation: {2}", aclCertValue, aclServerAuthX509StoreName, StoreLocation.LocalMachine); } } finally { store.Close(); } } else { Console.WriteLine("Invalid configuration for certificate. Thumbprint value: {0}, StoreName: {1}, StoreLocation: {2}", aclCertValue, aclServerAuthX509StoreName, StoreLocation.LocalMachine); } if (certificate != null) { PortAclUtility.BindCertificate(endpoint.IpAddressOrFqdn, endpoint.Port, certificate.GetCertHash()); } } // Do URL ACLing CodePackage codePackage = codePackageActivationContext.GetCodePackageObject("Code"); string daclString = "D:(A;;GX;;;NS)"; if (!string.IsNullOrEmpty(codePackage.EntryPointRunAsPolicy?.UserName)) { try { NTAccount entryPointRunAsUser = new NTAccount(codePackage.EntryPointRunAsPolicy.UserName); SecurityIdentifier entryPointRunAsUserSid = (SecurityIdentifier)entryPointRunAsUser.Translate(typeof(SecurityIdentifier)); daclString = GetAllowDacl(entryPointRunAsUserSid); } catch (IdentityNotMappedException ex) { Console.WriteLine("Failed to resolve NTAccount: {0}, Exception: {1}", codePackage.EntryPointRunAsPolicy.UserName, ex); throw; } catch (SystemException ex) { Console.WriteLine("Failed to resolve NTAccount: {0}, Exception: {1}", codePackage.EntryPointRunAsPolicy.UserName, ex); throw; } } var listeningAddress = String.Format( CultureInfo.InvariantCulture, "{0}://+:{1}/", serverAuthCredentialType == CredentialType.X509 || serverAuthCredentialType == CredentialType.Claims ? "https" : "http", endpoint.Port); PortAclUtility.ReserveUrl(listeningAddress, daclString); return(0); }