private static void MinimumAspDotNet4onIIS6ConfigExample(MsgOut msgOut) { string serverComment = "zzz"; string path = @"C:\Inetpub\zzz"; string serverBindings = "http::80:zzz.contoso.com;https::443:zzz.contoso.com"; string appPool = "DotNet4AppPool"; Directory.CreateDirectory(path); IISSite site = IIS.Tools.CreateNewSite(new IISServerCommentIdentifier(serverComment), serverBindings, path); site.SetBindings(serverBindings); site.DefaultDoc = "index.aspx"; site.AccessFlags = AccessFlags.AccessRead | AccessFlags.AccessExecute; site.AuthFlags = AuthFlags.AuthNTLM | AuthFlags.AuthAnonymous; site.AppPoolId = appPool; site.SetASPDotNetVersion(AspDotNetVersion.AspNetV4); try { site.Start(); } catch (Exception exp) { msgOut(exp.Message); } }
private void Sub1Handler(MsgOut m, CancellationToken token) { Console.WriteLine("Sub1 received: " + m.GetPayloadAsString()); Debug.Assert(m.GetPayloadAsString() == TestPayload); //releases the semaphore _sem1.Release(); }
private async Task Sub2HandlerAsync(MsgOut m, CancellationToken token) { Console.WriteLine("Sub2 (async) received: " + m.GetPayloadAsString()); Debug.Assert(m.GetPayloadAsString() == TestPayload); //releases the semaphore _sem2.Release(); await Task.CompletedTask; }
/// <summary> /// Processes the <see cref="MsgOut"/> as just received from the <see cref="Parser"/>. /// </summary> /// <param name="message"></param> internal override void ProcessMessage( MsgOut message ) { //extract the request-ID from the message's subject long reqId = Converters.StringToInt64(message.Subject.ToCharArray(), this.Subject.Length - 1); //dispatches the message back to the reqest-reply manager this._feedback.ProcessMessage(message, reqId); }
public async Task PassiveWorkerAsync() { while (this._n < this._ctx.LoopCount) { MsgOut m = await this._subPassive.NextMessageAsync(CancellationToken.None); bool match = this._ctx.DeserializeAndCheckSimpleJson(m.GetPayloadAsByteArray(), this._n); Debug.Assert(match); ++_n; } }
private void ReactiveListener(MsgOut message, CancellationToken token) { bool match = this._ctx.DeserializeAndCheckSimpleJson(message.GetPayloadAsByteArray(), this._n); Debug.Assert(match); ++_n; if (this._n >= this._ctx.LoopCount) { this._cde.Signal(); } }
public void PassiveWorker(object state) { while (this._n < this._ctx.LoopCount) { MsgOut m = this._subPassive.NextMessage(CancellationToken.None); bool match = this._ctx.DeserializeAndCheckSimpleJson(m.GetPayloadAsByteArray(), this._n); Debug.Assert(match); ++_n; } this._cde.Signal(); }
void IReqRepImpl.SlaveEndPointWorker(SlaveClientContext ctx) { var conn = (IConnection)ctx.Connection; var sub = (IPassiveSubscription)ctx.Subscription; while (ctx.IsComplete == false) { MsgOut m = sub.NextMessage(CancellationToken.None); ISlaveEndPoint ep = ctx.EndPoints[m.Subject]; var segment = ep.GetResponse(m.GetPayloadAsByteArray()); ctx.AddBytes(m.PayloadLength + segment.Count); conn.Publish( new MsgIn(m.ReplyTo).SetPayload(segment), CancellationToken.None ); } }
/// <summary> /// The async-way subscriber /// </summary> /// <returns></returns> private async Task SubscriberAsync() { ClientOptions opts = ConnectionUtils.GetDefaultOptions(); ConnectionFactory cf = new ConnectionFactory(); using (IConnection conn = cf.CreateConnection(opts)) { //subscribe to the subject IPassiveSubscription sub = conn.SubscribePassive("The.>"); //waits the message MsgOut m = await sub.NextMessageAsync(CancellationToken.None); //verify the expectation Console.WriteLine("Async received: " + m.GetPayloadAsString()); Debug.Assert(m.GetPayloadAsString() == TestPayload); } }
private void Master() { ClientOptions opts = ConnectionUtils.GetDefaultOptions(); ConnectionFactory cf = new ConnectionFactory(); using (IConnection conn = cf.CreateConnection(opts)) { //sends a request and waits for the response MsgOut m = conn.Request( new MsgIn("The.Target").SetPayload("Mario"), TimeSpan.FromSeconds(1), CancellationToken.None ); Console.WriteLine("Master received: " + m.GetPayloadAsString()); Debug.Assert(m.GetPayloadAsString() == this._expectedResponsePayload); } }
private void SubscriberSync() { ClientOptions opts = ConnectionUtils.GetDefaultOptions(); ConnectionFactory cf = new ConnectionFactory(); using (IConnection conn = cf.CreateConnection(opts)) { IPassiveSubscription sub = conn.SubscribePassive("The.>"); //instructs the subscriber to self-destroy after //exactly MessageCount messages sub.AutoUnsubscribe(MessageCount); int count = MessageCount; while (sub.IsValid) { try { //waits for the next message MsgOut m = sub.NextMessage(CancellationToken.None); Console.WriteLine("Sync received: " + m.GetPayloadAsString()); Debug.Assert(m.GetPayloadAsString() == TestPayload); } catch (NATSBadSubscriptionException) { //that should be raised by the subscriber, //because the current thread is stick to NextMessage method //but the subscription is actually being disposed break; } catch { //any other exception should be thrown elsewhere throw; } count--; } Console.WriteLine("Unsubscribed"); Debug.Assert(count == 0); } }
private void Slave() { ClientOptions opts = ConnectionUtils.GetDefaultOptions(); ConnectionFactory cf = new ConnectionFactory(); using (IConnection conn = cf.CreateConnection(opts)) { IPassiveSubscription sub = conn.SubscribePassive("The.>"); //waits for a request MsgOut m = sub.NextMessage(CancellationToken.None); Console.WriteLine("Slave received: " + m.GetPayloadAsString()); //builds the response up, then publish it back as reply this._expectedResponsePayload = "Hello " + m.GetPayloadAsString() + "!"; conn.Publish( new MsgIn(m.ReplyTo).SetPayload(this._expectedResponsePayload), CancellationToken.None ); } }
void IReqRepImpl.MasterEndPointWorker(object state) { var ep = (IMasterEndPoint)state; var conn = (IConnection)ep.MasterClient.Connection; int n = ep.MasterClient.LoopCount; while (--n >= 0) { if (n == 0) { ep.Release(); } var segment = ep.GetRequest(); MsgOut m = conn.Request( new MsgIn(ep.TargetSubject).SetPayload(segment), RequestTimeout, CancellationToken.None ); ep.ValidateResponse(m.GetPayloadAsByteArray()); } }
private void SubscriberSync() { ClientOptions opts = ConnectionUtils.GetDefaultOptions(); ConnectionFactory cf = new ConnectionFactory(); using (IConnection conn = cf.CreateConnection(opts)) { IPassiveSubscription sub = conn.SubscribePassive("The.>"); //waits for a message MsgOut m = sub.NextMessage(CancellationToken.None); Console.WriteLine("Sync received: " + m.GetPayloadAsString()); Debug.Assert(m.GetPayloadAsString() == TestPayload); //unsubscribes the subject sub.Unsubscribe(); Task.Delay(1000).Wait(); //releases the semaphore this._sem.Release(); } }
private static void MinimumAspDotNet4onIIS6ConfigExample(MsgOut msgOut) { string serverComment = "zzz"; string path = @"C:\Inetpub\zzz"; string serverBindings = "http::80:zzz.contoso.com;https::443:zzz.contoso.com"; string appPool = "DotNet4AppPool"; Directory.CreateDirectory(path); IISSite site = IIS.Tools.CreateNewSite(new IISServerCommentIdentifier(serverComment), serverBindings, path); site.SetBindings(serverBindings); site.DefaultDoc = "index.aspx"; site.AccessFlags = AccessFlags.AccessRead | AccessFlags.AccessExecute; site.AuthFlags = AuthFlags.AuthNTLM | AuthFlags.AuthAnonymous; site.AppPoolId = appPool; site.SetASPDotNetVersion(AspDotNetVersion.AspNetV4); try { site.Start(); } catch (Exception exp) { msgOut(exp.Message); } }
private static async Task GeocodeAddress(TDayAddress addr, ConcurrentBag <TDayAddress> goodAddr, ConcurrentBag <TDayAddress> badAddr, MsgOut msgOut) { var bingKey = "Aq03fYCDuaMZk0OxpH97nxHInqIsJDzab90p3twCHCk8CvlRoKjB4Xs5Msbgsvq6"; // ServiceManager.Proxy = new WebProxy("http://proxy.research.ge.com:80/"); var request = new GeocodeRequest() { Query = addr.ToAddress(), IncludeIso2 = true, IncludeNeighborhood = true, MaxResults = 25, BingMapsKey = bingKey }; //Process the request by using the ServiceManager. var response = await request.Execute(); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { Location foundAddr = null; foreach (var res in response.ResourceSets[0].Resources) { if (((Location)res).Address.AdminDistrict == "NY" && ((Location)res).Address.PostalCode != null && ((Location)res).Address.PostalCode.StartsWith("12")) { foundAddr = (Location)res; break; } } //var result = response.ResourceSets[0].Resources[0] as Location; if (foundAddr != null && foundAddr.MatchCodes[0].ToString() == "Good") { addr.Address1 = foundAddr.Address.AddressLine; addr.City = foundAddr.Address.Locality; addr.State = foundAddr.Address.AdminDistrict; addr.Zip = foundAddr.Address.PostalCode; var coords = foundAddr.Point.Coordinates; if (coords != null && coords.Length == 2) { addr.Lat = (float)coords[0]; addr.Lon = (float)coords[1]; } goodAddr.Add(addr); } else { badAddr.Add(addr); } //msgOut($"Geocode: {addr} => Results - Code: {result.MatchCodes[0]}\r"); } }
public static void GenerateRoutes(IEnumerable <TDayAddress> records, string outDir, MsgOut msgOut) { int delivertCnt = 0; // create a QuadTree and fill it with objects var quadTree = new QuadTree <TDayAddress>(-80F, 35, 10, 10, new MyPolygonBounds(), 6, 14); //quadTree.InsertRange(records); // "myPolygons" are an array of all your objects using (StreamWriter ew = new StreamWriter(Path.Combine(outDir, "DeliveriesErrors.txt"))) { foreach (var obj in records) { if (!quadTree.Insert(obj)) { ew.WriteLine($"Where the heck: {obj.FirstName} {obj.LastName}, {obj.City} {obj.State} {obj.Zip} "); // throw new ApplicationException("Failed insert"); } else { delivertCnt++; } } } msgOut($"Inserted {delivertCnt} into delivery scheduler\n"); delivertCnt = 0; Dictionary <int, TDayAddress[]> grids = new Dictionary <int, TDayAddress[]>(); StreamWriter sw = new StreamWriter(Path.Combine(outDir, "Deliveries.txt")); quadTree.GetDeliveries(grids); //string jsonString = JsonSerializer.Serialize(grids); foreach (KeyValuePair <int, TDayAddress[]> delivery in grids) { //msgOut($"DeliverID: {delivery.Key}: with {delivery.Value.Length} stops: "); sw.WriteLine($"DeliverID: {delivery.Key} with {delivery.Value.Length} stops: "); foreach (var res in delivery.Value) { //msgOut($"\t Delivery: {res.ToString()}"); sw.WriteLine($"\t Delivery: {res.ToString().Replace(",","|")}"); delivertCnt++; } // do something with entry.Value or entry.Key } msgOut($"Scheduled {delivertCnt} deliveries\n"); sw.WriteLine($"Scheduled {delivertCnt} deliveries"); sw.Close(); // find the intersecting objects among the nearest // bool IsIntersect(Point[] obj1, Point[] obj2) is your function for checking intersections //var intersectingObjects = nearestObjects.Where(nearest => IsIntersect(nearest, myPolygon); }
private static void GeocodeAddressGoogle(TDayAddress addr, ConcurrentBag <TDayAddress> goodAddr, ConcurrentBag <TDayAddress> badAddr, MsgOut msgOut) { string YOUR_API_KEY = "AIzaSyDSyz9RnSKz7AMs_EQhDVhpXvuhHmyDTGc"; string address = addr.ToAddress(); string requestUri = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?key={1}&address={0}&sensor=false", Uri.EscapeDataString(address), YOUR_API_KEY); WebRequest request = WebRequest.Create(requestUri); WebResponse response = request.GetResponse(); XDocument xdoc = XDocument.Load(response.GetResponseStream()); addr.Restaurant = GetRestaurant(addr.Zip); if (xdoc.Element("GeocodeResponse").Element("status").Value == "OK") { XElement result = xdoc.Element("GeocodeResponse").Element("result"); string [] vals = result.Element("formatted_address").ToString().Split(','); string[] tmp = vals[2].TrimStart(' ').Split(' '); vals[2] = tmp[0]; vals[3] = tmp[1]; //msgOut($"Addr: {addr.ToAddress()} Return: {addrFormat.ToString()}"); if (vals[3] != addr.Zip) { msgOut($"Changed zip: {addr.ToAddress()} => {result.Element("formatted_address").ToString()}"); } XElement locationElement = result.Element("geometry").Element("location"); addr.Address1 = vals[0]; addr.City = vals[1]; addr.State = vals[2]; addr.Zip = vals[3]; addr.Lat = float.Parse(locationElement.Element("lat").Value); addr.Lon = float.Parse(locationElement.Element("lng").Value); goodAddr.Add(addr); } else { badAddr.Add(addr); } }
private static async Task GeocodeAddress(TDayAddress addr, ConcurrentBag <TDayAddress> goodAddr, ConcurrentBag <TDayAddress> badAddr, MsgOut msgOut) { var bingKey = "Aq4xnynDuADw0OMoyrHEvCrM8VqhI8HlGIusrLdL30LGJBz71X9JtUCMcVU6mj7Y"; // ServiceManager.Proxy = new WebProxy("http://proxy.research.ge.com:80/"); var request = new GeocodeRequest() { Query = addr.ToAddress(), IncludeIso2 = true, IncludeNeighborhood = true, MaxResults = 25, BingMapsKey = bingKey }; //Process the request by using the ServiceManager. var response = await request.Execute(); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { Location foundAddr = null; foreach (var res in response.ResourceSets[0].Resources) { if (((Location)res).Address.AdminDistrict == "NY" && ((Location)res).Address.PostalCode != null && ((Location)res).Address.PostalCode.StartsWith("12")) { foundAddr = (Location)res; //if (((Location)res).Address.PostalCode != addr.Zip) //{ // msgOut($"Changed zip: {addr.ToAddress()} {foundAddr.Address.FormattedAddress}"); //} break; } } //var result = response.ResourceSets[0].Resources[0] as Location; addr.Restaurant = GetRestaurant(addr.Zip); if (foundAddr != null && foundAddr.MatchCodes[0].ToString() == "Good") { //addr.Address1 = foundAddr.Address.AddressLine; //addr.City = foundAddr.Address.Locality; //addr.State = foundAddr.Address.AdminDistrict; //addr.Zip = foundAddr.Address.PostalCode; var coords = foundAddr.Point.Coordinates; if (coords != null && coords.Length == 2) { addr.Lat = (float)coords[0]; addr.Lon = (float)coords[1]; } goodAddr.Add(addr); } else { badAddr.Add(addr); } //msgOut($"Geocode: {addr} => Results - Code: {result.MatchCodes[0]}\r"); } }
public static void ReadExcelFile(string excelFile, string outPath, ConcurrentBag <TDayAddress> goodAddr, ConcurrentBag <TDayAddress> badAddr, MsgOut msgOut) { using (var stream = File.Open(excelFile, FileMode.Open, FileAccess.Read)) { using (var reader = ExcelReaderFactory.CreateReader(stream)) { var dataSet = reader.AsDataSet(); // Now you can get data from each sheet by its index or its "name" var dataTable = dataSet.Tables[0]; int numCPU = 10; // Environment.ProcessorCount * 2; msgOut($"Processing on {numCPU} threads\n"); Parallel.ForEach(dataTable.Rows.OfType <DataRow>(), new ParallelOptions { MaxDegreeOfParallelism = numCPU }, (Row) => { DoGeocode(goodAddr, badAddr, msgOut, Row, dataTable.Rows.Count); }); // Write out the addresses using (var writer = new StreamWriter(outPath + "_GoodAddresses.csv")) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(goodAddr); } using (var writer = new StreamWriter(outPath + "_BadAddresses.csv")) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(badAddr); } msgOut($"\nData written to {outPath + @"_GoodAddresses.csv"} and {outPath + @"_Badddresses.csv"}"); } } }
public static void ReadExcelFile(string excelFile, string outDir, ConcurrentBag <TDayAddress> goodAddr, ConcurrentBag <TDayAddress> badAddr, MsgOut msgOut) { using (var stream = File.Open(excelFile, FileMode.Open, FileAccess.Read)) { using (var reader = ExcelReaderFactory.CreateReader(stream)) { var dataSet = reader.AsDataSet(); // Now you can get data from each sheet by its index or its "name" var dataTable = dataSet.Tables[0]; int numCPU = Environment.ProcessorCount / 2; msgOut($"Processing on {numCPU} threads\n"); Parallel.ForEach(dataTable.Rows.OfType <DataRow>(), new ParallelOptions { MaxDegreeOfParallelism = numCPU }, (Row) => { // tblRecipient_Address, tblRecipient_Address1, tblRecipient_City, tblRecipient_State, tblRecipient_PostalCode TDayAddress addr = new TDayAddress() { FirstName = EatTheDamReturns(Row[0].ToString().Replace(",", " ")), LastName = EatTheDamReturns(Row[1].ToString().Replace(",", " ")), Address1 = EatTheDamReturns(Row[2].ToString().Replace(",", " ")), AptNum = EatTheDamReturns(Row[3].ToString().Replace(",", " ")), Address2 = EatTheDamReturns(Row[4].ToString().Replace(",", " ")), City = EatTheDamReturns(Row[5].ToString().Replace(",", " ")), State = EatTheDamReturns(Row[6].ToString().Replace(",", " ")), Zip = EatTheDamReturns(Row[7].ToString()), HomePhone = EatTheDamReturns(Row[8].ToString()), CellPHone = EatTheDamReturns(Row[9].ToString()), DelDay = EatTheDamReturns(Row[10].ToString()), NumMeals = 0, Notes = EatTheDamReturns(Row[12].ToString()) }; int numMeals = 0; if (int.TryParse(Row[11].ToString(), out numMeals)) { addr.NumMeals = numMeals; //msgOut.WriteLine(addr); GeocodeAddress(addr, goodAddr, badAddr, msgOut).Wait(); } msgOut($"Procesed count: {goodAddr.Count + badAddr.Count}\r"); }); // Write out the addresses using (var writer = new StreamWriter(Path.Combine(outDir, "GoodAddresses.csv"))) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(goodAddr); } using (var writer = new StreamWriter(Path.Combine(outDir, "BadAddresses.csv"))) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(badAddr); } } } }
private static void DoGeocode(ConcurrentBag <TDayAddress> goodAddr, ConcurrentBag <TDayAddress> badAddr, MsgOut msgOut, DataRow Row, int rowCnt) { // tblRecipient_Address, tblRecipient_Address1, tblRecipient_City, tblRecipient_State, tblRecipient_PostalCode TDayAddress addr = new TDayAddress() { FirstName = EatTheDamReturns(Row[0].ToString().Replace(",", " ")), LastName = EatTheDamReturns(Row[1].ToString().Replace(",", " ")), Address1 = EatTheDamReturns(Row[2].ToString().Replace(",", " ")), AptNum = EatTheDamReturns(Row[3].ToString().Replace(",", " ")), Address2 = EatTheDamReturns(Row[4].ToString().Replace(",", " ")), City = EatTheDamReturns(Row[5].ToString().Replace(",", " ")), State = EatTheDamReturns(Row[6].ToString().Replace(",", " ")), Zip = EatTheDamReturns(Row[7].ToString()), HomePhone = EatTheDamReturns(Row[8].ToString()), CellPHone = EatTheDamReturns(Row[9].ToString()), DelDay = EatTheDamReturns(Row[10].ToString().Replace(",", " ")), NumMeals = 0, Notes = EatTheDamReturns(Row[12].ToString().Replace(",", " ")) }; int numMeals = 0; addr.NumMeals = 0; if (int.TryParse(Row[11].ToString(), out numMeals)) { addr.NumMeals = numMeals; //msgOut.WriteLine(addr); } GeocodeAddress(addr, goodAddr, badAddr, msgOut).Wait(); //GeocodeAddressGoogle(addr, goodAddr, badAddr, msgOut); msgOut($"Procesed address: {goodAddr.Count + badAddr.Count} of {rowCnt} on thread: {Thread.CurrentThread.ManagedThreadId}\r", true); }