protected override void OnClosed(EventArgs e)
        {
            m_session.Dispose();
            m_session = null;

            base.OnClosed(e);
        }
Example #2
0
 // Disconnect
 public void Disconnect(IServerSession session)
 {
     try
     {
         try
         {
             // Clean up any session resources
             InternalDisconnect((ServerSession)session);
         }
         catch (Exception E)
         {
             throw WrapException(E);
         }
     }
     finally
     {
         BeginCall();
         try
         {
             // Remove the session from the sessions list
             _sessions.SafeDisown((ServerSession)session);
         }
         finally
         {
             EndCall();
         }
     }
 }
Example #3
0
        /// <summary>Join a local game.</summary>
        /// <param name="server">the local server to join.</param>
        /// <param name="playerName">the name with which to register.</param>
        /// <param name="playerData">additional data to be associated with our player.</param>
        public void Join(IServerSession server, string playerName, object playerData)
        {
            if (ConnectionState != ClientState.Unconnected)
            {
                throw new InvalidOperationException("Must leave the current session first.");
            }
            if (!(server is HybridServerSession <TPlayerData>))
            {
                throw new InvalidOperationException("Incompatible server type.");
            }
            if (!(playerData is TPlayerData))
            {
                throw new ArgumentException("Invalid type.", "playerData");
            }

            Logger.Debug("Begin connecting to local server.");
            _playerName     = playerName;
            _playerData     = (TPlayerData)playerData;
            ConnectionState = ClientState.Connecting;

            // Check if the server is already full.
            if (server.PlayerCount >= server.MaxPlayers)
            {
                Logger.Debug("Join failed, server already full.");
                Reset();
                return;
            }

            // Create the two 'pipes' we use to pass data from client to server
            // and vice versa.
            var toClient = new SlidingStream();
            var toServer = new SlidingStream();

            // Our stream is the one where the sink is the server.
            // The server gets one in the other direction (see below).
            _stream = new SlidingPacketStream(toClient, toServer);
            using (var packet = new Packet())
            {
                using (var packetInner = new Packet())
                {
                    packetInner.
                    Write(_playerName).
                    Write(_playerData);
                    packet.
                    Write((byte)SessionMessage.JoinRequest).
                    Write((IWritablePacket)packetInner);
                    var written = _stream.Write(packet);

                    // Statistics.
                    Info.PutOutgoingTraffic(written, TrafficTypes.Protocol);
                    Info.PutOutgoingPacketSize(written);
                    Info.PutOutgoingPacketCompression((packet.Length / (float)written) - 1f);
                }
            }

            // Let's try this. This can throw if the server is already
            // full, but that shouldn't happen, because we checked above.
            ((HybridServerSession <TPlayerData>)server).
            Add(new SlidingPacketStream(toServer, toClient));
        }
Example #4
0
        public void SetUpFixture()
        {
            FServerConfigurationManager = new SQLCEServerConfigurationManager();
            FConfiguration = FServerConfigurationManager.GetTestConfiguration("TestInstance");
            FServerConfigurationManager.ResetInstance();
            FServer = FServerConfigurationManager.GetServer();
            FServer.Start();

            IServerSession LSession = FServer.Connect(new SessionInfo("Admin", ""));

            try
            {
                IServerProcess LProcess = LSession.StartProcess(new ProcessInfo(LSession.SessionInfo));
                try
                {
                    LProcess.ExecuteScript("EnsureLibraryRegistered('Frontend');");
                    LProcess.ExecuteScript("EnsureLibraryRegistered('TestFramework.Coverage.Base');");
                }
                finally
                {
                    LSession.StopProcess(LProcess);
                }
            }
            finally
            {
                FServer.Disconnect(LSession);
            }
        }
 /// <summary>
 /// 处理消息
 /// </summary>
 /// <param name="message"></param>
 internal void Process(IServerSession origin, Message message)
 {
     foreach (var handler in _handlers)
     {
         handler.Process(origin, message);
     }
 }
Example #6
0
        /// <summary> Executes a D4 script. </summary>
        public static void ExecuteScript(string script, IServer server, SessionInfo sessionInfo)
        {
            IServerSession session = server.Connect(sessionInfo);

            try
            {
                IServerProcess process = session.StartProcess(new ProcessInfo(sessionInfo));
                try
                {
                    IServerScript localScript = process.PrepareScript(script);
                    try
                    {
                        localScript.Execute(null);
                    }
                    finally
                    {
                        process.UnprepareScript(localScript);
                    }
                }
                finally
                {
                    session.StopProcess(process);
                }
            }
            finally
            {
                server.Disconnect(session);
            }
        }
 protected void Distribute(IServerSession origin, Message msg, IEnumerable <string> destinations)
 {
     foreach (var destination in destinations)
     {
         Distribute(origin, msg, destination);
     }
 }
Example #8
0
 public override void Open()
 {
     if (_server == null)
     {
         _foreignServer = false;
         OnBeforeOpen();
         if (_alias == null)
         {
             throw new ProviderException(ProviderException.Codes.NoAliasSpecified);
         }
         _connection = new ServerConnection(_alias, true);
         _server     = _connection.Server;
         try
         {
             _alias.SessionInfo.Environment = "ADO.NET";
             _session       = _server.Connect(_alias.SessionInfo);
             _serverProcess = _session.StartProcess(new ProcessInfo(_alias.SessionInfo));
         }
         catch
         {
             _server        = null;
             _session       = null;
             _serverProcess = null;
             _connection.Dispose();
             _connection = null;
             throw;
         }
         OnAfterOpen();
     }
 }
Example #9
0
        private static bool UpdateMyAttribute(IServerSession session)
        {
            var        attrBroker         = session.DataAccess.Brokers.NodeAttributeDefinition;
            var        dacFactory         = session.DataAccess.ModelFactory;
            IChangeSet changes            = session.DataAccess.CreateChangeSet();
            INodeAttributeDefinition attr = dacFactory.CreateNodeAttributeDefinition();

            attr.DefaultValue = "hello";
            attrBroker.UpdateNodeAttributeDefinitions(changes, attr, dacFactory.CreateSelectorByFilter(dacFactory.CreateFilterExpression("Name LIKE \"" + ATTRIBUTE_NAME + "\"")));

            Console.Write("Updating my NodeAttributeDefinition... ");
            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    Console.WriteLine("success");
                    return(true);
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return(false);
                }
            }
        }
Example #10
0
 /// <summary>
 /// 处理消息
 /// </summary>
 /// <param name="message"></param>
 internal void EndProcess(IServerSession origin, Message message, HandlerContext ctx)
 {
     foreach (var handler in _handlers)
     {
         handler.EndProcess(origin, message, ctx);
     }
 }
        private static bool ActivateTrigger(IServerSession session)
        {
            Console.Write("Adding row to trigger payload table...");

            IChangeSet changes = session.DataAccess.CreateChangeSet();

            IDataRow row = session.ModelFactory.CreateDataRow();
            row.ActivationDate = DateTime.Now;
            row.ExpirationDate = DateTime.Now.AddMinutes(1);// short expirations are good on triggers, because they usually represent timely events and in the case of a player being offline you don't want it to get a wave of stale triggers
            row.SequenceNumber = 0;
            row.Values["foo"] = "bar";// the column names depend upon the actual columns in the trigger

            session.DataAccess.Brokers.DataTable.CreateDataRow(changes, g_triggerDataTableId, row);

            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    Console.WriteLine("success");
                    return true;
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return false;
                }
            }
        }
        private static bool ActivateTrigger(IServerSession session)
        {
            Console.Write("Adding row to trigger payload table...");

            IChangeSet changes = session.DataAccess.CreateChangeSet();

            IDataRow row = session.ModelFactory.CreateDataRow();

            row.ActivationDate = DateTime.Now;
            row.ExpirationDate = DateTime.Now.AddMinutes(1); // short expirations are good on triggers, because they usually represent timely events and in the case of a player being offline you don't want it to get a wave of stale triggers
            row.SequenceNumber = 0;
            row.Values["foo"]  = "bar";                      // the column names depend upon the actual columns in the trigger

            session.DataAccess.Brokers.DataTable.CreateDataRow(changes, g_triggerDataTableId, row);

            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    Console.WriteLine("success");
                    return(true);
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return(false);
                }
            }
        }
        public bool Remove(IServerSession session)
        {
            if (session == null)
            {
                return(false);
            }

            bool exist = false;

            lock (_sessions)
            {
                var unicastAddress = session.UnicastAddress;
                exist = _sessions.RemoveValue(unicastAddress, session);
                if (exist)
                {
                    LeaveAll(session);
                }
            }

            if (exist)
            {
                session.Close();
                ServerEvents.AsyncRaiseClientDisconnectedEvent(_server, session);
            }

            return(exist);
        }
Example #14
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientSessionHandle" /> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="options">The options.</param>
 /// <param name="coreSession">The wrapped session.</param>
 public ClientSessionHandle(IMongoClient client, ClientSessionOptions options, ICoreSessionHandle coreSession)
 {
     _client        = client;
     _options       = options;
     _coreSession   = coreSession;
     _serverSession = new ServerSession(coreSession.ServerSession);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="UPSyncDataSets"/> class.
        /// </summary>
        /// <param name="dataSetNames">
        /// The data set names.
        /// </param>
        /// <param name="incremental">
        /// if set to <c>true</c> [incremental].
        /// </param>
        /// <param name="session">
        /// The session.
        /// </param>
        /// <param name="crmDataStore">
        /// The CRM data store.
        /// </param>
        /// <param name="configStore">
        /// The configuration store.
        /// </param>
        /// <param name="theDelegate">
        /// The delegate.
        /// </param>
        public UPSyncDataSets(
            List <string> dataSetNames,
            bool incremental,
            IServerSession session,
            ICRMDataStore crmDataStore,
            IConfigurationUnitStore configStore,
            ISyncDataSetsDelegate theDelegate)
        {
            this.Delegate    = theDelegate;
            this.Session     = session;
            this.DataStore   = crmDataStore;
            this.ConfigStore = configStore;

            var dataSetArray = dataSetNames == null
                                   ? new List <UPSyncDataSet>()
                                   : new List <UPSyncDataSet>(dataSetNames.Count);
            var dataSets = dataSetNames?.Select(dataSetName => new UPSyncDataSet(dataSetName, incremental, crmDataStore));

            if (dataSets != null && dataSets.Any())
            {
                dataSetArray.AddRange(dataSets);
            }

            this.DataSets = dataSetArray;
        }
        /// <inheritdoc />
        public void ReleaseSession(IServerSession session)
        {
            lock (_lock)
            {
                var removeCount = 0;
                for (var i = 0; i < _pool.Count; i++)
                {
                    var pooledSession = _pool[i];
                    if (IsAboutToExpire(pooledSession))
                    {
                        pooledSession.Dispose();
                        removeCount++;
                    }
                    else
                    {
                        break;
                    }
                }
                _pool.RemoveRange(0, removeCount);

                if (IsAboutToExpire(session))
                {
                    session.Dispose();
                }
                else
                {
                    _pool.Add(session);
                }
            }
        }
        /// <summary>
        /// Creates a new document request uri by given Record Identification and Filename
        /// </summary>
        /// <param name="serverSession">The server session.</param>
        /// <param name="recordIdentification">The record identification.</param>
        /// <param name="filename">The filename.</param>
        /// <returns>
        /// Returns an <see cref="Uri" /> for document request.
        /// </returns>
        public static Uri DocumentRequestUrlForRecordIdentification(
            this IServerSession serverSession,
            string recordIdentification,
            string filename)
        {
            Dictionary <string, string> parameterDictionary;

            if (!string.IsNullOrEmpty(filename))
            {
                parameterDictionary = new Dictionary <string, string>
                {
                    { "Service", "Documents" },
                    { "InfoAreaId", recordIdentification.InfoAreaId() },
                    { "RecordId", recordIdentification.RecordId() },
                    { "FileName", filename }
                };
            }
            else
            {
                parameterDictionary = new Dictionary <string, string>
                {
                    { "Service", "Documents" },
                    { "InfoAreaId", recordIdentification.InfoAreaId() },
                    { "RecordId", recordIdentification.RecordId() },
                    { "FileName", filename }
                };
            }

            return(serverSession.CrmServer.MobileWebserviceUrl.AppendUriWithQueryString(parameterDictionary));
        }
Example #18
0
        public static int Main(string[] args)
        {
            // hook API logger
            Logger.SetLogSink(HandleLogEntry);

            try
            {
                string ncHostname = "JoshVM-2003";
                int    ncPort     = 80;

                using (IServerSession ncSession = CSAPI.Create().CreateServerSession(ncHostname, ncPort))
                {
                    if (!Authenticate(ncSession))
                    {
                        return(-1);
                    }

                    Console.Write("Creating proxied connection...");
                    INodeConnection playerConn;
                    using (var result = ncSession.CreateProxiedConnectionToNode((Oid)PLAYER_NODE_ID))
                    {
                        if (result.IsSuccess)
                        {
                            Console.WriteLine("success");
                            playerConn = result.Value;
                        }
                        else
                        {
                            Console.WriteLine("failed: " + result.ToString());
                            return(-2);
                        }
                    }

                    Console.Write("Querying proxied node info...");
                    playerConn.SocketTimeout = 30;
                    using (var result = playerConn.ExecuteCommand("Coolsign.System.GetInfo", null))
                    {
                        if (result.IsSuccess)
                        {
                            Console.WriteLine("success" + Console.Out.NewLine + result.ReadBody());
                        }
                        else
                        {
                            Console.WriteLine("failed: " + result.ToString());
                            return(-3);
                        }
                    }
                }

                return(0);
            }
            finally
            {
                Console.WriteLine("Press enter to continue...");
                Console.ReadLine();

                // unhook logger
                Logger.SetLogSink(null);
            }
        }
Example #19
0
        private static bool CreateMyAttribute(IServerSession session)
        {
            var        attrBroker         = session.DataAccess.Brokers.NodeAttributeDefinition;
            IChangeSet changes            = session.DataAccess.CreateChangeSet();
            INodeAttributeDefinition attr = session.DataAccess.ModelFactory.CreateNodeAttributeDefinition();

            attr.Id           = new Oid();
            attr.Name         = ATTRIBUTE_NAME;
            attr.DefaultValue = "hi";
            attrBroker.CreateNodeAttributeDefinition(changes, attr);

            Console.Write("Creating my NodeAttributeDefinition... ");
            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    // extract the actual id of the created attr def
                    Oid newId = result.IdMap[attr.Id];
                    Console.WriteLine("success, my attribute def has id {0}", newId);
                    return(true);
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return(false);
                }
            }
        }
Example #20
0
        private void CancelSave(IServerSession origin, Message message)
        {
            //保存内容
            var info = message.Header.GetObject("info");

            CancelSave(info);
        }
Example #21
0
        private void SendError(IServerSession origin, Message message, Exception exception)
        {
            var info = message.Header.GetObject("info");
            var msg  = CreateErrorMessage(info, exception);
            var o    = origin as RemoteSession;

            o.Send(msg);
        }
        /// <summary>
        /// Creates a new document request uri by given Document key.
        /// </summary>
        /// <param name="serverSession">The server session.</param>
        /// <param name="key">The key.</param>
        /// <returns>
        /// The <see cref="Uri" />.
        /// </returns>
        public static Uri DocumentRequestUrlForDocumentKey(this IServerSession serverSession, string key)
        {
            Dictionary <string, string> parameterDictionary = new Dictionary <string, string> {
                { "Service", "Documents" }, { "DocumentKey", key }
            };

            return(serverSession.CrmServer.MobileWebserviceUrl.AppendUriWithQueryString(parameterDictionary));
        }
Example #23
0
 internal ClientSessionHandle(IMongoClient client, ClientSessionOptions options, ICoreSessionHandle coreSession, IClock clock)
 {
     _client        = client;
     _options       = options;
     _coreSession   = coreSession;
     _serverSession = new ServerSession(coreSession.ServerSession);
     _clock         = clock;
 }
Example #24
0
        private TClient InitializeClient(IServerSession session)
        {
            var client = _gameClientFactory.CreateClient(session);

            client.Closing += (s, e) => Clients.Remove(client);

            return(client);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerSessionEventArgs"/> class.
        /// </summary>
        /// <param name="serverSession">The <see cref="IServerSession"/> instance.</param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="serverSession"/> is <see langword="null"/>.
        /// </exception>
        public ServerSessionEventArgs(IServerSession serverSession)
        {
            if (serverSession == null)
            {
                throw new ArgumentNullException(nameof(serverSession));
            }

            ServerSession = serverSession;
        }
Example #26
0
        /// <inheritdoc/>
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthClient"/> class and binds it with a network session.
        /// </summary>
        /// <param name="authenticator">The <see cref="IAuthenticator"/> to use for authenticating the user.</param>
        /// <param name="nexus">The <see cref="IAuthToNexusRequestHandler"/> to query for... world stuff.</param>
        /// <param name="serverSession"><inheritdoc/></param>
        /// <param name="packetFactory"><inheritdoc/></param>
        /// <param name="logger"><inheritdoc/></param>
        public AuthClient(IAuthenticator authenticator, IAuthToNexusRequestHandler nexus, IServerSession serverSession, IPacketFactory packetFactory, ILogger logger)
            : base(serverSession, packetFactory, logger)
        {
            this.authenticator = authenticator;
            this.nexus = nexus;

            this.LoginAttempts = 0;
            this.State = AuthClientState.NotLoggedIn;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UPSyncDataSets"/> class.
 /// </summary>
 /// <param name="session">
 /// The session.
 /// </param>
 /// <param name="incremental">
 /// if set to <c>true</c> [incremental].
 /// </param>
 /// <param name="crmDataStore">
 /// The CRM data store.
 /// </param>
 /// <param name="configStore">
 /// The configuration store.
 /// </param>
 /// <param name="theDelegate">
 /// The delegate.
 /// </param>
 public UPSyncDataSets(
     IServerSession session,
     bool incremental,
     ICRMDataStore crmDataStore,
     IConfigurationUnitStore configStore,
     ISyncDataSetsDelegate theDelegate)
     : this(configStore?.AllDataSetNamesSorted(), incremental, session, crmDataStore, configStore, theDelegate)
 {
 }
        private void LeaveAll(IServerSession session)
        {
            var multicastAddresses = GetMulticastAddresses(session);

            foreach (var multicastAddress in multicastAddresses)
            {
                this.Leave(multicastAddress, session);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UPOfflineRequest"/> class.
 /// </summary>
 /// <param name="_requestMode">The request mode.</param>
 /// <param name="jsonString">The json string.</param>
 public UPOfflineRequest(UPOfflineRequestMode _requestMode, string jsonString)
 {
     this.RequestNr           = -1;
     this.requestMode         = _requestMode;
     this.Json                = jsonString;
     this.ServerRequestNumber = -1;
     this.ApplicationRequest  = true;
     this.Session             = ServerSession.CurrentSession;
 }
Example #30
0
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (null != m_session)
            {
                m_session.Dispose();
                m_session = null;
            }

            base.OnClosing(e);
        }
Example #31
0
        internal static void AsyncRaiseHeartBeatReceived(object sender, IServerSession session)
        {
            if (HeartBeatReceived == null)
            {
                return;
            }

            object[] args = { sender, new HeartBeatReceivedEventArgs(session) };
            AnycastEventThrower.QueueUserWorkItem(new RaiseEvent(_RaiseHeartBeatReceived), args);
        }
Example #32
0
        private void OnConnectionOpened(IServerSession session)
        {
            var handler = ConnectionOpened;

            if (handler != null)
            {
                var args = new ServerSessionEventArgs(session);
                handler.Invoke(this, args);
            }
        }
Example #33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientBase" /> class.
        /// </summary>
        /// <param name="serverSession">The network session to bind the instance to.</param>
        /// <param name="packetFactory">The <see cref="IPacketFactory" /> to use for this client.</param>
        /// <param name="logger">The logger to use for this client.</param>
        /// <exception cref="ArgumentNullException">Thrown if any of the parameters is <see langword="null" />.</exception>
        protected ClientBase(IServerSession serverSession, IPacketFactory packetFactory, ILogger logger)
        {
            Guard.NotNull(() => serverSession, serverSession);
            Guard.NotNull(() => packetFactory, packetFactory);

            this.isDisposed = false;
            this.sentPings = new AtomicInteger(0);

            this.ServerSession = this.InitializeSession(serverSession);
            this.PacketFactory = packetFactory;
            this.Logger = logger;

            this.keepAliveTimer = this.InitializeTimer();
            this.keepAliveTimer.Start();
        }
        public MainWindow()
        {
            InitializeComponent();

            m_nodeComboBox.ItemsSource = m_nodes;
            m_nodeComboBox.SelectionChanged += m_nodeComboBox_SelectionChanged;

            m_transferView.ItemsSource = m_transfers;

            m_session = CSAPI.Create().CreateServerSession(HOST, PORT);
            using (var result = m_session.Authenticate(USERNAME, PASSWORD))
            {
                if (!result.IsSuccess)
                {
                    m_errors.Text = "Login failed: " + result.ToString();
                    m_session.Dispose();
                    m_session = null;
                    return;
                }
            }

            using (var result = m_session.DataAccess.Brokers.Node.Read(m_session.ModelFactory.CreateAllSelector(), null))
            {
                if (result.IsSuccess)
                {
                    foreach (INode node in result.Value.Items)
                    {
                        NodeModel nm = new NodeModel()
                        {
                            Name = node.Name,
                            Id = node.Id.ToString(),
                        };
                        m_nodes.Add(nm);
                    }
                }
                else
                {
                    m_errors.Text = result.ToString();
                    return;
                }
            }
        }
        private static bool Authenticate(IServerSession session)
        {
            string ncUser = "******";
            string ncPassword = "******";

            Console.Write("Authenticating... ");
            using (var result = session.Authenticate(ncUser, ncPassword))
            {
                if (result.IsSuccess)
                {
                    Console.WriteLine("success");
                    return true;
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return false;
                }
            }
        }
        private void m_loginButton_Click(object sender, RoutedEventArgs e)
        {
            m_session = m_api.CreateServerSession(m_host, m_port);

            bool isAuthenticated = false;
            try
            {
                using (var result = m_session.Authenticate(m_username.Text, m_password.Password))
                {
                    if (result.IsSuccess)
                    {
                        DialogResult = true;
                        Close();
                        isAuthenticated = true;
                    }
                    else
                    {
                        if (result.Result == AuthenticateResultType.AuthFailed)
                        {
                            m_error.Text = "Invalid username/password";
                        }
                        else if (result.Result == AuthenticateResultType.ServerRefused)
                        {
                            m_error.Text = "Server rejected authentication, could be starting up";
                        }
                        else
                        {
                            m_error.Text = "Failed login: " + result.ToString();
                        }
                    }
                }
            }
            finally
            {
                if (!isAuthenticated)
                {
                    m_session.Dispose();
                    m_session = null;
                }
            }
        }
 private static bool IdentifyTriggerPayloadDataTable(IServerSession session)
 {
     Console.Write("Looking up payload table for trigger...");
     using (var result = session.DataAccess.Brokers.Trigger.ReadSingle(session.ModelFactory.CreateSelectorById(new Oid(TRIGGER_ID)), null))
     {
         if (result.IsSuccess)
         {
             Console.WriteLine("success: " + result.Value.DataTable.Id);
             g_triggerDataTableId = result.Value.DataTable.Id;
             return true;
         }
         else
         {
             Console.WriteLine("failed: " + result.ToString());
             return false;
         }
     }
 }
        private static bool ImportContentFile(IServerSession session, string assetFile, ContentAssetType type)
        {
            Console.Write("Analyzing {0} file \"{1}\"...", type, assetFile);
            AssetInfo imageInfo = MediaAnalyzer.AnalyzeAssetFile(assetFile);
            if (!string.IsNullOrEmpty(imageInfo.ErrorMessage))
            {
                Console.WriteLine("failed: {0}", imageInfo.ErrorMessage);
                return false;
            }
            else
            {
                Console.WriteLine("success");
            }

            string thumbnailFile = Path.Combine(Path.GetTempPath(), new Oid().ToString() + ".jpg");
            File.WriteAllBytes(thumbnailFile, imageInfo.ThumbnailImageBytes);
            try
            {
                IContent content = session.ModelFactory.CreateContent();
                content.DurationInMilliseconds = 5000;
                content.Format = ContentFormat.Landscape;
                content.Name = type.ToString() + " Content";
                content.ResolutionX = imageInfo.Width.Value;
                content.ResolutionY = imageInfo.Height.Value;

                Console.Write("Importing {0} content...", type);
                using (var result = session.DataAccess.Brokers.Content.ImportContentFromAssetFile(assetFile, type, content, thumbnailFile, new ContentImportOptions()))
                {
                    if (result.IsSuccess)
                    {
                        Console.WriteLine("success");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("failed: {0}", result.ToString());
                        return false;
                    }
                }
            }
            finally
            {
                File.Delete(thumbnailFile);
            }
        }
Example #39
0
 public void Register(IServerSession session)
 {
     session.ReadyForPush += this.OnReadyForPush;
 }
        private static int importItem(IServerSession session, SetConfig workingConf)
        {
            // hook API logger
            Logger.SetLogSink(HandleLogEntry);
            try
            {
                /*string ncHostname = "10.50.149.13";
                int ncPort = 80;9(*/
                Oid targetTable = new Oid(workingConf.oidForWrite);

                //using (session /*IServerSession session = CSAPI.Create().CreateServerSession(ncHostname, ncPort)*/)
                //{
                //if (false/*!Authenticate(session)*/)
                //{
                //    session.Dispose();
                //    return -1;
                //}
                //    else
                //    {
                        /* Get access to read the table */
                try
                {
                    var result = session.DataAccess.Brokers.DataTable.ReadSingle(
                        session.ModelFactory.CreateSelectorById(targetTable),
                        new IRelationshipMetaData[]
                            {
                                MetaData.DataTableToDataTableDesign,
                                MetaData.DataTableDesignToDataTableField,
                                MetaData.DataTableToFileInDataTable,
                                MetaData.DataTableToDataRow
                            });
                    IDataTable datatable = result.Value;
                    if (result.Value == null) { return 2; }
                }
                catch (InvalidOperationException)
                {
                    Console.WriteLine("Connection/authentication error. Reauthenticating before next iteration");
                    return -1;
                }

                /* The change set is a list of all changes to the database that will be sent after all edits are done */
                IChangeSet changes = session.DataAccess.CreateChangeSet();

                /* Delete all rows from the table */
                session.DataAccess.Brokers.DataTable.DeleteDataRows(changes, targetTable, session.ModelFactory.CreateAllSelector());

                /* TODO: Allow support for appending to tables instead of a fixed number of rows */

                int i = 1;
                if (workingConf.allOneRecord == false)
                {
                    List<List<string>> col_lists = new List<List<string>>();
                    List<IChangeSet> trigger_changes = new List<IChangeSet>();
                    /* TODO: Fork the process so that general datatable updates don't have to happen unless there is a change in the state of the triggered table */
                    foreach (colConf entry in workingConf.cols)
                    {
                        List<string> col_vals = new List<string>();
                        col_vals.Add(entry.name_of_col);
                        XmlDocument xd = new XmlDocument();
                        int retries = 3;
                        do //Solves transient network issues that occur when repeatedly pulling updated XML documents
                        {
                            try
                            {
                                xd.Load(entry.source);
                                break;
                            }
                            catch (WebException)
                            {
                                Console.WriteLine("Failed to get XML file from server, retrying . . .");
                                if (retries <= 0)
                                {
                                    Console.WriteLine("Retrying failed. Skipping document until next iteration.");
                                }
                                else
                                {
                                    Thread.Sleep(300);
                                }
                            }
                        }
                        while (retries-- > 0);
                        if (retries <= 0) { break; }
                        XmlNamespaceManager nsmgr = new XmlNamespaceManager(xd.NameTable);
                        /* Namespace entries (does not have to be exclusive to the entry that uses it, so long as there are no conflicts!) */
                        /* nsmgr.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
                        nsmgr.AddNamespace("m", "http://www.w3.org/2005/Atom");
                        nsmgr.AddNamespace("cap", "urn:oasis:names:tc:emergency:cap:1.1");
                        nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom"); */

                        /* (Experimental) Add user specified namespaces [TODO: Should add error handling so that program can continue if it fails] */
                        foreach (nsConf ns_info in workingConf.ns_list)
                        {
                            nsmgr.AddNamespace(ns_info.ns, ns_info.ns_source);
                        }

                        XmlNodeList found_nodes = xd.SelectNodes(entry.description, nsmgr);
                        if (entry.firesTrigger)
                        {
                            bool triggered = false;

                            /* Create new trigger_change set if column is triggerable*/
                            IChangeSet trigger_change = session.DataAccess.CreateChangeSet();
                            var result2 = session.DataAccess.Brokers.Trigger.ReadSingle(session.ModelFactory.CreateSelectorById(new Oid(entry.triggerID)), null);
                            Oid m_triggerDataTableId = result2.Value.DataTable.Id;
                            foreach (XmlNode nodeInList in found_nodes)
                            {
                                if (!triggered)
                                {
                                    triggered = true; // Prevents multiple triggers when there is more than one node in the triggerable column

                                    /* Adding a row to the trigger payload table activates the trigger */
                                    IDataRow trigger_row = session.ModelFactory.CreateDataRow();
                                    trigger_row.ActivationDate = DateTime.Now;
                                    trigger_row.ExpirationDate = DateTime.Now.AddDays(5); //I really need to figure out how to write this in more clearly. Perhaps being able to clear triggers?
                                    trigger_row.SequenceNumber = 0;

                                    session.DataAccess.Brokers.DataTable.CreateDataRow(trigger_change, m_triggerDataTableId, trigger_row);
                                    trigger_changes.Add(trigger_change);
                                }
                                if (!String.IsNullOrEmpty(entry.attrib))
                                {
                                    col_vals.Add(nodeInList.Attributes[entry.attrib].Value);
                                }
                                else
                                {
                                    string valueToAdd = String.IsNullOrEmpty(nodeInList.Value) ? nodeInList.InnerText : nodeInList.Value;
                                    col_vals.Add(valueToAdd);
                                }
                            }
                            if (!triggered) // Clears the trigger if no data is added to the table upon update
                            {
                                session.DataAccess.Brokers.DataTable.DeleteDataRows(changes, m_triggerDataTableId, session.ModelFactory.CreateAllSelector());
                                trigger_changes.Add(trigger_change);
                            }
                        }
                        else
                        {
                            foreach (XmlNode nodeInList in found_nodes)
                            {
                                if (!String.IsNullOrEmpty(entry.attrib))
                                {
                                    col_vals.Add(nodeInList.Attributes[entry.attrib].Value);
                                }
                                else
                                {
                                    string valueToAdd = String.IsNullOrEmpty(nodeInList.Value) ? nodeInList.InnerText : nodeInList.Value;
                                    col_vals.Add(valueToAdd);
                                }
                            }
                        }
                        col_lists.Add(col_vals);

                    }
                    for (int j = 1; j <= workingConf.numRows; j++)
                    {
                        /* Add new rows to the table */
                        IDataRow row = session.ModelFactory.CreateDataRow();
                        row.SequenceNumber = i;
                        row.ActivationDate = new DateTime(1601, 1, 1);
                        row.ExpirationDate = new DateTime(3000, 1, 1);
                        foreach (List<string> col in col_lists)
                        {
                            try
                            {
                                row.Values[col[0]] = col[j];
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                break;
                            }
                            catch (IndexOutOfRangeException)
                            {
                                break;
                            }
                        }
                        session.DataAccess.Brokers.DataTable.CreateDataRow(changes, targetTable, row);
                        i++;
                    }
                    changes.Save();
                    foreach (IChangeSet trig_cha in trigger_changes)
                    {
                        trig_cha.Save();
                    }
                }
                else
                {
                    /* TODO: Add a generic trigger to sources that are all on one record */
                    /* Access the Xml data source */
                    String URLString = workingConf.sourceUrl;
                    XmlDocument xd = new XmlDocument();
                    xd.Load(URLString);
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xd.NameTable);

                    /* (Experimental) Add user specified namespaces [Should add error handling so that program can continue if it fails] */
                    foreach (nsConf ns_info in workingConf.ns_list)
                    {
                        nsmgr.AddNamespace(ns_info.ns, ns_info.ns_source);
                    }

                    //nsmgr.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
                    XmlNodeList nodeOfRec = xd.SelectNodes(workingConf.itemOfRec, nsmgr);
                    foreach (XmlNode node in nodeOfRec)
                    {
                        //Add new rows to the table
                        IDataRow row = session.ModelFactory.CreateDataRow();
                        row.SequenceNumber = i;
                        row.ActivationDate = new DateTime(1601, 1, 1);
                        row.ExpirationDate = new DateTime(3000, 1, 1);
                        if (node.HasChildNodes) /* Then the items we are looking for are not attributes of the node of record (but could be attributes of a child node) */
                        {
                            foreach (XmlNode cnode in node.ChildNodes)
                            {
                                foreach (colConf testcols in workingConf.cols)
                                {
                                    if (testcols.description == cnode.Name)
                                    {
                                        if (!String.IsNullOrEmpty(testcols.attrib))
                                        {
                                            row.Values[testcols.name_of_col] = cnode.Attributes[testcols.attrib].Value;
                                        }
                                        else
                                        {
                                            row.Values[testcols.name_of_col] = cnode.Value;
                                        }
                                    }
                                }
                            }
                        }
                        else /* We are looking at the node of record's attributes only */
                        {
                            XmlAttributeCollection xac = node.Attributes;
                            foreach (XmlAttribute xa in xac)
                            {
                                foreach (colConf testcols in workingConf.cols)
                                {
                                    if (testcols.attrib == xa.Name)
                                    {
                                        row.Values[testcols.name_of_col] = xa.Value;
                                        break;
                                    }
                                }
                            }
                            session.DataAccess.Brokers.DataTable.CreateDataRow(changes, targetTable, row);
                            i++;
                        }
                    }
                    changes.Save();
                }
                return 0;
            }
            finally
            {
                // unhook logger
                Logger.SetLogSink(null);
            }
        }
 private static Oid FindANodeId(IServerSession session)
 {
     Console.Write("Finding a Node... ");
     using (var result = session.DataAccess.Brokers.Node.Read(null, null))
     {
         if (result.IsSuccess)
         {
             foreach (var node in result.Value.Items)
             {
                 Console.WriteLine("found Node with id {0}", node.Id);
                 return node.Id;
             }
             Console.WriteLine("there are no Nodes in the network!");
             return null;
         }
         else
         {
             Console.WriteLine("failed: " + result.ToString());
             return null;
         }
     }
 }
 private static bool ReadNodeAttributeValues(Oid nodeId, IServerSession session)
 {
     Console.Write("Reading attribute values for Node {0}... ", nodeId);
     using (var result = session.DataAccess.Brokers.Node.ReadSingle(session.DataAccess.ModelFactory.CreateSelectorById(nodeId), null))
     {
         if (result.IsSuccess)
         {
             Console.WriteLine("found {0} attribute values", result.Value.Attributes.Count);
             foreach (string attrName in result.Value.Attributes.Keys)
             {
                 Console.WriteLine("  Attribute {{ Name = \"{0}\", Value = \"{1}\" }}", attrName, result.Value.Attributes[attrName]);
             }
             return true;
         }
         else
         {
             Console.WriteLine("failed: " + result.ToString());
             return false;
         }
     }
 }
        protected override void OnClosed(EventArgs e)
        {
            m_session.Dispose();
            m_session = null;

            base.OnClosed(e);
        }
        private static bool SetNodeAttributeValue(Oid nodeId, string value, IServerSession session)
        {
            IModelFactory dacFactory = session.DataAccess.ModelFactory;
            INodeBroker nodeBroker = session.DataAccess.Brokers.Node;
            ISelector nodeIdSel = dacFactory.CreateSelectorById(nodeId);

            Console.WriteLine("Updating attribute values for Node {0}... ", nodeId);
            NodeAttributeValues attrValues;
            using (var result = nodeBroker.ReadSingle(nodeIdSel, null))
            {
                if (result.IsSuccess)
                {
                    attrValues = result.Value.Attributes;
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return false;
                }
            }
            IChangeSet changes = session.DataAccess.CreateChangeSet();
            INode node = session.DataAccess.ModelFactory.CreateNode();
            node.Attributes = attrValues;
            node.Attributes[ATTRIBUTE_NAME] = value;
            nodeBroker.UpdateNodes(changes, node, nodeIdSel);
            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    Console.WriteLine("success");
                    return true;
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return false;
                }
            }
        }
        private static bool CreateMyAttribute(IServerSession session)
        {
            var attrBroker = session.DataAccess.Brokers.NodeAttributeDefinition;
            IChangeSet changes = session.DataAccess.CreateChangeSet();
            INodeAttributeDefinition attr = session.DataAccess.ModelFactory.CreateNodeAttributeDefinition();
            attr.Id = new Oid();
            attr.Name = ATTRIBUTE_NAME;
            attr.DefaultValue = "hi";
            attrBroker.CreateNodeAttributeDefinition(changes, attr);

            Console.Write("Creating my NodeAttributeDefinition... ");
            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    // extract the actual id of the created attr def
                    Oid newId = result.IdMap[attr.Id];
                    Console.WriteLine("success, my attribute def has id {0}", newId);
                    return true;
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return false;
                }
            }
        }
Example #46
0
 private void OnConnectionOpened(IServerSession session)
 {
     var handler = this.ConnectionOpened;
     if (handler != null)
     {
         var args = new ServerSessionEventArgs(session);
         handler.Invoke(this, args);
     }
 }
Example #47
0
        private void StartSession(IServerSession session)
        {
            var clientIv = this.ivGenerator.GetNewIv();
            var serverIv = this.ivGenerator.GetNewIv();

            var info = new ConfiguredHandshakeInfo(this.serverConfiguration, clientIv, serverIv);
            var crypto = EndpointCrypto.Server(this.ivFactory, clientIv, serverIv);
            session.Start(crypto, info);
        }
        private static bool DeactivateTriggers(IServerSession session)
        {
            Console.Write("Deleting existing rows from trigger payload table...");

            IChangeSet changes = session.DataAccess.CreateChangeSet();

            session.DataAccess.Brokers.DataTable.DeleteDataRows(changes, g_triggerDataTableId, session.ModelFactory.CreateAllSelector());

            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    Console.WriteLine("success");
                    return true;
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return false;
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerSessionEventArgs"/> class.
 /// </summary>
 /// <param name="serverSession">The <see cref="IServerSession"/> instance.</param>
 /// <exception cref="ArgumentNullException">
 /// Thrown if <paramref name="serverSession"/> is <see langword="null"/>.
 /// </exception>
 public ServerSessionEventArgs(IServerSession serverSession)
 {
     Guard.NotNull(() => serverSession, serverSession);
     this.ServerSession = serverSession;
 }
Example #50
0
 /// <inheritdoc/>
 public ChannelClient(IServerSession serverSession, IPacketFactory packetFactory, ILogger logger)
     : base(serverSession, packetFactory, logger)
 {
 }
 private static ICollection<INodeAttributeDefinition> ReadAllAttributeDefs(IServerSession session)
 {
     Console.Write("Reading NodeAttributeDefinitions... ");
     using (var result = session.DataAccess.Brokers.NodeAttributeDefinition.Read(null, null))
     {
         if (result.IsSuccess)
         {
             Console.WriteLine("found {0}", result.Value.Count);
             foreach (var attr in result.Value.Items)
             {
                 Console.WriteLine("  NodeAttributeDef {{ Name = \"{0}\", DefaultValue = \"{1}\" }}", attr.Name, attr.DefaultValue);
             }
             return result.Value.Items;
         }
         else
         {
             Console.WriteLine("failed: " + result.ToString());
             return null;
         }
     }
 }
        private static bool UpdateMyAttribute(IServerSession session)
        {
            var attrBroker = session.DataAccess.Brokers.NodeAttributeDefinition;
            var dacFactory = session.DataAccess.ModelFactory;
            IChangeSet changes = session.DataAccess.CreateChangeSet();
            INodeAttributeDefinition attr = dacFactory.CreateNodeAttributeDefinition();
            attr.DefaultValue = "hello";
            attrBroker.UpdateNodeAttributeDefinitions(changes, attr, dacFactory.CreateSelectorByFilter(dacFactory.CreateFilterExpression("Name LIKE \"" + ATTRIBUTE_NAME + "\"")));

            Console.Write("Updating my NodeAttributeDefinition... ");
            using (var result = changes.Save())
            {
                if (result.IsSuccess)
                {
                    Console.WriteLine("success");
                    return true;
                }
                else
                {
                    Console.WriteLine("failed: " + result.ToString());
                    return false;
                }
            }
        }
Example #53
0
 private IServerSession InitializeSession(IServerSession serverSession)
 {
     serverSession.PacketProcessing += this.OnPacketProcessing;
     serverSession.Closing += this.OnSessionClosing;
     return serverSession;
 }