Ejemplo n.º 1
0
 public ZActor(ZContext context, ZAction action, params object[] args)
     : this(context, default(string), action, args)
 {
     var rnd0 = new byte[8];
     using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetNonZeroBytes(rnd0);
     this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
 }
Ejemplo n.º 2
0
 public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
 {
     if (string.IsNullOrEmpty(roleName))
     {
         return false;
     }
     using (var Context = new ZContext())
     {
         Role Role = null;
         Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName);
         if (Role == null)
         {
             return false;
         }
         if (throwOnPopulatedRole)
         {
             if (Role.Users.Any())
             {
                 return false;
             }
         }
         else
         {
             Role.Users.Clear();
         }
         Context.Roles.Remove(Role);
         Context.SaveChanges();
         return true;
     }
 }
Ejemplo n.º 3
0
		/// <summary>
		/// Initializes a new instance of the <see cref="PubSubDevice"/> class.
		/// </summary>
		public PubSubDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
			: base(context, FrontendType, BackendType)
		{
			FrontendSetup.Bind(frontendBindAddr);
			BackendSetup.Bind(backendBindAddr);
			BackendSetup.SubscribeAll();
		}
Ejemplo n.º 4
0
        public ZActor(ZContext context, string endpoint, ZAction action, params object[] args)
            : base()
        {
            this.Context = context;

            this.Endpoint = endpoint;
            this.Action = action;
            this.Arguments = args;
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Get all database in SQL Server
 /// </summary>
 /// <returns>Data</returns>
 public static List<string> GetDatabases()
 {
     try
     {
         var db = new ZContext();
         return db.Database.SqlQuery<string>("select name from sys.sysdatabases").ToList();
     }
     catch { return null; }
 }
Ejemplo n.º 6
0
            public MajordomoClient(string broker, bool verbose)
            {
                if(broker == null)
                    throw new InvalidOperationException();
                _context = new ZContext();
                Broker = broker;
                Verbose = verbose;
                Timeout = TimeSpan.FromMilliseconds(2500);
                Retries = 3;

                ConnectToBroker();
            }
Ejemplo n.º 7
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            System.Data.Entity.Database.SetInitializer<ZContext>(new ZInitializer());

            using (var TestContext = new ZContext())
            {
                TestContext.Users.Count();
            }
        }
Ejemplo n.º 8
0
            // waiting
            // heartbeat_at
            public Broker(bool verbose)
            {
                // Constructor
                _context = new ZContext();

                Socket = new ZSocket(_context, ZSocketType.ROUTER);

                Verbose = verbose;

                Services = new Dictionary<string, Service>(); //new HashSet<Service>();
                Workers = new Dictionary<string, Worker>(); //new HashSet<Worker>();
                Waiting = new List<Worker>();

                HeartbeatAt = DateTime.UtcNow + MdpCommon.HEARTBEAT_INTERVAL;
            }
Ejemplo n.º 9
0
 public override void AddUsersToRoles(string[] usernames, string[] roleNames)
 {
     using (var Context = new ZContext())
     {
         List<User> Users = Context.Users.Where(Usr => usernames.Contains(Usr.Username)).ToList();
         List<Role> Roles = Context.Roles.Where(Rl => roleNames.Contains(Rl.RoleName)).ToList();
         foreach (User user in Users)
         {
             foreach (Role role in Roles)
             {
                 if (!user.Roles.Contains(role))
                 {
                     user.Roles.Add(role);
                 }
             }
         }
         Context.SaveChanges();
     }
 }
Ejemplo n.º 10
0
 public override void CreateRole(string roleName)
 {
     if (!string.IsNullOrEmpty(roleName))
     {
         using (var Context = new ZContext())
         {
             Role Role = null;
             Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName);
             if (Role == null)
             {
                 Role NewRole = new Role
                 {
                     RoleId = Guid.NewGuid(),
                     RoleName = roleName
                 };
                 Context.Roles.Add(NewRole);
                 Context.SaveChanges();
             }
         }
     }
 }
Ejemplo n.º 11
0
 public override bool ValidateUser(string username, string password)
 {
     if (string.IsNullOrEmpty(username))
     {
         return false;
     }
     if (string.IsNullOrEmpty(password))
     {
         return false;
     }
     using (var Context = new ZContext())
     {
         User User = null;
         User = Context.Users.FirstOrDefault(Usr => Usr.Username == username);
         if (User == null)
         {
             return false;
         }
         if (!User.IsApproved)
         {
             return false;
         }
         if (User.IsLockedOut)
         {
             return false;
         }
         String HashedPassword = User.Password;
         Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, password));
         if (VerificationSucceeded)
         {
             User.PasswordFailuresSinceLastSuccess = 0;
             User.LastLoginDate = DateTime.UtcNow;
             User.LastActivityDate = DateTime.UtcNow;
         }
         else
         {
             int Failures = User.PasswordFailuresSinceLastSuccess;
             if (Failures < MaxInvalidPasswordAttempts)
             {
                 User.PasswordFailuresSinceLastSuccess += 1;
                 User.LastPasswordFailureDate = DateTime.UtcNow;
             }
             else if (Failures >= MaxInvalidPasswordAttempts)
             {
                 User.LastPasswordFailureDate = DateTime.UtcNow;
                 User.LastLockoutDate = DateTime.UtcNow;
                 User.IsLockedOut = true;
             }
         }
         Context.SaveChanges();
         if (VerificationSucceeded)
         {
             return true;
         }
         else
         {
             return false;
         }
     }
 }
Ejemplo n.º 12
0
 public override string GetUserNameByEmail(string email)
 {
     using (var Context = new ZContext())
     {
         User User = null;
         User = Context.Users.FirstOrDefault(Usr => Usr.Email == email);
         if (User != null)
         {
             return User.Username;
         }
         else
         {
             return string.Empty;
         }
     }
 }
Ejemplo n.º 13
0
 public override MembershipUser GetUser(string username, bool userIsOnline)
 {
     if (string.IsNullOrEmpty(username))
     {
         return null;
     }
     using (var Context = new ZContext())
     {
         User User = null;
         User = Context.Users.FirstOrDefault(Usr => Usr.Username == username);
         if (User != null)
         {
             if (userIsOnline)
             {
                 User.LastActivityDate = DateTime.UtcNow;
                 Context.SaveChanges();
             }
             return new MembershipUser(Membership.Provider.Name, User.Username, User.UserId, User.Email, null, null, User.IsApproved, User.IsLockedOut, User.CreateDate.Value, User.LastLoginDate.Value, User.LastActivityDate.Value, User.LastPasswordChangedDate.Value, User.LastLockoutDate.Value);
         }
         else
         {
             return null;
         }
     }
 }
Ejemplo n.º 14
0
        public static void FLServer3(IDictionary <string, string> dict, string[] args)
        {
            //
            // Freelance server - Model 3
            // Uses an ROUTER/ROUTER socket but just one thread
            //
            // Author: metadings
            //

            // Prepare server socket with predictable identity
            string bind_endpoint    = "tcp://*:5555";
            string connect_endpoint = "tcp://127.0.0.1:5555";

            using (var context = ZContext.Create())
                using (var server = ZSocket.Create(context, ZSocketType.ROUTER))
                {
                    Console.CancelKeyPress += (s, ea) =>
                    {
                        ea.Cancel = true;
                        context.Shutdown();
                    };

                    server.IdentityString = connect_endpoint;
                    server.Bind(bind_endpoint);
                    Console.WriteLine("I: service is ready as {0}", bind_endpoint);

                    ZError   error;
                    ZMessage request;
                    while (true)
                    {
                        if (null == (request = server.ReceiveMessage(out error)))
                        {
                            if (error == ZError.ETERM)
                            {
                                break;                          // Interrupted
                            }
                            throw new ZException(error);
                        }
                        using (var response = new ZMessage())
                        {
                            ZFrame identity;

                            using (request)
                            {
                                Console_WriteZMessage(request, "Receiving");

                                // Frame 0: identity of client
                                // Frame 1: PING, or client control frame
                                // Frame 2: request body

                                identity = request.Pop();

                                ZFrame control        = request.Pop();
                                string controlMessage = control.ReadString();

                                if (controlMessage == "PING")
                                {
                                    control.Dispose();
                                    response.Add(new ZFrame("PONG"));
                                }
                                else
                                {
                                    response.Add(control);
                                    response.Add(new ZFrame("OK"));
                                }
                            }

                            response.Prepend(identity);

                            Console_WriteZMessage(response, "Sending  ");
                            if (!server.Send(response, out error))
                            {
                                if (error == ZError.ETERM)
                                {
                                    break;                              // Interrupted
                                }
                                throw new ZException(error);
                            }
                        }
                    }
                    if (error == ZError.ETERM)
                    {
                        Console.WriteLine("W: interrupted");
                    }
                }
        }
Ejemplo n.º 15
0
        public static void SPWorker(IDictionary <string, string> dict, string[] args)
        {
            //
            // Simple Pirate worker
            // Connects REQ socket to tcp://localhost:5556
            // Implements worker part of load-balancing
            //
            // Authors: Pieter Hintjens, Uli Riehm
            //

            var rnd = new Random();

            if (args == null || args.Length < 1)
            {
                args = new string[] { "World" + rnd.Next() };
            }
            string name = args[0];

            using (var context = ZContext.Create())
                using (var worker = ZSocket.Create(context, ZSocketType.REQ))
                {
                    worker.Identity = Encoding.UTF8.GetBytes(name);
                    worker.Connect("tcp://127.0.0.1:5556");

                    Console.WriteLine("I: ({0}) worker ready", name);

                    using (var outgoing = new ZFrame("READY"))
                    {
                        worker.Send(outgoing);
                    }

                    int      cycles = 0;
                    ZError   error;
                    ZMessage incoming;

                    while (true)
                    {
                        if (null == (incoming = worker.ReceiveMessage(out error)))
                        {
                            if (error == ZError.ETERM)
                            {
                                return;
                            }

                            throw new ZException(error);
                        }
                        using (incoming)
                        {
                            // Simulate various problems, after a few cycles
                            cycles++;

                            if (cycles > 3 && rnd.Next(5) == 0)
                            {
                                Console.WriteLine("I: ({0}) simulating a crash", name);
                                return;
                            }
                            else if (cycles > 3 && rnd.Next(5) == 0)
                            {
                                Console.WriteLine("I: ({0}) simulating CPU overload", name);
                                Thread.Sleep(500);
                            }

                            Console.WriteLine("I: ({0}) normal reply", name);

                            Thread.Sleep(1);                     // Do some heavy work

                            // Send message back
                            worker.Send(incoming);
                        }
                    }
                }
        }
Ejemplo n.º 16
0
        public void LPClient()
        {
            string name = "ZMQsocket";

            using (var context = new ZContext())
            {
                ZSocket requester = null;
                try
                { // using (requester)
                    ZError error;

                    if (null == (requester = LPClient_CreateZSocket(context, name, out error)))
                    {
                        if (error == ZError.ETERM)
                        {
                            return;    // Interrupted
                        }
                        throw new ZException(error);
                    }

                    int sequence     = 10;
                    int retries_left = LPClient_RequestRetries;
                    var poll         = ZPollItem.CreateReceiver();

                    while (retries_left > 0)
                    {
                        // We send a request, then we work to get a reply
                        using (var outgoing = ZFrame.Create(4))
                        {
                            outgoing.Write(sequence);
                            if (!requester.Send(outgoing, out error))
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;    // Interrupted
                                }
                                throw new ZException(error);
                            }
                        }

                        ZMessage incoming;
                        // Here we process a server reply and exit our loop
                        // if the reply is valid.

                        // If we didn't a reply, we close the client socket
                        // and resend the request. We try a number of times
                        // before finally abandoning:

                        // Poll socket for a reply, with timeout
                        if (requester.PollIn(poll, out incoming, out error, LPClient_RequestTimeout))
                        {
                            using (incoming)
                            {
                                // We got a reply from the server
                                int incoming_sequence = incoming[0].ReadInt32();
                                if (incoming_sequence >= 0 && incoming_sequence <= 9)
                                {
                                    TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": I: Сервер ответил: ({0}) \n", incoming_sequence));
                                }
                                else
                                {
                                    TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": E: Ошибка на стороне сервера: ({0}) \n", incoming_sequence));
                                }
                                retries_left = LPClient_RequestRetries;
                                break;
                            }
                        }
                        else
                        {
                            if (error == ZError.EAGAIN)
                            {
                                if (--retries_left == 0)
                                {
                                    TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": E: Сервер недоступен \n"));
                                    break;
                                }

                                TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": W: Нет ответа от сервера, переподключение... \n"));

                                // Old socket is confused; close it and open a new one
                                requester.Dispose();
                                if (null == (requester = LPClient_CreateZSocket(context, name, out error)))
                                {
                                    if (error == ZError.ETERM)
                                    {
                                        return;    // Interrupted
                                    }
                                    throw new ZException(error);
                                }

                                TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": I: Переподключение \n"));

                                // Send request again, on new socket
                                using (var outgoing = ZFrame.Create(4))
                                {
                                    outgoing.Write(sequence);
                                    if (!requester.Send(outgoing, out error))
                                    {
                                        if (error == ZError.ETERM)
                                        {
                                            return;    // Interrupted
                                        }
                                        throw new ZException(error);
                                    }
                                }

                                continue;
                            }

                            if (error == ZError.ETERM)
                            {
                                return;    // Interrupted
                            }
                            throw new ZException(error);
                        }
                    }
                }
                catch
                {
                    TextBoard.AppendText(DateTime.Now.TimeOfDay.ToString() + String.Format(": E: Ошибка запроса. \n"));
                }
                finally
                {
                    if (requester != null)
                    {
                        requester.Dispose();
                        requester = null;
                    }
                }
            }
        }
Ejemplo n.º 17
0
 public override bool IsUserInRole(string username, string roleName)
 {
     if (string.IsNullOrEmpty(username))
     {
         return false;
     }
     if (string.IsNullOrEmpty(roleName))
     {
         return false;
     }
     using (var Context = new ZContext())
     {
         User User = null;
         User = Context.Users.FirstOrDefault(Usr => Usr.Username == username);
         if (User == null)
         {
             return false;
         }
         Role Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName);
         if (Role == null)
         {
             return false;
         }
         return User.Roles.Contains(Role);
     }
 }
Ejemplo n.º 18
0
        public static void MSReader(string[] args)
        {
            //
            // Reading from multiple sockets
            // This version uses a simple recv loop
            //
            // Author: metadings
            //

            using (var context = new ZContext())
                using (var receiver = new ZSocket(context, ZSocketType.PULL))
                    using (var subscriber = new ZSocket(context, ZSocketType.SUB))
                    {
                        // Connect to task ventilator
                        receiver.Connect("tcp://127.0.0.1:5557");

                        // Connect to weather server
                        subscriber.Connect("tcp://127.0.0.1:5556");
                        subscriber.SetOption(ZSocketOption.SUBSCRIBE, "10001 ");

                        // Process messages from both sockets
                        // We prioritize traffic from the task ventilator
                        ZError error;
                        ZFrame frame;
                        while (true)
                        {
                            if (null != (frame = receiver.ReceiveFrame(ZSocketFlags.DontWait, out error)))
                            {
                                // Process task
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;                     // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }

                            if (null != (frame = subscriber.ReceiveFrame(ZSocketFlags.DontWait, out error)))
                            {
                                // Process weather update
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;                     // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }

                            // No activity, so sleep for 1 msec
                            Thread.Sleep(1);
                        }
                    }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            try
            {
                System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
                string topicName = ConfigurationManager.AppSettings["TopicName"].ToString();
                string fatiNotificationServerUrl = ConfigurationManager.AppSettings["FatiNotificationServerUrl"].ToString();
                string areaNames = ConfigurationManager.AppSettings["AreaNames"].ToString();
                int    siteId    = string.IsNullOrEmpty(ConfigurationManager.AppSettings["SiteId"].ToString())?0:int.Parse(ConfigurationManager.AppSettings["SiteId"].ToString());

                using (var context = new ZContext())
                    using (var subscriber = new ZSocket(context, ZSocketType.SUB))
                    {
                        //Create the Subscriber Connection
                        subscriber.Connect(fatiNotificationServerUrl);
                        subscriber.Subscribe(topicName);
                        Console.WriteLine("Subscriber started for Topic with URL : {0} {1}", topicName, fatiNotificationServerUrl);
                        Console.WriteLine("Site ID set to : {0}", siteId);
                        Library objLibray  = new Library();
                        int     subscribed = 0;

                        while (true)
                        {
                            using (ZMessage message = subscriber.ReceiveMessage())
                            {
                                subscribed++;

                                // Read message contents
                                string contents = message[1].ReadString();

                                Console.WriteLine(contents);

                                LocationData objLocationData = JsonConvert.DeserializeObject <ListOfArea>(contents).device_notification.records.FirstOrDefault();


                                bool checkSeenAfterConstantMinute = false;
                                bool checkConsecutiveVisit        = false;
                                bool checkAlreadyNotifiedOnce     = false;

                                //if the MacAddress is Registered through our RTLS Service Layer
                                if (objLibray.IsMacAddressExist(objLocationData, siteId) > 0)
                                {
                                    Console.WriteLine(objLocationData.mac + " - Mac Address Exist");

                                    string[] watchArea = (string.IsNullOrEmpty(areaNames) ? null : areaNames.Split(','));
                                    if (watchArea != null && watchArea.Length > 0)
                                    {
                                        string[] inputArea = objLocationData.an;
                                        foreach (string an in inputArea)
                                        {
                                            if (watchArea.Contains(an.Trim()))
                                            {
                                                Console.WriteLine("Checking for Area [" + an + "]");

                                                DateTime macFoundDatetime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds(objLocationData.last_seen_ts);
                                                objLocationData.LastSeenDatetime = macFoundDatetime;

                                                //Alrearady Exist MacAddress to update the Notification LastSeenDateTime
                                                if (objLibray.IsNotificationSentBefore(objLocationData) >= 1)
                                                {
                                                    checkSeenAfterConstantMinute = objLibray.IsSeenAfterConstantMinute(objLocationData);
                                                    checkConsecutiveVisit        = objLibray.IsConsecutiveStreamDataForMac(objLocationData);
                                                    checkAlreadyNotifiedOnce     = objLibray.IsAlreadyNotified(objLocationData.mac);

                                                    Console.WriteLine(Environment.NewLine + "Check Seen After Constant Seconds - " + checkSeenAfterConstantMinute);
                                                    Console.WriteLine("Check Consecutive Visit - " + checkConsecutiveVisit);
                                                    Console.WriteLine("Check Already Notified Once - " + checkAlreadyNotifiedOnce);


                                                    if (checkConsecutiveVisit == true && checkAlreadyNotifiedOnce == false)
                                                    {
                                                        Console.WriteLine("Notifiy Visit.");
                                                        objLibray.PostRestCall(objLocationData);
                                                        objLibray.UpdateNotificationData(objLocationData);
                                                    }
                                                    else if (checkSeenAfterConstantMinute == true && checkAlreadyNotifiedOnce == true)
                                                    {
                                                        Console.WriteLine("Notifiy Visit ");
                                                        objLibray.PostRestCall(objLocationData);
                                                        objLibray.UpdateNotificationData(objLocationData);
                                                    }
                                                }
                                                //New MacAddress For Storing in Notification table.
                                                else
                                                {
                                                    objLibray.InsertData(objLocationData);
                                                    objLibray.PostRestCall(objLocationData);
                                                    objLibray.UpdateNotificationData(objLocationData);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                Console.Write(" Error:-" + ex.Message);
            }
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            //TODO: Implement a (presumably) high performance server which somehow exposes the operations on IPal over the network, executes those operations against InteropPal, and returns results when relevant.

            InteropPal ip = new InteropPal();

            using (var context = new ZContext())
                using (responder = new ZSocket(context, ZSocketType.REP))
                {
                    // Bind
                    responder.Bind("tcp://*:5555");
                    while (true)
                    {
                        // Receive
                        using (ZFrame request = responder.ReceiveFrame())
                        {
                            string requestJson = request.ReadString();

                            var palMessage = JsonConvert.DeserializeObject <PalMessage>(requestJson, settings);

                            if (palMessage is InitMessage)
                            {
                                Console.WriteLine($"<-- {nameof(InitMessage)}");

                                Send(responder, new InitResponse {
                                    Result = ip.Init()
                                });
                            }
                            else if (palMessage is GetNumDevicesMessage)
                            {
                                Console.WriteLine($"<-- {nameof(GetNumDevicesMessage)}");

                                Send(responder, new GetNumDevicesResponse {
                                    Result = ip.GetNumDevices()
                                });
                            }
                            else if (palMessage is GetDeviceInfoMessage msg1)
                            {
                                Console.WriteLine($"<-- {nameof(GetDeviceInfoMessage)}");

                                bool result = ip.GetDeviceInfo(msg1.Index, out uint model, out uint sn);

                                Send(responder, new GetDeviceInfoResponse {
                                    Result = result, Model = model, Sn = sn
                                });
                            }
                            else if (palMessage is SelectDeviceMessage msg2)
                            {
                                Console.WriteLine($"<-- {nameof(SelectDeviceMessage)}");

                                Send(responder, new SelectDeviceResponse {
                                    Result = ip.SelectDevice(msg2.Index)
                                });
                            }
                            else if (palMessage is SetCallbackMessage msg10)
                            {
                                Console.WriteLine($"<-- {nameof(SetCallbackMessage)}");

                                ip.SetCallback(notificationCallback);

                                var ctx = new ZContext();
                                publisher = new ZSocket(ctx, ZSocketType.PUB);
                                publisher.Bind("tcp://*:5556");

                                Send(responder, new PalResponse());
                            }
                            else if (palMessage is ReadOp1Message msg3)
                            {
                                Console.WriteLine($"<-- {nameof(ReadOp1Message)}");
                                int result = ip.ReadOp1(msg3.Opcode, msg3.Data1, msg3.Data2, out uint rtn);

                                Send(responder, new ReadOp1Response {
                                    Result = result, Rtn = rtn
                                });
                            }
                            else if (palMessage is ReadOp2Message msg4)
                            {
                                Console.WriteLine($"<-- {nameof(ReadOp2Message)}");

                                int result = ip.ReadOp2(msg4.Opcode, msg4.Data1, msg4.Data2, out float rtn);

                                Send(responder, new ReadOp2Response {
                                    Result = result, Rtn = rtn
                                });
                            }
                            else if (palMessage is WriteOp1Message msg5)
                            {
                                Console.WriteLine($"<-- {nameof(WriteOp1Message)}");

                                int result = ip.WriteOp1(msg5.Opcode, msg5.Data1, msg5.Data2);

                                Send(responder, new WriteOp1Response {
                                    Result = result
                                });
                            }
                            else if (palMessage is WriteOp2Message msg6)
                            {
                                Console.WriteLine($"<-- {nameof(WriteOp2Message)}");

                                int result = ip.WriteOp2(msg6.Opcode, msg6.Data1, msg6.Data2);

                                Send(responder, new WriteOp2Response {
                                    Result = result
                                });
                            }
                            else if (palMessage is WriteOp3Message msg7)
                            {
                                Console.WriteLine($"<-- {nameof(WriteOp3Message)}");

                                int result = ip.WriteOp3(msg7.Opcode, msg7.Data1, msg7.Data2);

                                Send(responder, new WriteOp3Response {
                                    Result = result
                                });
                            }
                            else if (palMessage is WriteOp4Message msg8)
                            {
                                Console.WriteLine($"<-- {nameof(WriteOp4Message)}");

                                int result = ip.WriteOp4(msg8.Opcode, msg8.Data1, msg8.Data2);

                                Send(responder, new WriteOp4Response {
                                    Result = result
                                });
                            }
                            else if (palMessage is SetBufferSizeMessage msg9)
                            {
                                Console.WriteLine($"<-- {nameof(SetBufferSizeMessage)}");

                                ip.SetBufferSize(msg9.Val);

                                Send(responder, new PalResponse());
                            }
                            else if (palMessage is ExitMessage)
                            {
                                Console.WriteLine($"<-- {nameof(ExitMessage)}");

                                ip.Exit();

                                Send(responder, new PalResponse());
                            }
                            else
                            {
                                Console.WriteLine("Not implemented: " + palMessage.GetType().Name);
                            }
                        }
                    }
                }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PubSubDevice"/> class.
 /// </summary>
 public PubSubDevice(ZContext context)
     : base(context, FrontendType, BackendType)
 {
     BackendSetup.SubscribeAll();
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
 /// </summary>
 public StreamDealerDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
     : base(context, FrontendType, BackendType)
 {
     FrontendSetup.Bind(frontendBindAddr);
     BackendSetup.Bind(backendBindAddr);
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
 /// </summary>
 public StreamDealerDevice(ZContext context)
     : base(context, FrontendType, BackendType)
 {
 }
Ejemplo n.º 24
0
 public WorkloadContextSenderModel(ZContext ctx)
 {
     _pubSocket = new ZSocket(ctx, ZSocketType.PUB);
     _pubSocket.Connect("tcp://127.0.0.1:5560");
 }
Ejemplo n.º 25
0
        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            if (string.IsNullOrEmpty(roleName))
            {
                return null;
            }

            if (string.IsNullOrEmpty(usernameToMatch))
            {
                return null;
            }

            using (var Context = new ZContext())
            {

                return (from Rl in Context.Roles from Usr in Rl.Users where Rl.RoleName == roleName && Usr.Username.Contains(usernameToMatch) select Usr.Username).ToArray();
            }
        }
Ejemplo n.º 26
0
 public override string[] GetRolesForUser(string username)
 {
     if (string.IsNullOrEmpty(username))
     {
         return null;
     }
     using (var Context = new ZContext())
     {
         User User = null;
         User = Context.Users.FirstOrDefault(Usr => Usr.Username == username);
         if (User != null)
         {
             return User.Roles.Select(Rl => Rl.RoleName).ToArray();
         }
         else
         {
             return null;
         }
     }
 }
Ejemplo n.º 27
0
        public static void RouterDealer(IDictionary <string, string> dict, string[] args)
        {
            int  who       = dict.ContainsKey("--server") ? 1 : (dict.ContainsKey("--client") ? 2 : 0);
            bool doMonitor = dict.ContainsKey("--monitor");

            if (args == null || args.Length < 1)
            {
                // say here were some arguments...
                args = new string[] { "World" };
            }

            // Setup the ZContext
            context = ZContext.Create();

            RouterDealerDevice      routerDealer = null;
            CancellationTokenSource cancellor0   = null;

            var cancellor1 = doMonitor ? new CancellationTokenSource() : null;

            if (who == 0 || who == 1)
            {
                // Create the "Server" cancellor and thread
                cancellor0 = new CancellationTokenSource();

                routerDealer = new RouterDealerDevice(context, Frontend, Backend);
                routerDealer.Start(cancellor0);
                routerDealer.Join(64);

                int i = -1;
                foreach (string arg in args)
                {
                    int j = ++i;

                    var serverThread = new Thread(() => RouterDealer_Server(cancellor0.Token, j, arg, doMonitor));
                    serverThread.Start(cancellor0);
                    serverThread.Join(64);

                    if (doMonitor)
                    {
                        var monitor = ZMonitor.Create(context, "inproc://RouterDealer-Server" + j);

                        monitor.AllEvents += (sender, e) =>
                        {
                            Console.Write("  {0}: {1}", arg, Enum.GetName(typeof(ZMonitorEvents), e.Event.Event));
                            if (e.Event.EventValue > 0)
                            {
                                Console.Write(" ({0})", e.Event.EventValue);
                            }
                            Console.WriteLine();
                        };

                        monitor.Start(cancellor1);
                        monitor.Join(64);
                    }
                }
            }

            if (who == 0 || who == 2)
            {
                // foreach arg we are the Client, asking the Server
                int i = -1;
                foreach (string arg in args)
                {
                    int j = ++i;

                    if (doMonitor)
                    {
                        var monitor = ZMonitor.Create(context, "inproc://RouterDealer-Client" + j);

                        monitor.AllEvents += (sender, e) =>
                        {
                            Console.Write("  {0}: {1}", arg, Enum.GetName(typeof(ZMonitorEvents), e.Event.Event));
                            if (e.Event.EventValue > 0)
                            {
                                Console.Write(" ({0})", e.Event.EventValue);
                            }
                            Console.WriteLine();
                        };

                        Console.WriteLine(RouterDealer_Client(j, arg, () => { monitor.Start(cancellor1); monitor.Join(64); }));
                    }
                    else
                    {
                        Console.WriteLine(RouterDealer_Client(j, arg));
                    }
                }
            }

            if (who == 1)
            {
                Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
                {
                    Console.WriteLine("Cancelled...");

                    if (cancellor1 != null)
                    {
                        // Cancel the Monitors
                        cancellor1.Cancel();
                    }

                    if (cancellor0 != null)
                    {
                        // Cancel the Server
                        cancellor0.Cancel();
                    }

                    if (routerDealer != null)
                    {
                        routerDealer.Stop();
                    }
                };

                Console.WriteLine("Running...");

                while (true)
                {
                    Thread.Sleep(250);
                }
            }

            if (cancellor1 != null)
            {
                // Cancel the Monitors
                cancellor1.Cancel();
            }

            if (cancellor0 != null)
            {
                // Cancel the Server
                cancellor0.Cancel();
            }

            if (routerDealer != null)
            {
                routerDealer.Stop();
            }

            // we could have done here context.Terminate()
        }
Ejemplo n.º 28
0
 public override bool RoleExists(string roleName)
 {
     if (string.IsNullOrEmpty(roleName))
     {
         return false;
     }
     using (var Context = new ZContext())
     {
         Role Role = null;
         Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName);
         if (Role != null)
         {
             return true;
         }
         else
         {
             return false;
         }
     }
 }
Ejemplo n.º 29
0
        static void MTServer_Worker(ZContext ctx)
        {
            // Socket to talk to dispatcher
            using (var server = new ZSocket(ctx, ZSocketType.REP))
            {
                server.Connect("inproc://workers");

                while (true)
                {
                    using (ZFrame frame = server.ReceiveFrame())
                    {
                        Console.WriteLine("receivin request");
                        byte[]  receivedBytes = frame.Read();
                        Request req           = ProtoDeserialize <Request>(receivedBytes);
                        Console.WriteLine("request deserialized");
                        Console.WriteLine(req.request);
                        switch (req.request)
                        {
                        default:
                        {
                            Console.WriteLine("default -> break");

                            break;
                        }

                        case "login":
                        {
                            Console.WriteLine("login request");

                            TRequest <Login> tLogin = new TRequest <Login>();

                            tLogin = ProtoDeserialize <TRequest <Login> >(req.reqData);

                            LoginResponse response = new LoginResponse();

                            response = tLogin.Data.response;

                            response.user = tLogin.Data.user;
                            response.ID   = tLogin.Data.ID;

                            response.cookie = "XXXXXXXXXXXXXXXXXXXX";

                            response.hasLogged = true;

                            tLogin.Data.response = response;

                            req.reqData = ProtoSerialize <TRequest <Login> >(tLogin);

                            byte[] sendT = ProtoSerialize(req);


                            // Do some 'work'
                            Thread.Sleep(1);


                            // Send reply back to client

                            server.Send(new ZFrame(sendT));

                            break;
                        }
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
        public static void LPClient(IDictionary <string, string> dict, string[] args)
        {
            if (args == null || args.Length < 1)
            {
                Console.WriteLine();
                Console.WriteLine("Usage: ./{0} LPClient [Name]", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine();
                Console.WriteLine("    Name   Your name. Default: People");
                Console.WriteLine();
                args = new string[] { "People" };
            }

            string name = args[0];

            ZSocket requester = null;

            try {             // using (requester)
                using (var context = new ZContext())
                {
                    ZError error;

                    if (null == (requester = LPClient_CreateZSocket(context, name, out error)))
                    {
                        if (error == ZError.ETERM)
                        {
                            return;                             // Interrupted
                        }
                        throw new ZException(error);
                    }

                    int sequence     = 0;
                    int retries_left = LPClient_RequestRetries;
                    var poll         = ZPollItem.CreateReceiver();

                    while (retries_left > 0)
                    {
                        // We send a request, then we work to get a reply
                        using (var outgoing = ZFrame.Create(4))
                        {
                            outgoing.Write(++sequence);
                            requester.Send(outgoing);
                        }

                        ZMessage incoming;
                        while (true)
                        {
                            // Here we process a server reply and exit our loop
                            // if the reply is valid.

                            // If we didn't a reply, we close the client socket
                            // and resend the request. We try a number of times
                            // before finally abandoning:

                            // Poll socket for a reply, with timeout
                            if (requester.PollIn(poll, out incoming, out error, LPClient_RequestTimeout))
                            {
                                using (incoming)
                                {
                                    // We got a reply from the server
                                    int incoming_sequence = incoming[0].ReadInt32();
                                    if (sequence == incoming_sequence)
                                    {
                                        Console.WriteLine("I: server replied OK ({0})", incoming_sequence);
                                        retries_left = LPClient_RequestRetries;
                                        break;
                                    }
                                    else
                                    {
                                        Console_WriteZMessage(incoming, "E: malformed reply from server");
                                    }
                                }
                            }
                            else
                            {
                                if (error == ZError.EAGAIN)
                                {
                                    if (--retries_left == 0)
                                    {
                                        Console.WriteLine("E: server seems to be offline, abandoning");
                                        break;
                                    }

                                    Console.WriteLine("W: no response from server, retrying...");

                                    // Old socket is confused; close it and open a new one
                                    requester.Dispose();
                                    if (null == (requester = LPClient_CreateZSocket(context, name, out error)))
                                    {
                                        if (error == ZError.ETERM)
                                        {
                                            return;                                             // Interrupted
                                        }
                                        throw new ZException(error);
                                    }

                                    Console.WriteLine("I: reconnected");

                                    // Send request again, on new socket
                                    using (var outgoing = ZFrame.Create(4))
                                    {
                                        outgoing.Write(sequence);
                                        requester.Send(outgoing);
                                    }

                                    continue;
                                }

                                if (error == ZError.ETERM)
                                {
                                    return;                                     // Interrupted
                                }
                                throw new ZException(error);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (requester != null)
                {
                    requester.Dispose();
                    requester = null;
                }
            }
        }
Ejemplo n.º 31
0
            public static void Agent(ZContext context, ZSocket backend, CancellationToken cancellus, object[] args)
            {
                // Finally, here's the agent task itself, which polls its two sockets
                // and processes incoming messages:

                using (var agent = new Agent(context, backend))
                {
                    var p = ZPollItem.CreateReceiver();

                    while (!cancellus.IsCancellationRequested)
                    {
                        ZMessage msg;
                        ZError   error;

                        // Poll the control message

                        if (agent.Pipe.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            using (msg)
                            {
                                agent.ControlMessage(msg);
                            }
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                break;                                  // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }

                        // Poll the router message

                        if (agent.Router.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(64)))
                        {
                            using (msg)
                            {
                                agent.RouterMessage(msg);
                            }
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                break;                                  // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }

                        if (agent.Request != null)
                        {
                            // If we're processing a request, dispatch to next server

                            if (DateTime.UtcNow >= agent.Expires)
                            {
                                // Request expired, kill it
                                using (var outgoing = new ZFrame("FAILED"))
                                {
                                    agent.Pipe.Send(outgoing);
                                }

                                agent.Request.Dispose();
                                agent.Request = null;
                            }
                            else
                            {
                                // Find server to talk to, remove any expired ones
                                foreach (Server server in agent.Actives.ToList())
                                {
                                    if (DateTime.UtcNow >= server.Expires)
                                    {
                                        agent.Actives.Remove(server);
                                        server.Alive = false;
                                    }
                                    else
                                    {
                                        // Copy the Request, Push the Endpoint and send on Router
                                        using (var request = agent.Request.Duplicate())
                                        {
                                            request.Prepend(new ZFrame(server.Endpoint));

                                            agent.Router.Send(request);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        // Disconnect and delete any expired servers
                        // Send heartbeats to idle servers if needed
                        foreach (Server server in agent.Servers)
                        {
                            server.Ping(agent.Router);
                        }
                    }
                }
            }
        public static void Broker(ZContext context, string brokerAddrRequest, string brokerAddrResponse, string brokerAddrRequestPush, string brokerAddrResponsePull, string brokerAddrRequestPub, string brokerAddrResponseSub, string AddrToBroker1, string AddrToBroker2, string AddrFromBrokers, string brokerIdentity)
        {
            List <ArrayList> requestEndpoints  = new List <ArrayList>();
            List <ArrayList> responseEndpoints = new List <ArrayList>();
            List <ArrayList> copies            = new List <ArrayList>();

            using (var brokerRequest = new ZSocket(context, ZSocketType.ROUTER))
                using (var brokerResponse = new ZSocket(context, ZSocketType.DEALER))
                    using (var brokerRequestPush = new ZSocket(context, ZSocketType.PULL))
                        using (var brokerResponsePull = new ZSocket(context, ZSocketType.PUSH))
                            using (var brokerRequestPub = new ZSocket(context, ZSocketType.SUB))
                                using (var brokerResponseSub = new ZSocket(context, ZSocketType.PUB))
                                    using (var brokerToOtherBroker1 = new ZSocket(context, ZSocketType.DEALER))
                                        using (var brokerToOtherBroker2 = new ZSocket(context, ZSocketType.DEALER))
                                            using (var brokerFromBrokers = new ZSocket(context, ZSocketType.DEALER))
                                            {
                                                brokerRequestPub.SubscribeAll();

                                                String reqMonitorAddr = "inproc://req." + brokerIdentity;
                                                brokerRequest.Monitor(reqMonitorAddr);
                                                ZMonitor reqMonitor = ZMonitor.Create(context, reqMonitorAddr);
                                                reqMonitor.Start();
                                                bool reqConnected    = false;
                                                bool reqDisconnected = false;

                                                reqMonitor.Disconnected +=
                                                    (s, a) =>
                                                {
                                                    reqDisconnected = true;
                                                    reqConnected    = false;
                                                };

                                                reqMonitor.Accepted +=
                                                    (s, a) =>
                                                {
                                                    reqConnected    = true;
                                                    reqDisconnected = false;
                                                };

                                                String subMonitorAddr = "inproc://sub." + brokerIdentity;
                                                brokerResponseSub.Monitor(subMonitorAddr);
                                                ZMonitor subMonitor = ZMonitor.Create(context, subMonitorAddr);
                                                subMonitor.Start();
                                                bool subConnected    = false;
                                                bool subDisconnected = false;

                                                subMonitor.Disconnected +=
                                                    (s, a) =>
                                                {
                                                    subDisconnected = true;
                                                    subConnected    = false;
                                                };

                                                subMonitor.Accepted +=
                                                    (s, a) =>
                                                {
                                                    subConnected = true;
                                                };

                                                String pullMonitorAddr = "inproc://pull." + brokerIdentity;
                                                brokerResponsePull.Monitor(pullMonitorAddr);
                                                ZMonitor pullMonitor = ZMonitor.Create(context, pullMonitorAddr);
                                                pullMonitor.Start();
                                                bool pullConnected    = false;
                                                bool pullDisconnected = false;

                                                pullMonitor.Disconnected +=
                                                    (s, a) =>
                                                {
                                                    pullDisconnected = true;
                                                    pullConnected    = false;
                                                };

                                                pullMonitor.Accepted +=
                                                    (s, a) =>
                                                {
                                                    pullConnected = true;
                                                };

                                                brokerRequest.Bind(brokerAddrRequest);
                                                brokerResponse.Bind(brokerAddrResponse);
                                                brokerFromBrokers.Bind(AddrFromBrokers);
                                                brokerToOtherBroker1.Connect(AddrToBroker1);
                                                brokerToOtherBroker2.Connect(AddrToBroker2);
                                                brokerRequestPush.Bind(brokerAddrRequestPush);
                                                brokerResponsePull.Bind(brokerAddrResponsePull);
                                                brokerRequestPub.Bind(brokerAddrRequestPub);
                                                brokerResponseSub.Bind(brokerAddrResponseSub);

                                                ZError    error;
                                                ZMessage  request;
                                                ZPollItem poll = ZPollItem.CreateReceiver();

                                                string fileRequest  = "Request.txt";
                                                string fileResponse = "Response.txt";
                                                //string pathReq =".\\Request\\" + uid + ".txt";
                                                //string pathRep = ".\\Request\\" + uid + ".txt";
                                                Directory.CreateDirectory("Request");
                                                Directory.CreateDirectory("Response");
                                                if (!File.Exists(fileRequest))
                                                {
                                                    File.Create(fileRequest).Close();
                                                }
                                                if (!File.Exists(fileResponse))
                                                {
                                                    File.Create(fileResponse).Close();
                                                }

                                                while (true)
                                                {
                                                    SendCopies(copies, brokerIdentity);

                                                    if (requestEndpoints.Any())
                                                    {
                                                        for (int i = 0; i < requestEndpoints.Count; i++)
                                                        {
                                                            string content = requestEndpoints[i][0].ToString();
                                                            string uid     = requestEndpoints[i][1].ToString();

                                                            if (requestEndpoints[i].Count > 5)
                                                            {
                                                                string addrOrTopic;
                                                                if (requestEndpoints[i][5].ToString().Length == 20)
                                                                {
                                                                    addrOrTopic = requestEndpoints[i][5].ToString().Substring(16, 4);
                                                                }
                                                                else
                                                                {
                                                                    addrOrTopic = requestEndpoints[i][5].ToString();
                                                                }
                                                                ZSocket socket  = (ZSocket)requestEndpoints[i][3];
                                                                string  address = socket.LastEndpoint.Substring(14, 4);
                                                                bool    sended  = false;

                                                                if (addrOrTopic == address)
                                                                {
                                                                    if (socket.SocketType == ZSocketType.PUSH & pullDisconnected == false & pullConnected == true)
                                                                    {
                                                                        sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server");
                                                                    }
                                                                    else
                                                                    {
                                                                        sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server");
                                                                    }
                                                                }
                                                                else if (socket.SocketType == ZSocketType.PUB & subDisconnected == false & subConnected == true)
                                                                {
                                                                    sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server", addrOrTopic);
                                                                }

                                                                if (socket != brokerResponse && sended == true)
                                                                {
                                                                    RemoveFromList(requestEndpoints, Guid.Parse(uid));
                                                                    string messageType = "REP";

                                                                    MoveFile(uid, content);
                                                                    //WriteToFile(fileResponse, Guid.Parse(uid));
                                                                    DeleteFile(uid);
                                                                    UpdateFile(fileRequest, uid);

                                                                    AddToList(copies, content, Guid.Parse(uid), messageType, null, null, brokerToOtherBroker1, brokerToOtherBroker2);
                                                                }
                                                            }
                                                        }
                                                    }

                                                    if (responseEndpoints.Any())
                                                    {
                                                        for (int i = 0; i < responseEndpoints.Count; i++)
                                                        {
                                                            string content = responseEndpoints[i][0].ToString();
                                                            string uid     = responseEndpoints[i][1].ToString();

                                                            if (responseEndpoints[i].Count > 4)
                                                            {
                                                                string  identity = responseEndpoints[i][2].ToString();
                                                                ZSocket socket   = (ZSocket)responseEndpoints[i][3];
                                                                string  address  = responseEndpoints[i][4].ToString().Substring(14, 4);
                                                                string  address2 = brokerRequest.LastEndpoint.Substring(14, 4);

                                                                if (address == address2)
                                                                {
                                                                    if (reqDisconnected == true & reqConnected == false)
                                                                    {
                                                                        Thread.Sleep(5 * 1000);
                                                                    }

                                                                    if (reqDisconnected == false & reqConnected == true)
                                                                    {
                                                                        Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, identity);

                                                                        DeleteFile(uid);
                                                                        UpdateFile(fileResponse, uid);
                                                                        RemoveFromList(responseEndpoints, Guid.Parse(uid));

                                                                        string messageType = "CON";
                                                                        AddToList(copies, content, Guid.Parse(uid), messageType, null, null, brokerToOtherBroker1, brokerToOtherBroker2);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                    if (brokerRequest.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1)))
                                                    {
                                                        string receiverAddress = request[2].ReadString();
                                                        string identity        = request[3].ReadString();
                                                        string content         = request[4].ReadString();
                                                        string messageType     = "REQ";
                                                        string senderAddress   = brokerRequest.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1);

                                                        Guid guid = Guid.NewGuid();
                                                        Console.WriteLine("{0} <- {1} : [{2} {3}]", brokerIdentity, identity, messageType, guid.ToString());
                                                        CreateFile(guid, content);
                                                        WriteToFile(fileRequest, guid);
                                                        AddToList(requestEndpoints, content, guid, identity, senderAddress, receiverAddress, brokerResponse);
                                                        AddToList(copies, content, guid, messageType, senderAddress, receiverAddress, brokerToOtherBroker1, brokerToOtherBroker2);
                                                    }
                                                    else
                                                    {
                                                        ErrorChecker(error);
                                                    }

                                                    if (brokerRequestPush.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1)))
                                                    {
                                                        string receiverAddress = request[0].ReadString();
                                                        string identity        = request[1].ReadString();
                                                        string content         = request[2].ReadString();
                                                        string messageType     = "REQ";
                                                        string senderAddress   = brokerRequestPush.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1);

                                                        Guid guid = Guid.NewGuid();
                                                        Console.WriteLine("{0} <- {1} : [{2}]", brokerIdentity, identity, guid.ToString());
                                                        CreateFile(guid, content);
                                                        WriteToFile(fileRequest, guid);
                                                        AddToList(requestEndpoints, content, guid, identity, senderAddress, receiverAddress, brokerResponsePull);
                                                        AddToList(copies, content, guid, messageType, senderAddress, receiverAddress, brokerToOtherBroker1, brokerToOtherBroker2);
                                                    }
                                                    else
                                                    {
                                                        ErrorChecker(error);
                                                    }

                                                    if (brokerRequestPub.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1)))
                                                    {
                                                        string topic         = request[0].ReadString();
                                                        string identity      = request[1].ReadString();
                                                        string content       = request[2].ReadString();
                                                        string messageType   = "REQ";
                                                        string senderAddress = brokerRequestPub.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1);

                                                        Guid guid = Guid.NewGuid();
                                                        Console.WriteLine("{0} <- {1} : [{2}]", brokerIdentity, identity, guid.ToString());
                                                        CreateFile(guid, content, topic);
                                                        WriteToFile(fileRequest, guid);

                                                        AddToList(requestEndpoints, content, guid, identity, senderAddress, topic, brokerResponseSub);
                                                        AddToList(copies, content, guid, messageType, senderAddress, topic, brokerToOtherBroker1, brokerToOtherBroker2);
                                                    }
                                                    else
                                                    {
                                                        ErrorChecker(error);
                                                    }

                                                    int counter = 1;
                                                    do
                                                    {
                                                        if (brokerFromBrokers.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(100)))
                                                        {
                                                            string identity        = request[0].ReadString();
                                                            string content         = request[1].ReadString();
                                                            string uid             = request[2].ReadString();
                                                            string messageType     = request[3].ReadString();
                                                            string senderAddress   = null;
                                                            string receiverAddress = null;

                                                            if (request.Count > 5)
                                                            {
                                                                senderAddress   = request[4].ReadString();
                                                                receiverAddress = request[5].ReadString();
                                                            }
                                                            else if (request.Count > 4)
                                                            {
                                                                senderAddress = request[4].ReadString();
                                                            }

                                                            ZSocket socket2 = null;
                                                            ZSocket socket  = null;

                                                            if ((brokerIdentity == "Broker1" & identity == "Broker2") ||
                                                                (brokerIdentity == "Broker2" & identity == "Broker1") ||
                                                                (brokerIdentity == "Broker3" & identity == "Broker1"))
                                                            {
                                                                socket = brokerToOtherBroker1;
                                                            }
                                                            else if ((brokerIdentity == "Broker1" & identity == "Broker3") ||
                                                                     (brokerIdentity == "Broker2" & identity == "Broker3") ||
                                                                     (brokerIdentity == "Broker3" & identity == "Broker2"))
                                                            {
                                                                socket = brokerToOtherBroker2;
                                                            }

                                                            if (messageType == "CONCOP")
                                                            {
                                                                RemoveFromList(copies, Guid.Parse(uid), content, socket);
                                                            }
                                                            else
                                                            {
                                                                if (messageType == "REQ")
                                                                {
                                                                    if (AddressforClientReq.Contains(senderAddress))
                                                                    {
                                                                        socket2 = brokerResponse;
                                                                    }
                                                                    else if (AddressforClientPush.Contains(senderAddress))
                                                                    {
                                                                        socket2 = brokerResponsePull;
                                                                    }
                                                                    else if (AddressforClientPub.Contains(senderAddress))
                                                                    {
                                                                        socket2 = brokerResponseSub;
                                                                    }

                                                                    AddToList(requestEndpoints, content, Guid.Parse(uid), identity, senderAddress, receiverAddress, socket2);
                                                                }
                                                                else if (messageType == "REP")
                                                                {
                                                                    if (AddressforClientReq.Contains(senderAddress))
                                                                    {
                                                                        var list = GetFromList(requestEndpoints, Guid.Parse(uid));

                                                                        if (list != null)
                                                                        {
                                                                            string identity2 = list[2].ToString();
                                                                            AddToList(responseEndpoints, content, Guid.Parse(uid), identity2, senderAddress, null, brokerRequest);
                                                                        }
                                                                    }

                                                                    RemoveFromList(requestEndpoints, Guid.Parse(uid));
                                                                }
                                                                else if (messageType == "CON")
                                                                {
                                                                    RemoveFromList(responseEndpoints, Guid.Parse(uid));
                                                                }
                                                                Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), messageType, uid, "CONCOP", null, null);
                                                            }
                                                        }
                                                        else
                                                        {
                                                            ErrorChecker(error);
                                                        }
                                                        counter++;
                                                    }while (copies.Any() & counter < 4);

                                                    if (brokerResponse.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1)))
                                                    {
                                                        string    uid         = request[2].ReadString();
                                                        string    identity    = request[3].ReadString();
                                                        string    content     = request[4].ReadString();
                                                        string    messageType = "REP";
                                                        ArrayList list        = GetFromList(requestEndpoints, Guid.Parse(uid));
                                                        string    address     = list[4].ToString();
                                                        string    identity2   = list[2].ToString();

                                                        Console.WriteLine("{0} <- {1} : [{2} {3}]", brokerIdentity, identity, uid, messageType);
                                                        MoveFile(uid, content);
                                                        WriteToFile(fileResponse, Guid.Parse(uid));
                                                        UpdateFile(fileRequest, uid);
                                                        RemoveFromList(requestEndpoints, Guid.Parse(uid));
                                                        AddToList(responseEndpoints, content, Guid.Parse(uid), identity2, address, null, brokerRequest);
                                                        AddToList(copies, content, Guid.Parse(uid), messageType, address, null, brokerToOtherBroker1, brokerToOtherBroker2);
                                                    }
                                                    else
                                                    {
                                                        ErrorChecker(error);
                                                    }
                                                }
                                            }
        }
Ejemplo n.º 33
0
        // asynchronous server

        static void Main(string[] args)
        {
            var options = new Options();
            var parser  = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            using (var context = ZContext.Create())
            {
                using (var socket = new ZSocket(context, ZSocketType.ROUTER))
                {
                    foreach (var bindEndPoint in options.BindEndPoints)
                    {
                        socket.Bind(bindEndPoint);
                    }

                    var opllItem = ZPollItem.CreateReceiver();

                    while (true)
                    {
                        Thread.Sleep(options.Delay);

                        ZMessage message;
                        ZError   error;

                        //
                        if (socket.PollIn(opllItem, out message, out error, new TimeSpan(10 * 1000)))
                        {
                            message.DumpZmsg("--------------------------");

                            var rcvdMsg = message[2].ReadString(Encoding.UTF8);
                            Console.WriteLine("Received: " + rcvdMsg);

                            //be carefull the message format
                            var outMsg = new ZMessage();
                            outMsg.Add(message[0]);
                            outMsg.Add(new ZFrame());

                            var replyMsg   = options.ReplyMessage.Replace("#msg#", rcvdMsg);
                            var replyFrame = new ZFrame(replyMsg);
                            outMsg.Add(replyFrame);

                            Console.WriteLine("Sending : " + replyMsg + Environment.NewLine);

                            socket.Send(outMsg);
                        }


                        //2) sync
                        //using (ZMessage identity = socket.ReceiveMessage())
                        //{
                        //    identity.DumpZmsg("--------------------------");

                        //    var rcvdMsg = identity[2].ReadString(Encoding.UTF8);
                        //    Console.WriteLine("Received: " + rcvdMsg);

                        //    //be carefull the message format
                        //    var outMsg = new ZMessage();
                        //    outMsg.Add(identity[0]);
                        //    outMsg.Add(new ZFrame());

                        //    var replyMsg = options.ReplyMessage.Replace("#msg#", rcvdMsg);
                        //    var replyFrame = new ZFrame(replyMsg);
                        //    outMsg.Add(replyFrame);

                        //    Console.WriteLine("Sending : " + replyMsg + Environment.NewLine);

                        //    socket.Send(outMsg);
                        //}
                    }
                }
            }
        }
Ejemplo n.º 34
0
 public override int GetNumberOfUsersOnline()
 {
     DateTime DateActive = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(Convert.ToDouble(Membership.UserIsOnlineTimeWindow)));
     using (var Context = new ZContext())
     {
         return Context.Users.Where(Usr => Usr.LastActivityDate > DateActive).Count();
     }
 }
Ejemplo n.º 35
0
        static void Main(string[] args)
        {
            using (var context = new ZContext())
                using (var backend = new ZSocket(context, ZSocketType.ROUTER))
                    using (var frontend = new ZSocket(context, ZSocketType.ROUTER))
                    {
                        backend.Bind("tcp://*:5556");
                        frontend.Bind("tcp://*:5555");

                        // List of available workers
                        var workers = new List <Worker>();

                        // Send out heartbeats at regular intervals
                        DateTime heartbeat_at = DateTime.UtcNow + Worker.PPP_HEARTBEAT_INTERVAL;

                        // Create a Receiver ZPollItem (ZMQ_POLLIN)
                        var poll = ZPollItem.CreateReceiver();

                        ZError   error;
                        ZMessage incoming;

                        while (true)
                        {
                            // Handle worker activity on backend
                            if (backend.PollIn(poll, out incoming, out error, Worker.PPP_TICK))
                            {
                                using (incoming)
                                {
                                    incoming.DumpZmsg("--------from worker---------");

                                    // Any sign of life from worker means it's ready
                                    ZFrame identity = incoming.Unwrap();
                                    var    worker   = new Worker(identity);
                                    workers.Ready(worker);

                                    // Validate control message, or return reply to client
                                    if (incoming.Count == 1)
                                    {
                                        string message = incoming[0].ReadString();
                                        if (message == Worker.PPP_READY)
                                        {
                                            Console.WriteLine("I:        worker ready ({0})", worker.IdentityString);
                                        }
                                        else if (message == Worker.PPP_HEARTBEAT)
                                        {
                                            Console.WriteLine("I: receiving heartbeat ({0})", worker.IdentityString);
                                        }
                                        else
                                        {
                                            ProgramerHelper.Console_WriteZMessage("E: invalid message from worker", incoming);
                                        }
                                    }
                                    else
                                    {
                                        if (ProgramerHelper.Verbose)
                                        {
                                            ProgramerHelper.Console_WriteZMessage("I: [backend sending to frontend] ({0})", incoming, worker.IdentityString);
                                        }

                                        frontend.Send(incoming);
                                    }
                                }
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    break; // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }

                            // Handle client activity on frontend
                            if (workers.Count > 0)
                            {
                                // Poll frontend only if we have available workers
                                if (frontend.PollIn(poll, out incoming, out error, Worker.PPP_TICK))
                                {
                                    // Now get next client request, route to next worker
                                    using (incoming)
                                    {
                                        ZFrame workerIdentity = workers.Next();
                                        incoming.Prepend(workerIdentity);

                                        if (ProgramerHelper.Verbose)
                                        {
                                            ProgramerHelper.Console_WriteZMessage("I: [frontend sending to backend] ({0})", incoming, workerIdentity.ReadString());
                                        }

                                        backend.Send(incoming);
                                    }
                                }
                                else
                                {
                                    if (error == ZError.ETERM)
                                    {
                                        break; // Interrupted
                                    }
                                    if (error != ZError.EAGAIN)
                                    {
                                        throw new ZException(error);
                                    }
                                }
                            }

                            // We handle heartbeating after any socket activity. First, we send
                            // heartbeats to any idle workers if it's time. Then, we purge any
                            // dead workers:
                            if (DateTime.UtcNow > heartbeat_at)
                            {
                                heartbeat_at = DateTime.UtcNow + Worker.PPP_HEARTBEAT_INTERVAL;

                                foreach (Worker worker in workers)
                                {
                                    using (var outgoing = new ZMessage())
                                    {
                                        outgoing.Add(ZFrame.CopyFrom(worker.Identity));
                                        outgoing.Add(new ZFrame(Worker.PPP_HEARTBEAT));

                                        Console.WriteLine("I:   sending heartbeat ({0})", worker.IdentityString);
                                        backend.Send(outgoing);
                                    }
                                }
                            }

                            workers.Purge();
                        }

                        // When we're done, clean up properly
                        foreach (Worker worker in workers)
                        {
                            worker.Dispose();
                        }
                    }
        }
Ejemplo n.º 36
0
        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            if (providerUserKey is Guid) { }
            else
            {
                return null;
            }

            using (var Context = new ZContext())
            {
                User User = null;
                User = Context.Users.Find(providerUserKey);
                if (User != null)
                {
                    if (userIsOnline)
                    {
                        User.LastActivityDate = DateTime.UtcNow;
                        Context.SaveChanges();
                    }
                    return new MembershipUser(Membership.Provider.Name, User.Username, User.UserId, User.Email, null, null, User.IsApproved, User.IsLockedOut, User.CreateDate.Value, User.LastLoginDate.Value, User.LastActivityDate.Value, User.LastPasswordChangedDate.Value, User.LastLockoutDate.Value);
                }
                else
                {
                    return null;
                }
            }
        }
Ejemplo n.º 37
0
        public static void Main(string[] args)
        {
            string UserName;

            Console.Write("Enter your name: ");
            UserName = Console.ReadLine();

            using (var context = new ZContext())
                using (var subscriber = new ZSocket(context, ZSocketType.SUB))
                    using (var requester = new ZSocket(context, ZSocketType.REQ))
                    {
                        // First, connect our subscriber socket
                        subscriber.Connect("tcp://127.0.0.1:8080");
                        subscriber.SubscribeAll();

                        // 0MQ is so fast, we need to wait a while…
                        Thread.Sleep(1);

                        // Second, synchronize with publisher
                        requester.Connect("tcp://127.0.0.1:8081");

                        // - send a synchronization request
                        requester.Send(new ZFrame());

                        // - wait for synchronization reply
                        //requester.ReceiveFrame();

                        // Third, get our updates and report how many we got
                        while (true)
                        {
                            // Send
                            using (ZFrame txt = requester.ReceiveFrame())
                            {
                                string requestText;
                                Console.Write("Enter your message: ");
                                requestText = Console.ReadLine();
                                Console.WriteLine();
                                requestText = txt.ReadString();
                                Console.WriteLine("Sending {0}: {1}...", UserName, requestText);
                                requester.Send(new ZFrame(requestText));
                            }

                            // Receive

                            using (ZFrame frame = subscriber.ReceiveFrame())
                            {
                                string text = frame.ReadString();
                                Console.WriteLine("Received {0} updates.", frame.ReadString());

                                /*if (text == "TEST")
                                 * {
                                 *  Console.WriteLine(text);
                                 * }*/

                                // frame.Position = 0;
                                // Console.WriteLine("Receiving {0}…", frame.ReadInt32());
                            }
                            //Console.WriteLine("Received {0} updates.", i);
                        }
                    }
        }
Ejemplo n.º 38
0
 public override bool UnlockUser(string userName)
 {
     using (var Context = new ZContext())
     {
         User User = null;
         User = Context.Users.FirstOrDefault(Usr => Usr.Username == userName);
         if (User != null)
         {
             User.IsLockedOut = false;
             User.PasswordFailuresSinceLastSuccess = 0;
             Context.SaveChanges();
             return true;
         }
         else
         {
             return false;
         }
     }
 }
Ejemplo n.º 39
0
 protected override ZSocket CreateSocket(ZContext context)
 {
     return(new ZSocket(context, ZSocketType.PULL));
 }
Ejemplo n.º 40
0
 public override bool ChangePassword(string username, string oldPassword, string newPassword)
 {
     if (string.IsNullOrEmpty(username))
     {
         return false;
     }
     if (string.IsNullOrEmpty(oldPassword))
     {
         return false;
     }
     if (string.IsNullOrEmpty(newPassword))
     {
         return false;
     }
     using (var Context = new ZContext())
     {
         User User = null;
         User = Context.Users.FirstOrDefault(Usr => Usr.Username == username);
         if (User == null)
         {
             return false;
         }
         String HashedPassword = User.Password;
         Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, oldPassword));
         if (VerificationSucceeded)
         {
             User.PasswordFailuresSinceLastSuccess = 0;
         }
         else
         {
             int Failures = User.PasswordFailuresSinceLastSuccess;
             if (Failures < MaxInvalidPasswordAttempts)
             {
                 User.PasswordFailuresSinceLastSuccess += 1;
                 User.LastPasswordFailureDate = DateTime.UtcNow;
             }
             else if (Failures >= MaxInvalidPasswordAttempts)
             {
                 User.LastPasswordFailureDate = DateTime.UtcNow;
                 User.LastLockoutDate = DateTime.UtcNow;
                 User.IsLockedOut = true;
             }
             Context.SaveChanges();
             return false;
         }
         String NewHashedPassword = Crypto.HashPassword(newPassword);
         if (NewHashedPassword.Length > 128)
         {
             return false;
         }
         User.Password = NewHashedPassword;
         User.LastPasswordChangedDate = DateTime.UtcNow;
         Context.SaveChanges();
         return true;
     }
 }
Ejemplo n.º 41
0
        // The main task begins by setting-up its frontend and backend sockets
        // and then starting its client and worker tasks:
        public static void Peering2(IDictionary <string, string> dict, string[] args)
        {
            // First argument is this broker's name
            // Other arguments are our peers' names
            //
            if (args == null || args.Length < 3)
            {
                if (args != null && args.Length == 1)
                {
                    args = new string[] { args[0], "Me", "You" };
                }
                else
                {
                    Console.WriteLine("Usage: {0} Peering2 Hello Me You", AppDomain.CurrentDomain.FriendlyName);
                    Console.WriteLine("       {0} Peering2 Message You Me", AppDomain.CurrentDomain.FriendlyName);
                    return;
                }
            }

            string message = args[0];

            string name = args[1];

            Console.WriteLine("I: preparing broker as {0}", name);

            using (var context = ZContext.Create())
                using (var cloudFrontend = ZSocket.Create(context, ZSocketType.ROUTER))
                    using (var cloudBackend = ZSocket.Create(context, ZSocketType.ROUTER))
                        using (var localFrontend = ZSocket.Create(context, ZSocketType.ROUTER))
                            using (var localBackend = ZSocket.Create(context, ZSocketType.ROUTER))
                            {
                                // Bind cloud frontend to endpoint
                                cloudFrontend.IdentityString = name;
                                cloudFrontend.Bind("tcp://127.0.0.1:" + Peering2_GetPort(name) + 0);

                                // Connect cloud backend to all peers
                                cloudBackend.IdentityString = name;
                                for (int i = 2; i < args.Length; ++i)
                                {
                                    string peer = args[i];
                                    Console.WriteLine("I: connecting to cloud frontend at {0}", peer);
                                    cloudBackend.Connect("tcp://127.0.0.1:" + Peering2_GetPort(peer) + 0);
                                }

                                // Prepare local frontend and backend
                                localFrontend.Bind("tcp://127.0.0.1:" + Peering2_GetPort(name) + 1);
                                localBackend.Bind("tcp://127.0.0.1:" + Peering2_GetPort(name) + 2);

                                // Get user to tell us when we can start...
                                Console.WriteLine("Press ENTER when all brokers are started...");
                                Console.ReadKey(true);

                                // Start local workers
                                for (int i = 0; i < Peering2_Workers; ++i)
                                {
                                    int j = i; new Thread(() => Peering2_WorkerTask(context, j, name)).Start();
                                }

                                // Start local clients
                                for (int i = 0; i < Peering2_Clients; ++i)
                                {
                                    int j = i; new Thread(() => Peering2_ClientTask(context, j, name, message)).Start();
                                }

                                // Here, we handle the request-reply flow. We're using load-balancing
                                // to poll workers at all times, and clients only when there are one
                                // or more workers available.

                                // Least recently used queue of available workers
                                var workers = new List <string>();

                                ZError   error;
                                ZMessage incoming;
                                TimeSpan?wait;
                                var      poll = ZPollItem.CreateReceiver();

                                while (true)
                                {
                                    // If we have no workers, wait indefinitely
                                    wait = workers.Count > 0 ? (TimeSpan?)TimeSpan.FromMilliseconds(1000) : null;

                                    // Poll localBackend
                                    if (localBackend.PollIn(poll, out incoming, out error, wait))
                                    {
                                        // Handle reply from local worker
                                        string identity = incoming[0].ReadString();
                                        workers.Add(identity);

                                        // If it's READY, don't route the message any further
                                        string hello = incoming[2].ReadString();
                                        if (hello == "READY")
                                        {
                                            incoming.Dispose();
                                            incoming = null;
                                        }
                                    }
                                    else if (error == ZError.EAGAIN && cloudBackend.PollIn(poll, out incoming, out error, wait))
                                    {
                                        // We don't use peer broker identity for anything

                                        // string identity = incoming[0].ReadString();

                                        // string ok = incoming[2].ReadString();
                                    }
                                    else
                                    {
                                        if (error == ZError.ETERM)
                                        {
                                            return;             // Interrupted
                                        }
                                        if (error != ZError.EAGAIN)
                                        {
                                            throw new ZException(error);
                                        }
                                    }

                                    if (incoming != null)
                                    {
                                        // Route reply to cloud if it's addressed to a broker
                                        string identity = incoming[0].ReadString();

                                        for (int i = 2; i < args.Length; ++i)
                                        {
                                            if (identity == args[i])
                                            {
                                                using (incoming)
                                                    cloudFrontend.Send(incoming);

                                                incoming = null;
                                                break;
                                            }
                                        }
                                    }

                                    // Route reply to client if we still need to
                                    if (incoming != null)
                                    {
                                        using (incoming)
                                            localFrontend.Send(incoming);

                                        incoming = null;
                                    }

                                    // Now we route as many client requests as we have worker capacity
                                    // for. We may reroute requests from our local frontend, but not from //
                                    // the cloud frontend. We reroute randomly now, just to test things
                                    // out. In the next version, we'll do this properly by calculating
                                    // cloud capacity://

                                    var rnd = new Random();

                                    while (workers.Count > 0)
                                    {
                                        int reroutable = 0;

                                        // We'll do peer brokers first, to prevent starvation

                                        if (localFrontend.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(64)))
                                        {
                                            reroutable = 0;
                                        }
                                        else if (error == ZError.EAGAIN && cloudFrontend.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(64)))
                                        {
                                            reroutable = 1;
                                        }
                                        else
                                        {
                                            if (error == ZError.ETERM)
                                            {
                                                return;                 // Interrupted
                                            }
                                            if (error == ZError.EAGAIN)
                                            {
                                                break;                  // No work, go back to backends
                                            }
                                            throw new ZException(error);
                                        }

                                        using (incoming)
                                        {
                                            // If reroutable, send to cloud 25% of the time
                                            // Here we'd normally use cloud status information
                                            //
                                            if (reroutable == 1 && rnd.Next(4) == 0)
                                            {
                                                // Route to random broker peer

                                                int peer = rnd.Next(args.Length - 2) + 2;

                                                incoming.ReplaceAt(0, new ZFrame(args[peer]));

                                                /* using (var outgoing = new ZMessage())
                                                 * {
                                                 *      outgoing.Add(new ZFrame(args[peer]));
                                                 *      outgoing.Add(new ZFrame());
                                                 *      outgoing.Add(incoming[2]);
                                                 *
                                                 *      cloudBackend.Send(outgoing);
                                                 * } /**/

                                                cloudBackend.Send(incoming);
                                            }
                                            else
                                            {
                                                // Route to local broker peer

                                                string peer = workers[0];

                                                workers.RemoveAt(0);
                                                incoming.ReplaceAt(0, new ZFrame(peer));

                                                /* using (var outgoing = new ZMessage())
                                                 * {
                                                 *      outgoing.Add(new ZFrame(peer));
                                                 *      outgoing.Add(new ZFrame());
                                                 *      outgoing.Add(incoming[2]);
                                                 *
                                                 *      localBackend.Send(outgoing);
                                                 * } /**/

                                                localBackend.Send(incoming);
                                            }
                                        }
                                    }
                                }
                            }
        }
Ejemplo n.º 42
0
 public override string[] GetAllRoles()
 {
     using (var Context = new ZContext())
     {
         return Context.Roles.Select(Rl => Rl.RoleName).ToArray();
     }
 }
Ejemplo n.º 43
0
        public static void WUClient(IDictionary <string, string> dict, string[] args)
        {
            //
            // Weather update client
            // Connects SUB socket to tcp://localhost:5556
            // Collects weather updates and finds avg temp in zipcode
            //
            // Author: metadings
            //

            if (args == null || args.Length < 2)
            {
                Console.WriteLine();
                Console.WriteLine("Usage: ./{0} WUClient [ZipCode] [Endpoint]", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine();
                Console.WriteLine("    ZipCode   The zip code to subscribe. Default is 72622 Nürtingen");
                Console.WriteLine("    Endpoint  Where WUClient should connect to.");
                Console.WriteLine("              Default is tcp://127.0.0.1:5556");
                Console.WriteLine();
                if (args.Length < 1)
                {
                    args = new string[] { "72622", "tcp://127.0.0.1:5556" }
                }
                ;
                else
                {
                    args = new string[] { args[0], "tcp://127.0.0.1:5556" }
                };
            }

            // Socket to talk to server
            using (var context = ZContext.Create())
                using (var subscriber = ZSocket.Create(context, ZSocketType.SUB))
                {
                    string connect_to = args[1];
                    Console.WriteLine("I: Connecting to {0}...", connect_to);
                    subscriber.Connect(connect_to);

                    foreach (IPAddress address in WUProxy_GetPublicIPs())
                    {
                        var epgmAddress = string.Format("epgm://{0};239.192.1.1:8100", address);
                        Console.WriteLine("I: Connecting to {0}...", epgmAddress);
                        subscriber.Connect(epgmAddress);
                    }

                    // Subscribe to zipcode
                    string zipCode = args[0];
                    Console.WriteLine("I: Subscribing to zip code {0}...", zipCode);
                    subscriber.Subscribe(zipCode);

                    // Process 10 updates
                    int  i = 0;
                    long total_temperature = 0;
                    for (; i < 20; ++i)
                    {
                        using (var replyFrame = subscriber.ReceiveFrame())
                        {
                            string reply = replyFrame.ReadString();

                            Console.WriteLine(reply);
                            total_temperature += Convert.ToInt64(reply.Split(' ')[1]);
                        }
                    }
                    Console.WriteLine("Average temperature for zipcode '{0}' was {1}°", zipCode, (total_temperature / i));
                }
        }
    }
Ejemplo n.º 44
0
 public override string[] GetUsersInRole(string roleName)
 {
     if (string.IsNullOrEmpty(roleName))
     {
         return null;
     }
     using (var Context = new ZContext())
     {
         Role Role = null;
         Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName);
         if (Role != null)
         {
             return Role.Users.Select(Usr => Usr.Username).ToArray();
         }
         else
         {
             return null;
         }
     }
 }
Ejemplo n.º 45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PushPullDevice"/> class.
 /// </summary>
 public PushPullDevice(ZContext context)
     : base(context, FrontendType, BackendType)
 {
 }
Ejemplo n.º 46
0
 public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
 {
     using (var Context = new ZContext())
     {
         foreach (String username in usernames)
         {
             String us = username;
             User user = Context.Users.FirstOrDefault(U => U.Username == us);
             if (user != null)
             {
                 foreach (String roleName in roleNames)
                 {
                     String rl = roleName;
                     Role role = user.Roles.FirstOrDefault(R => R.RoleName == rl);
                     if (role != null)
                     {
                         user.Roles.Remove(role);
                     }
                 }
             }
         }
         Context.SaveChanges();
     }
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
 /// </summary>
 public StreamDealerDevice(ZContext context)
     : base(context, FrontendType, BackendType)
 {
 }
Ejemplo n.º 48
0
		/// <summary>
		/// Initializes a new instance of the <see cref="PubSubDevice"/> class.
		/// </summary>
		public PubSubDevice(ZContext context)
			: base(context, FrontendType, BackendType)
		{
			BackendSetup.SubscribeAll();
		}
Ejemplo n.º 49
0
        //  Titanic service
        //  Implements server side of http://rfc.zeromq.org/spec:9
        public static void Titanic(string[] args)
        {
            bool verbosedeep =
                (args.Any(e => e.ToLower().Equals("-vd") ||
                          e.ToLower().Equals("--verbosedeep")));


            bool verbose = verbosedeep || (args.Any(e => e.ToLower().Equals("-v") ||
                                                    e.ToLower().Equals("--verbose")));

            Console.WriteLine("Verbose: {0}", verbose);
            Console.WriteLine("Verbosedeep: {0}", verbosedeep);

            CancellationTokenSource cancellor = new CancellationTokenSource();

            Console.CancelKeyPress += (s, ea) =>
            {
                ea.Cancel = true;
                cancellor.Cancel();
            };

            ZContext ctx = new ZContext();

            using (var requestPipe = new ZActor(ctx, Titanic_Request, verbosedeep))
            {
                (new Thread(() => Titanic_Reply(ctx, cancellor, verbosedeep))).Start();
                (new Thread(() => Titanic_Close(ctx, cancellor, verbosedeep))).Start();
                ////////////////////
                /// HINT: Use requestPipe.Start instead of requestPipe.Start(cancellor)
                /// => with cancellor consturctor needed frontent pipe will not be initializes!!
                ////////////////////
                requestPipe.Start();
                Thread.Sleep(1500);


                // Main dispatcher loop
                while (true)
                {
                    //continue;
                    if (cancellor.IsCancellationRequested ||
                        (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
                    {
                        ctx.Shutdown();
                    }

                    var      path = Path.Combine(TitanicCommon.TITANIC_DIR, TitanicCommon.QUEUE_FILE);
                    var      p    = ZPollItem.CreateReceiver();
                    ZMessage msg;
                    ZError   error;
                    if (requestPipe.Frontend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1000)))
                    {
                        using (msg)
                        {
                            // Ensure message directory exists
                            Directory.CreateDirectory(TitanicCommon.TITANIC_DIR);

                            // Append UUID to queue, prefixed with '-' for pending
                            var uuid = Guid.Parse(msg.PopString());
                            using (var sw = File.AppendText(path))
                            {
                                sw.Write(TitanicCommon.QUEUE_LINEFORMAT, uuid);
                            }
                        }
                    }
                    else if (error.Equals(ZError.ETERM))
                    {
                        cancellor.Cancel();
                        break; // Interrupted
                    }
                    else if (error.Equals(ZError.EAGAIN))
                    //continue;
                    {
                        Thread.Sleep(1);
                    }
                    else
                    {
                        break; // Interrupted
                    }
                    // Brute force dispatcher
                    if (File.Exists(path))
                    {
                        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            int    numBytesRead   = 0;
                            int    numBytesToRead = (new UTF8Encoding().GetBytes(String.Format(TitanicCommon.QUEUE_LINEFORMAT, Guid.NewGuid()))).Length;
                            byte[] readBytes      = new byte[numBytesToRead];
                            while (numBytesToRead > 0)
                            {
                                var n = fs.Read(readBytes, 0, numBytesToRead);
                                if (n == 0)
                                {
                                    break;
                                }
                                var line = (new UTF8Encoding()).GetString(readBytes, 0, n);
                                //  UUID is prefixed with '-' if still waiting
                                if (line.StartsWith("-"))
                                {
                                    var uuid = Guid.Parse(line.Substring(1, Guid.NewGuid().ToString().Length));
                                    if (verbose)
                                    {
                                        "I: processing request {0}".DumpString(uuid);
                                    }
                                    if (Titanic_ServiceSuccess(uuid, cancellor))
                                    {
                                        //  Mark queue entry as processed
                                        var newval = (new UTF8Encoding()).GetBytes("+");
                                        fs.Seek(-n, SeekOrigin.Current);
                                        fs.Write(newval, 0, newval.Length);
                                        fs.Seek(n - newval.Length, SeekOrigin.Current);
                                    }
                                }
                                if (cancellor.IsCancellationRequested)
                                {
                                    break;
                                }

                                numBytesRead  += n;
                                numBytesToRead = n;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 50
0
        //
        // Broker peering simulation (part 1)
        // Prototypes the state flow
        //
        // Author: metadings
        //

        public static void Peering1(IDictionary <string, string> dict, string[] args)
        {
            // First argument is this broker's name
            // Other arguments are our peers' names
            //
            if (args == null || args.Length < 2)
            {
                Console.WriteLine();
                Console.WriteLine("Usage: {0} Peering1 World Receiver0", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine("       {0} Peering1 Receiver0 World", AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine();
                return;
            }
            string self = args[0];

            Console.WriteLine("I: preparing broker as {0}", self);

            using (var context = new ZContext())
                using (var backend = new ZSocket(context, ZSocketType.PUB))
                    using (var frontend = new ZSocket(context, ZSocketType.SUB))
                    {
                        // Bind backend to endpoint
                        backend.Bind("tcp://127.0.0.1:" + Peering1_GetPort(self));

                        // Connect frontend to all peers
                        frontend.SubscribeAll();
                        for (int i = 1; i < args.Length; ++i)
                        {
                            string peer = args[i];
                            Console.WriteLine("I: connecting to state backend at {0}", peer);
                            frontend.Connect("tcp://127.0.0.1:" + Peering1_GetPort(peer));
                        }

                        // The main loop sends out status messages to peers, and collects
                        // status messages back from peers. The zmq_poll timeout defines
                        // our own heartbeat:

                        ZError   error;
                        ZMessage incoming;
                        var      poll = ZPollItem.CreateReceiver();
                        var      rnd  = new Random();

                        while (true)
                        {
                            // Poll for activity, or 1 second timeout
                            if (!frontend.PollIn(poll, out incoming, out error, TimeSpan.FromSeconds(1)))
                            {
                                if (error == ZError.EAGAIN)
                                {
                                    error = ZError.None;

                                    using (var output = new ZMessage())
                                    {
                                        output.Add(new ZFrame(self));

                                        var outputNumber = ZFrame.Create(4);
                                        outputNumber.Write(rnd.Next(10));
                                        output.Add(outputNumber);

                                        backend.Send(output);
                                    }

                                    continue;
                                }
                                if (error == ZError.ETERM)
                                {
                                    return;
                                }

                                throw new ZException(error);
                            }
                            using (incoming)
                            {
                                string peer_name = incoming[0].ReadString();
                                int    available = incoming[1].ReadInt32();
                                Console.WriteLine("{0} - {1} workers free", peer_name, available);
                            }
                        }
                    }
        }
Ejemplo n.º 51
0
 public ZmqContext()
 {
     Context = new ZContext();
 }
Ejemplo n.º 52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamerDevice"/> class.
 /// </summary>
 public PushPullDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
     : base(context, FrontendType, BackendType)
 {
     FrontendSetup.Bind(frontendBindAddr);
     BackendSetup.Bind(backendBindAddr);
 }
Ejemplo n.º 53
0
        void _RecvRoute(object obj)
        {
            using (var ctx = new ZContext())
                using (var skt = new ZSocket(ctx, ZSocketType.SUB))
                {
                    skt.SubscribeAll();
                    //skt.
                    //skt.SetOption(ZSocketOption.IDENTITY, "yoyotek.cn");
                    //skt.SetOption(ZSocketOption.RCVHWM, 0);
                    //skt.Subscribe("BDPK");
                    // WDPK, 五档盘口
                    // SDPK, 十档盘口
                    // ZBCJ,逐笔成交
                    // ZBWT,逐笔委托
                    // ZBDD,逐笔大单
                    // BDPK,百档盘口
                    // QQPK,期权盘口
                    skt.ReceiveHighWatermark = 0;
                    skt.MulticastRate        = 10000;
                    skt.Connect(ConfigurationManager.AppSettings["ZMQServer"]);
                    while (true)
                    {
                        try
                        {
                            //var bytes = _udpClient.Receive(ref _ipEndPoint);

                            ZError zerr = new ZError(0);
                            //skt.SetOption(ZSocketOption.SUBSCRIBE, "");
                            var frms = skt.ReceiveFrames(100);

                            frms.ToList().ForEach(frm => {
                                var bytes = frm.Read();
                                //var str = frm.
                                //if (string.IsNullOrEmpty(str) || str == "UNKNOWN")
                                //{
                                //    return null;
                                //}
                                //else
                                //{
                                //    var dit = new Dictionary<string, string>();
                                //    str.Split(new char[] { ';' }).ToList().ForEach(kv =>
                                //    {
                                //        var pair = kv.Split(new char[] { '=' });
                                //        if (pair.Length == 2)
                                //            dit.Add(pair[0], pair[1]);
                                //    });
                                //    return dit;
                                //}

                                //writelog("dzh_recvthread.log", "thread is:" + Thread.CurrentThread.ManagedThreadId.ToString() + " received!");
                                _ResolveDatagram(bytes);


                                frm.Close();
                                if (_hsAltered.Any() && QuoteChanged != null)
                                {
                                    QuoteChanged();
                                }
                            });
                        }
                        catch (ThreadAbortException)
                        {
                            //LogManager.LogMgr.WriteLog(LogManager.LogFile.Trace, "UDP recv aborted.");
                        }
                        catch (System.Exception ex)
                        {
                            //LogManager.LogMgr.WriteLog(LogManager.LogFile.Error, "UDP recv err:" + ex.Message);
                            writelog(DateTime.Now.ToString("yyyyMMdd") + "\\exception.txt", ex.Message);
                        }
                    }
                }
        }
Ejemplo n.º 54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
 /// </summary>
 public StreamDealerDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
     : base(context, FrontendType, BackendType)
 {
     FrontendSetup.Bind(frontendBindAddr);
     BackendSetup.Bind(backendBindAddr);
 }
Ejemplo n.º 55
0
        public static void LVCache(IDictionary <string, string> dict, string[] args)
        {
            //
            // Last value cache
            // Uses XPUB subscription messages to re-send data
            //
            // Author: metadings
            //

            using (var context = new ZContext())
                using (var frontend = new ZSocket(context, ZSocketType.SUB))
                    using (var backend = new ZSocket(context, ZSocketType.XPUB))
                    {
                        // Subscribe to every single topic from publisher
                        frontend.Bind("tcp://*:5557");
                        frontend.SubscribeAll();

                        backend.Bind("tcp://*:5558");

                        // Store last instance of each topic in a cache
                        var cache = new HashSet <LVCacheItem>();

                        // We route topic updates from frontend to backend, and
                        // we handle subscriptions by sending whatever we cached,
                        // if anything:
                        var      p = ZPollItem.CreateReceiver();
                        ZMessage msg;
                        ZError   error;
                        while (true)
                        {
                            // Any new topic data we cache and then forward
                            if (frontend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1)))
                            {
                                using (msg)
                                {
                                    string topic   = msg[0].ReadString();
                                    string current = msg[1].ReadString();

                                    LVCacheItem previous = cache.FirstOrDefault(item => topic == item.Topic);
                                    if (previous != null)
                                    {
                                        cache.Remove(previous);
                                    }
                                    cache.Add(new LVCacheItem {
                                        Topic = topic, Current = current
                                    });

                                    backend.Send(msg);
                                }
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    break;                      // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }

                            // When we get a new subscription, we pull data from the cache:
                            if (backend.PollIn(p, out msg, out error, TimeSpan.FromMilliseconds(1)))
                            {
                                using (msg)
                                {
                                    // Event is one byte 0=unsub or 1=sub, followed by topic
                                    byte subscribe = msg[0].ReadAsByte();
                                    if (subscribe == 0x01)
                                    {
                                        string      topic    = msg[0].ReadString();
                                        LVCacheItem previous = cache.FirstOrDefault(item => topic == item.Topic);
                                        if (previous != null)
                                        {
                                            Console.WriteLine("Sending cached topic {0}", topic);
                                            backend.SendMore(new ZFrame(previous.Topic));
                                            backend.Send(new ZFrame(previous.Current));
                                        }
                                        else
                                        {
                                            Console.WriteLine("Failed to send cached topic {0}!", topic);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (error == ZError.ETERM)
                                {
                                    break;                      // Interrupted
                                }
                                if (error != ZError.EAGAIN)
                                {
                                    throw new ZException(error);
                                }
                            }
                        }
                    }
        }
Ejemplo n.º 56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PushPullDevice"/> class.
 /// </summary>
 public PushPullDevice(ZContext context)
     : base(context, FrontendType, BackendType)
 {
 }
Ejemplo n.º 57
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamerDevice"/> class.
 /// </summary>
 public PushPullDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
     : base(context, FrontendType, BackendType)
 {
     FrontendSetup.Bind(frontendBindAddr);
     BackendSetup.Bind(backendBindAddr);
 }
Ejemplo n.º 58
0
            protected void Dispose(bool disposing)
            {
                if (disposing)
                {
                    // Destructor
                    if (Socket != null)
                    {
                        Socket.Dispose();
                        Socket = null;
                    }

                    if (_context != null)
                    {
                        // Do Context.Dispose()
                        _context.Dispose();
                        _context = null;
                    }
                }
            }
Ejemplo n.º 59
0
        public static void PPWorker(IDictionary <string, string> dict, string[] args)
        {
            if (args == null || args.Length == 0)
            {
                args = new string[] { "World" };
            }
            string name = args[0];

            ZError error;

            using (var context = ZContext.Create())
            {
                ZSocket worker = null;
                try                 // using (worker)
                {
                    if (null == (worker = PPWorker_CreateZSocket(context, name, out error)))
                    {
                        if (error == ZError.ETERM)
                        {
                            return;                             // Interrupted
                        }
                        throw new ZException(error);
                    }

                    // If liveness hits zero, queue is considered disconnected
                    int liveness = Worker.PPP_HEARTBEAT_LIVENESS;
                    int interval = Worker.PPP_INTERVAL_INIT;

                    // Send out heartbeats at regular intervals
                    DateTime heartbeat_at = DateTime.UtcNow + Worker.PPP_HEARTBEAT_INTERVAL;

                    ZMessage incoming;
                    int      cycles = 0;
                    var      poll   = ZPollItem.CreateReceiver();
                    var      rnd    = new Random();

                    while (true)
                    {
                        if (worker.PollIn(poll, out incoming, out error, Worker.PPP_TICK))
                        {
                            // Get message
                            // - 3-part envelope + content -> request
                            // - 1-part HEARTBEAT -> heartbeat
                            using (incoming)
                            {
                                // To test the robustness of the queue implementation we
                                // simulate various typical problems, such as the worker
                                // crashing or running very slowly. We do this after a few
                                // cycles so that the architecture can get up and running
                                // first:
                                if (incoming.Count >= 3)
                                {
                                    Console_WriteZMessage(incoming, "I: receiving reply");

                                    cycles++;
                                    if (cycles > 3 && rnd.Next(5) == 0)
                                    {
                                        Console.WriteLine("I: simulating a crash");
                                        return;
                                    }
                                    if (cycles > 3 && rnd.Next(3) == 0)
                                    {
                                        Console.WriteLine("I: simulating CPU overload");
                                        Thread.Sleep(100);
                                    }

                                    Thread.Sleep(1);                                            // Do some heavy work

                                    Console.WriteLine("I: sending reply");
                                    worker.Send(incoming);

                                    liveness = Worker.PPP_HEARTBEAT_LIVENESS;
                                }
                                // When we get a heartbeat message from the queue, it means the
                                // queue was (recently) alive, so we must reset our liveness
                                // indicator:
                                else if (incoming.Count == 1)
                                {
                                    string identity = incoming[0].ReadString();

                                    if (identity == Worker.PPP_HEARTBEAT)
                                    {
                                        Console.WriteLine("I: receiving heartbeat");
                                        liveness = Worker.PPP_HEARTBEAT_LIVENESS;
                                    }
                                    else
                                    {
                                        Console_WriteZMessage(incoming, "E: invalid message");
                                    }
                                }
                                else
                                {
                                    Console_WriteZMessage(incoming, "E: invalid message");
                                }
                            }
                            interval = Worker.PPP_INTERVAL_INIT;
                        }
                        else
                        {
                            if (error == ZError.ETERM)
                            {
                                break;                                  // Interrupted
                            }
                            if (error != ZError.EAGAIN)
                            {
                                throw new ZException(error);
                            }
                        }

                        if (error == ZError.EAGAIN)
                        {
                            // If the queue hasn't sent us heartbeats in a while, destroy the
                            // socket and reconnect. This is the simplest most brutal way of
                            // discarding any messages we might have sent in the meantime:
                            if (--liveness == 0)
                            {
                                Console.WriteLine("W: heartbeat failure, can't reach queue");
                                Console.WriteLine("W: reconnecting in {0} ms", interval);
                                Thread.Sleep(interval);

                                if (interval < Worker.PPP_INTERVAL_MAX)
                                {
                                    interval *= 2;
                                }
                                else
                                {
                                    Console.WriteLine("E: interrupted");
                                    break;
                                }

                                worker.Dispose();
                                if (null == (worker = PPWorker_CreateZSocket(context, name, out error)))
                                {
                                    if (error == ZError.ETERM)
                                    {
                                        break;                                          // Interrupted
                                    }
                                    throw new ZException(error);
                                }
                                liveness = Worker.PPP_HEARTBEAT_LIVENESS;
                            }
                        }

                        // Send heartbeat to queue if it's time
                        if (DateTime.UtcNow > heartbeat_at)
                        {
                            heartbeat_at = DateTime.UtcNow + Worker.PPP_HEARTBEAT_INTERVAL;

                            Console.WriteLine("I:   sending heartbeat");
                            using (var outgoing = new ZFrame(Worker.PPP_HEARTBEAT))
                            {
                                worker.Send(outgoing);
                            }
                        }
                    }
                }
                finally
                {
                    if (worker != null)
                    {
                        worker.Dispose();
                        worker = null;
                    }
                }
            }
        }