Example #1
0
        /// <summary>
        /// Create a new property object.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ServerProperties CreateProperties(string name) {
            ServerProperties prop = new ServerProperties();

            //set name
            prop.DisplayName = name;

            //server type
            prop.Type = ServerType.Minecraft;

            //have to change to jarmanager later
            prop.JarFile = "minecraft_server.jar";

            //Do everything in MB
            prop.Memory = "1024";

            //supported threads
            prop.Threads = "2";

            //grabs the latest release, if possible
            if (JarManager.IsSetup) {
                prop.MCVersion = JarManager.LatestRelease;
                prop.JarEntryName = JarManager.LatestRelease + "-Mojang";
            } else {

            }

            prop.Optimize = true;

            prop.IPAddress = "0.0.0.0";

            prop.Port = 25565;

            return prop;
        }
        public void DoesLeavingSettingsOnDefaultGenerateBlankFile()
        {
            var sp = new ServerProperties();
            var f  = sp.ToFileFormat();

            Assert.AreEqual("", f);
        }
        public string ProcessRequest(string request, IHttpResponse httpResponse,
                                     ServerProperties serverProperties)
        {
            var fileProcessors =
                ((Readers)serverProperties.ServiceSpecificObjectsWrapper);
            var requestItem = CleanRequest(request);

            requestItem = requestItem.Substring(1);
            var listing = DirectoryContents(requestItem,
                                            fileProcessors.DirectoryProcess,
                                            serverProperties.CurrentDir,
                                            serverProperties.Port);

            httpResponse.SendHeaders(new List <string>
            {
                "HTTP/1.1 200 OK\r\n",
                "Cache-Control: no-cache\r\n",
                "Content-Type: text/html\r\n",
                "Content-Length: "
                + (GetByteCount(listing)) +
                "\r\n\r\n"
            });

            httpResponse.SendBody(GetByte(listing),
                                  GetByteCount(listing));
            return("200 OK");
        }
Example #4
0
        public static IMainServer HelloWorldServer(string port, IPrinter io)
        {
            var portConverted = PortWithinRange(port, io);

            if (portConverted == -1)
            {
                return(null);
            }
            var endPoint   = new IPEndPoint((IPAddress.Loopback), portConverted);
            var zSocket    = new DefaultZSocket(endPoint);
            var properties = new ServerProperties(null,
                                                  portConverted,
                                                  new ServerTime(), io,
                                                  new Readers
            {
                FileProcess      = new FileProcessor(),
                DirectoryProcess = new DirectoryProcessor()
            });

            return(new MainServer(zSocket, properties,
                                  new HttpServiceFactory(new Service404()),
                                  new DefaultRequestProcessor(),
                                  new List <string>()
            {
                "FileServer.Core"
            },
                                  new List <Assembly>()
            {
                Assembly.GetExecutingAssembly()
            }));
        }
        public void Can_Process_Non_Post_Request(string requestListing)
        {
            var request = requestListing + "\r\n" +
                          "Host: localhost:8080\r\n" +
                          "Connection: keep-alive\r\n" +
                          "Content-Length: 33\r\n" +
                          "Cache-Control: max-age = 0\r\n" +
                          "Accept: text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp,*/*;q=0.8\r\n" +
                          "Origin: http://localhost:8080\r\n" +
                          "Upgrade-Insecure-Requests: 1\r\n" +
                          "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36\r\n" +
                          "Content-Type: application/JSON\r\n" +
                          "Referer: http://localhost:8080/form\r\n" +
                          "Accept-Encoding: gzip, deflate\r\n" +
                          "Accept-Language: en-US,en;q=0.8\r\n\r\n";

            var zSocket = new MockZSocket().StubReceive("")
                          .StubSentToReturn(10)
                          .StubConnect(true);

            zSocket = zSocket.StubAcceptObject(zSocket);
            var properties = new ServerProperties(@"Home",
                                                  8080, new ServerTime(),
                                                  new MockPrinter());
            var process = new RequestProcessor();
            var status  = process.HandleRequest(request, zSocket,
                                                new MockHttpService()
                                                .StubProcessRequest("200 OK"),
                                                properties, new HttpResponse(zSocket));

            Assert.Equal("200 OK", status);
            zSocket.VerifyManyReceive(0);
        }
Example #6
0
        public async Task ExecuteAsync(string clientId, IPacket input, IMqttChannel <IPacket> channel)
        {
            if (input.Type != MqttPacketType.Unsubscribe)
            {
                return;
            }

            Unsubscribe   unsubscribe = input as Unsubscribe;
            ClientSession session     = _sessionRepository.Read(clientId);

            if (session == null)
            {
                throw new MqttException(ServerProperties.SessionRepository_ClientSessionNotFound(clientId));
            }

            foreach (string topic in unsubscribe.Topics)
            {
                ClientSubscription subscription = session.GetSubscriptions().FirstOrDefault(s => s.TopicFilter == topic);

                if (subscription != null)
                {
                    session.RemoveSubscription(subscription);
                }
            }

            _sessionRepository.Update(session);

            await channel.SendAsync(new UnsubscribeAck( unsubscribe.PacketId ));
        }
Example #7
0
        protected override void BeginProcessing()
        {
            var serverApi = new ServerApi(Utilities.Configuration);

            var server = new ServerProperties();

            if (!string.IsNullOrEmpty(this.Name) && !string.IsNullOrWhiteSpace(this.Name))
            {
                server.Name = this.Name;
            }
            if (this.Cores != 0)
            {
                server.Cores = this.Cores;
            }
            if (Ram != 0)
            {
                server.Ram = this.Ram;
            }
            if (!string.IsNullOrEmpty(this.CpuFamily) && !string.IsNullOrWhiteSpace(this.CpuFamily))
            {
                server.CpuFamily = this.CpuFamily;
            }
            if (!string.IsNullOrEmpty(this.AvailabilityZone) && !string.IsNullOrWhiteSpace(this.AvailabilityZone))
            {
                server.AvailabilityZone = this.AvailabilityZone;
            }

            var resp = serverApi.PartialUpdate(this.DataCenterId, this.ServerId, server);

            WriteObject(resp);
        }
Example #8
0
        /// <summary>
        /// Get Id for data
        /// </summary>
        /// <param name="connectionGroup">Connection group</param>
        /// <param name="instance">Instance</param>
        /// <returns></returns>
        public Int64?GetId(ConnectionGroupInfo connectionGroup, InstanceInfo instance)
        {
            connectionGroup.ReadGroupIdFrom(Storage.ConnectionGroupDirectory);

            Int64?           loginId    = Storage.LoginDirectory.GetId(instance);
            ServerProperties props      = instance.ServerProperties;
            string           serverName = null;
            string           serverVers = null;

            if (props != null)
            {
                serverName = props.Name;
                serverVers = props.Version.ToString();
            }

            return(this.GetRecordIdByFields(
                       this.CreateField(ConnectionGroupIdFn, connectionGroup.Identity),
                       this.CreateField(LoginIdFn, loginId),
                       this.CreateField(ConnectionNameFn, instance.Name),
                       this.CreateField(ServerInstanceNameFn, serverName),
                       this.CreateField(ServerInstanceVersionFn, serverVers),
                       this.CreateField(DbTypeFn, instance.DbType),
                       this.CreateField(IsOdbcFn, instance.IsODBC),
                       this.CreateField(IsDynamicConnectionFn, instance.IsDynamicConnection)
                       ));
        }
        public string ProcessRequest(string request,
                                     IHttpResponse httpResponse,
                                     ServerProperties serverProperties)
        {
            var helloWorldHtml = new StringBuilder();

            helloWorldHtml.Append(@"<!DOCTYPE html>");
            helloWorldHtml.Append(@"<html>");
            helloWorldHtml.Append(@"<head><title>Vatic Server Hello World</title></head>");
            helloWorldHtml.Append(@"<body>");
            helloWorldHtml.Append(@"<h1>Hello World</h1>");
            helloWorldHtml.Append(@"</body>");
            helloWorldHtml.Append(@"</html>");
            httpResponse.SendHeaders(new List <string>
            {
                "HTTP/1.1 200 OK\r\n",
                "Cache-Control: no-cache\r\n",
                "Content-Type: text/html\r\n",
                "Content-Length: "
                + (Encoding.ASCII
                   .GetByteCount(helloWorldHtml.ToString())) +
                "\r\n\r\n"
            });

            httpResponse.SendBody(Encoding
                                  .ASCII.GetBytes(helloWorldHtml.ToString()),
                                  Encoding.ASCII.GetByteCount(helloWorldHtml.ToString()));
            return("200 OK");
        }
        private string Form(ITicTacToeBoxClass.ITicTacToeBox ticTacToeBox,
                            TicTacToeGame game, int errorMesageCode, ServerProperties serverProperties)
        {
            var form = MakeForm(ticTacToeBox);

            form = RemoveButton(game.Setting.playerGlyph, form);
            form = RemoveButton(game.Setting.aIGlyph, form);
            var errorMessage = errorMesageCode != Translate.Blank
                ? "<p>" +
                               Translator.translator(Translator.language.english,
                                                     errorMesageCode) + "</p>"
                : "";

            form = errorMessage += form;
            if (!game.CheckForWinner((TicTacToeBoxClass.TicTacToeBox)ticTacToeBox))
            {
                return(form);
            }
            form = "<p>Game Over</p>"
                   + @"<a href=""http://127.0.0.1:"
                   + serverProperties.Port
                   + @"""><button>Another Game?</button></a>"
                   + form;
            for (var i = 0; i < ticTacToeBox.cellCount(); i++)
            {
                form = RemoveButton("-" + (i + 1) + "-", form);
            }
            return(form);
        }
 public string ProcessRequest(string request, IHttpResponse httpResponse, ServerProperties serverProperties)
 {
     return(request.Contains("GET /")
         ? GetRequest(httpResponse)
         : PostRequest(request, httpResponse,
                       serverProperties));
 }
Example #12
0
        private bool IsDirect(string request,
                              ServerProperties serverProperties)
        {
            var requestItem   = CleanRequest(request);
            var configManager = ConfigurationManager.AppSettings;

            if (configManager.AllKeys.Any(key => requestItem.EndsWith(configManager[key])) &&
                !request.Contains("POST /"))
            {
                return(false);
            }
            if (!request.Contains("POST /"))
            {
                return(false);
            }
            var fullpath
                = (serverProperties.CurrentDir + requestItem.Substring(1));

            _file = fullpath.Substring(fullpath
                                       .LastIndexOf("/", StringComparison.Ordinal) + 1);
            var copyDistance =
                _directory = fullpath.Substring(0, fullpath
                                                .LastIndexOf("/", StringComparison.Ordinal) + 1);

            _directRequest = true;
            _headerRemoved = false;
            return(true);
        }
Example #13
0
 public string ProcessRequest(string request, IHttpResponse httpResponse,
                              ServerProperties serverProperties)
 {
     return(request.Contains("GET /") && request.IndexOf("GET /", StringComparison.Ordinal) == 0
         ? GetRequest(request, httpResponse)
         : PostRequest(request, httpResponse, serverProperties));
 }
Example #14
0
        public void Send_Error_Data()
        {
            var zSocket = new MockZSocket();
            var guid    = Guid.NewGuid();

            var mockFileSearch = new MockFileProcessor()
                                 .StubExists(true)
                                 .StubGetFileStream(null)
                                 .StubFileSize(2);

            var properties = new ServerProperties(@"c:/",
                                                  5555, new ServerTime(),
                                                  new MockPrinter(),
                                                  new Readers
            {
                DirectoryProcess = new MockDirectoryProcessor(),
                FileProcess      = mockFileSearch
            });
            var inlinePngService = new InlinePngService();

            var statusCode = inlinePngService
                             .ProcessRequest("GET /" + guid + ".png HTTP/1.1",
                                             new HttpResponse(zSocket),
                                             properties);

            Assert.Equal("200 OK", statusCode);
        }
Example #15
0
        async Task HandleConnectionExceptionAsync(Exception exception)
        {
            if (exception is TimeoutException)
            {
                await NotifyErrorAsync(ServerProperties.ServerPacketListener_NoConnectReceived, exception);
            }
            else if (exception is MqttConnectionException)
            {
                _tracer.Error(exception, ServerProperties.ServerPacketListener_ConnectionError(_clientId ?? "N/A"));

                MqttConnectionException connectEx = exception as MqttConnectionException;
                ConnectAck errorAck = new ConnectAck(connectEx.ReturnCode, existingSession: false);

                try
                {
                    await _channel.SendAsync(errorAck);
                }
                catch (Exception ex)
                {
                    await NotifyErrorAsync(ex);
                }
            }
            else
            {
                await NotifyErrorAsync(exception);
            }
        }
Example #16
0
        private string SendHtml(string requestItem,
                                ServerProperties serverProperties,
                                IHttpResponse httpResponse)
        {
            var html = HtmlHeader() +
                       @"<video width=""320"" height=""240"" controls>" +
                       @"<source src=""http://127.0.0.1:" + serverProperties.Port + "/" +
                       requestItem.Substring(1) + ".vaticToMp4" +
                       @""" type=""video/mp4"">" +
                       "</video>"
                       + HtmlTail();

            httpResponse.SendHeaders(new List <string>
            {
                "HTTP/1.1 200 OK\r\n",
                "Cache-Control: no-cache\r\n",
                "Content-Type: text/html\r\n",
                "Content-Length: "
                + (Encoding.ASCII.GetByteCount(html)) +
                "\r\n\r\n"
            });

            httpResponse.SendBody(Encoding
                                  .ASCII.GetBytes(html),
                                  Encoding.ASCII.GetByteCount(html));
            return("200 OK");
        }
Example #17
0
        void ttserver_OnServerUpdated(ref ServerProperties lpServerProperties, ref User lpUser)
        {
            String str = String.Format("Server properties updated, name is now {0}",
                                       lpServerProperties.szServerName);

            Console.WriteLine(str);
        }
Example #18
0
 static void ttclient_OnCmdServerUpdate(ServerProperties serverproperties)
 {
     Console.WriteLine("Get new server properties.");
     Console.WriteLine("Server Name: " + serverproperties.szServerName);
     Console.WriteLine("MOTD: " + serverproperties.szMOTD);
     Console.WriteLine("Server Version: " + serverproperties.szServerVersion);
 }
        public static IMainServer TicTacToeServer(string port,
                                                  IPrinter io)
        {
            var portConverted = PortWithinRange(port, io);

            if (portConverted == -1)
            {
                return(null);
            }
            var endPoint = new IPEndPoint((IPAddress.Loopback),
                                          portConverted);
            var zSocket    = new DefaultZSocket(endPoint);
            var properties = new ServerProperties(null,
                                                  portConverted,
                                                  new ServerTime(), io,
                                                  new TicTacToeGame(new User(), new Ai(),
                                                                    MakeSettings()));

            return(new MainServer(zSocket, properties,
                                  new HttpServiceFactory(new Service404()),
                                  new DefaultRequestProcessor(),
                                  new List <string> {
                "TicTacToeServer.Core"
            },
                                  new List <Assembly> {
                Assembly.GetExecutingAssembly()
            }));
        }
        public string ProcessRequest(string request,
                                     IHttpResponse httpResponse,
                                     ServerProperties serverProperties)
        {
            var errorPage = new StringBuilder();

            errorPage.Append(@"<!DOCTYPE html>");
            errorPage.Append(@"<html>");
            errorPage.Append(@"<head><title>Vatic Server 404 Error Page</title></head>");
            errorPage.Append(@"<body>");
            errorPage.Append(@"<h1>404, Can not process request on port " + serverProperties.Port + "</h1>");
            errorPage.Append(@"</body>");
            errorPage.Append(@"</html>");
            httpResponse.SendHeaders(new List <string>
            {
                "HTTP/1.1 404 Not Found\r\n",
                "Cache-Control: no-cache\r\n",
                "Content-Type: text/html\r\n",
                "Content-Length: "
                + (Encoding.ASCII.GetByteCount(errorPage.ToString())) +
                "\r\n\r\n"
            });

            httpResponse.SendBody(Encoding
                                  .ASCII.GetBytes(errorPage.ToString()),
                                  Encoding.ASCII.GetByteCount(errorPage.ToString()));

            return("404 Not Found");
        }
Example #21
0
        public static ServerProperties Deserialize(string data)
        {
            var serverProperties = new ServerProperties();
            var properties       = typeof(ServerProperties).GetProperties();

            foreach (var line in data.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
            {
                var parts = line.Split('=');
                if (parts.Length == 2)
                {
                    var name = parts[0].Trim()
                               .Replace(".", "__")
                               .Replace('-', '_');

                    var rawValue = parts[1].Trim();

                    var property = properties.FirstOrDefault(p => p.Name.ToLower() == name.ToLower());
                    if (property != null)
                    {
                        var value = Convert.ChangeType(rawValue, property.PropertyType);

                        property.SetValue(serverProperties, value);
                    }
                }
            }

            return(serverProperties);
        }
Example #22
0
        private static void SelectEnv()
        {
            string[] envs = { "127.0.0.1", "51.91.156.75" };

            Console.WriteLine("Welcom on NS_MMO server, choose an environment : ");
            for (int i = 0; i < envs.Length; i++)
            {
                Console.WriteLine("{0}. {1}", i, envs[i]);
            }

            // wait user select an environment
            int choice;

            do
            {
                string input = Console.ReadLine();
                if (int.TryParse(input, out choice))
                {
                    break;
                }
                if (choice != 0 || choice != 1)
                {
                    Console.WriteLine("You can only type 0 or 1.");
                }
            } while (choice != 0 || choice != 1);

            // set environment
            ServerProperties.setAddress(envs[choice]);
        }
Example #23
0
        public bool CanProcessRequest(string request,
                                      ServerProperties serverProperties)
        {
            var requestItem = CleanRequest(request);

            return(requestItem == "/form");
        }
        public async Task ExecuteAsync(string clientId, IPacket input, IMqttChannel <IPacket> channel)
        {
            if (input.Type != MqttPacketType.Disconnect)
            {
                return;
            }

            await Task.Run(() =>
            {
                Disconnect disconnect = input as Disconnect;

                _tracer.Info(ServerProperties.DisconnectFlow_Disconnecting(clientId));

                _willRepository.Delete(clientId);

                ClientSession session = _sessionRepository.Read(clientId);

                if (session == null)
                {
                    throw new MqttException(ServerProperties.SessionRepository_ClientSessionNotFound(clientId));
                }

                if (session.Clean)
                {
                    _sessionRepository.Delete(session.Id);

                    _tracer.Info(ServerProperties.Server_DeletedSessionOnDisconnect(clientId));
                }

                _connectionProvider.RemoveConnection(clientId);
            });
        }
Example #25
0
        public async Task SaveServerProperties(string id, ServerProperties properties)
        {
            var server = await _repo.GetServerById(id);

            if (server == null)
            {
                throw new Exception("Server not found.");
            }
            else if (server.TimesRan == 0)
            {
                throw new Exception("You must first run the server to generate neccessary files before saving.");
            }

            try
            {
                server.Properties = properties as Properties;
                await _repo.UpsertServer(server);

                await properties.Save(Path.Combine(server.ServerPath, "server.properties"));
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return;
        }
Example #26
0
        public static IMainServer MakedirectoryServer(string chosenPort, string homeDirectory, IPrinter io)
        {
            var cleanHomeDir = homeDirectory.Replace('\\', '/');
            var port         = PortWithinRange(chosenPort, io);

            if (port == -1)
            {
                return(null);
            }
            if (!VaildDrive(cleanHomeDir, io))
            {
                return(null);
            }
            var endPoint   = new IPEndPoint((IPAddress.Loopback), port);
            var zSocket    = new DefaultZSocket(endPoint);
            var properties = new ServerProperties(cleanHomeDir,
                                                  port, new ServerTime(), io,
                                                  new Readers
            {
                FileProcess      = new FileProcessor(),
                DirectoryProcess = new DirectoryProcessor()
            });

            return(new MainServer(zSocket, properties,
                                  new HttpServiceFactory(new Service404()),
                                  new DefaultRequestProcessor(),
                                  new List <string>()
            {
                "FileServer.Core"
            },
                                  new List <Assembly>()
            {
                Assembly.GetExecutingAssembly()
            }));
        }
        /// <summary>
        /// Initializes the datastore with the server configuration.
        /// </summary>
        /// <param name="serverDescription">The server description.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="messageContext">The message context.</param>
        /// <param name="certificateValidator">The certificate validator.</param>
        /// <param name="instanceCertificate">The instance certificate.</param>
        public ServerInternalData(
            ServerProperties serverDescription,
            ApplicationConfiguration configuration,
            IServiceMessageContext messageContext,
            CertificateValidator certificateValidator,
            X509Certificate2 instanceCertificate)
        {
            m_serverDescription = serverDescription;
            m_configuration     = configuration;
            m_messageContext    = messageContext;

            m_endpointAddresses = new List <Uri>();

            foreach (string baseAddresses in m_configuration.ServerConfiguration.BaseAddresses)
            {
                Uri url = Utils.ParseUri(baseAddresses);

                if (url != null)
                {
                    m_endpointAddresses.Add(url);
                }
            }

            m_namespaceUris = m_messageContext.NamespaceUris;
            m_factory       = m_messageContext.Factory;

            m_serverUris = new StringTable();
            m_typeTree   = new TypeTable(m_namespaceUris);

            // add the server uri to the server table.
            m_serverUris.Append(m_configuration.ApplicationUri);

            // create the default system context.
            m_defaultSystemContext = new ServerSystemContext(this);
        }
 public OutgoingPayloadHandler(ServerProperties serverProperties)
 {
     Header              = new byte[Properties.TS3SRV_WEBLIST_PROTOCOL_HEADERLEN];
     PayloadType         = PayloadTypes.Dataupload;
     CanCreateChannel    = serverProperties.CanCreateChannels;
     IsPasswordProtected = serverProperties.IsPasswordProtected;
     ServerProperties    = serverProperties;
 }
 public bool CanProcessRequest(string request, ServerProperties serverProperties)
 {
     if (request == "GET /Default HTTP/1.1")
     {
         return(false);
     }
     return(_mock.Object.CanProcessRequest(request, serverProperties));
 }
Example #30
0
        /// <summary>
        /// This method returns the compile time properties for the server.
        /// </summary>
        protected override ServerProperties LoadServerProperties()
        {
            ServerProperties properties = new ServerProperties();

            properties.DatatypeAssemblies.Add(Assembly.GetExecutingAssembly().FullName);

            return(properties);
        }
        /// <summary>
        /// Initializes the datastore with the server configuration.
        /// </summary>
        /// <param name="serverDescription">The server description.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="messageContext">The message context.</param>
        /// <param name="certificateValidator">The certificate validator.</param>
        /// <param name="instanceCertificate">The instance certificate.</param>
        public ServerInternalData(
            ServerProperties                     serverDescription, 
            ApplicationConfiguration             configuration,
            ServiceMessageContext                messageContext,
            CertificateValidator                 certificateValidator,
            X509Certificate2                     instanceCertificate)
        {
            m_serverDescription = serverDescription;
            m_configuration = configuration;
            m_messageContext = messageContext;
            
            m_endpointAddresses = new List<Uri>();

            foreach (string baseAddresses in m_configuration.ServerConfiguration.BaseAddresses)
            {
                Uri url = Utils.ParseUri(baseAddresses);

                if (url != null)
                {
                    m_endpointAddresses.Add(url);
                }
            }
            
            m_namespaceUris = m_messageContext.NamespaceUris;
            m_factory = m_messageContext.Factory;

            m_serverUris = new StringTable();
            m_typeTree = new TypeTable(m_namespaceUris);

#if LEGACY_CORENODEMANAGER
            m_typeSources = new TypeSourceTable();
#endif
                                                
            // add the server uri to the server table.
            m_serverUris.Append(m_configuration.ApplicationUri);

            // create the default system context.
            m_defaultSystemContext = new ServerSystemContext(this);
        }
 public ProxyProperties(HttpWebClientProtocol proxy)
 {
     Timeout = proxy.Timeout;
     AllowAutoRedirect = proxy.AllowAutoRedirect;
     PreAuthenticate = proxy.PreAuthenticate;
     if (proxy.CookieContainer == null)
     {
         UseCookieContainer = true;
     }
     Server = new ServerProperties();
     Server.Url = proxy.Url;
     SetCredentialValues(proxy.Credentials, new Uri(Server.Url), out Server.UseDefaultCredentials,
                         out Server.UserNameForBasicAuth, out Server.PasswordForBasicAuth);
     WebProxy proxy1 = proxy.Proxy as WebProxy;
     if (proxy1 != null)
     {
         HttpProxy = new ServerProperties();
         HttpProxy.Url = proxy1.Address.ToString();
         SetCredentialValues(proxy1.Credentials, new Uri(HttpProxy.Url), out HttpProxy.UseDefaultCredentials,
                             out HttpProxy.UserNameForBasicAuth, out HttpProxy.PasswordForBasicAuth);
     }
     InitAdditionalProperties(proxy);
 }
 /// <summary>
 /// Partially modify a Server You can use update attributes of a server
 /// </summary>
 /// <param name="datacenterId"></param> 
 /// <param name="serverId">The unique ID of the server</param> 
 /// <param name="server">Modified properties of Server</param> 
 /// <param name="body"></param> 
 /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> 
 /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param> 
 /// <returns>Server</returns>
 public Server PartialUpdate(string datacenterId, string serverId, ServerProperties server, Body3 body = null, bool? parameter = null, int? depth = null)
 {
     ApiResponse<Server> response = PartialUpdateWithHttpInfo(datacenterId, serverId, server, body, parameter, depth);
     return response.Data;
 }
        /// <summary>
        /// Partially modify a Server You can use update attributes of a server
        /// </summary>
        /// <param name="datacenterId"></param>
        /// <param name="serverId">The unique ID of the server</param>
        /// <param name="server">Modified properties of Server</param>
        /// <param name="body"></param>
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param>
        /// <returns>Task of ApiResponse (Server)</returns>
        public async System.Threading.Tasks.Task<ApiResponse<Server>> PartialUpdateAsyncWithHttpInfo(string datacenterId, string serverId, ServerProperties server, Body3 body = null, bool? parameter = null, int? depth = null)
        {
            // verify the required parameter 'datacenterId' is set
            if (datacenterId == null) throw new ApiException(400, "Missing required parameter 'datacenterId' when calling PartialUpdate");
            // verify the required parameter 'serverId' is set
            if (serverId == null) throw new ApiException(400, "Missing required parameter 'serverId' when calling PartialUpdate");
            // verify the required parameter 'server' is set
            if (server == null) throw new ApiException(400, "Missing required parameter 'server' when calling PartialUpdate");


            var path_ = "/datacenters/{datacenterId}/servers/{serverId}";

            var pathParams = new Dictionary<String, String>();
            var queryParams = new Dictionary<String, String>();
            var headerParams = new Dictionary<String, String>();
            var formParams = new Dictionary<String, String>();
            var fileParams = new Dictionary<String, FileParameter>();
            Object postBody = null;

            // to determine the Content-Type header
            String[] httpContentTypes = new String[] {
                "application/vnd.profitbricks.partial-properties+json", "application/json"
            };
            String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);

            // to determine the Accept header
            String[] httpHeaderAccepts = new String[] {
                "application/vnd.profitbricks.resource+json"
            };
            String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
            if (httpHeaderAccept != null)
                headerParams.Add("Accept", httpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            pathParams.Add("format", "json");
            if (datacenterId != null) pathParams.Add("datacenterId", Configuration.ApiClient.ParameterToString(datacenterId)); // path parameter
            if (serverId != null) pathParams.Add("serverId", Configuration.ApiClient.ParameterToString(serverId)); // path parameter

            if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
            if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter



            postBody = Configuration.ApiClient.Serialize(server); // http body (model) parameter



            // authentication (basicAuth) required

            // http basic authentication required
            if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
            {
                headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
            }


            // make the HTTP request
            IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_,
                Method.PATCH, queryParams, postBody, headerParams, formParams, fileParams,
                pathParams, httpContentType);

            int statusCode = (int)response.StatusCode;

            if (statusCode >= 400)
                throw new ApiException(statusCode, "Error calling PartialUpdate: " + response.Content, response.Content);
            else if (statusCode == 0)
                throw new ApiException(statusCode, "Error calling PartialUpdate: " + response.ErrorMessage, response.ErrorMessage);

            return new ApiResponse<Server>(statusCode,
                response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (Server)Configuration.ApiClient.Deserialize(response, typeof(Server)));

        }
        /// <summary>
        /// Partially modify a Server You can use update attributes of a server
        /// </summary>
        /// <param name="datacenterId"></param>
        /// <param name="serverId">The unique ID of the server</param>
        /// <param name="server">Modified properties of Server</param>
        /// <param name="body"></param>
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param>
        /// <returns>Task of Server</returns>
        public async System.Threading.Tasks.Task<Server> PartialUpdateAsync(string datacenterId, string serverId, ServerProperties server, Body3 body = null, bool? parameter = null, int? depth = null)
        {
            ApiResponse<Server> response = await PartialUpdateAsyncWithHttpInfo(datacenterId, serverId, server, body, parameter, depth);
            return response.Data;

        }
Example #36
0
        /// <summary>
        /// This method returns the compile time properties for the server.
        /// </summary>
        protected override ServerProperties LoadServerProperties()
        {
            ServerProperties properties = new ServerProperties();

            properties.DatatypeAssemblies.Add(Assembly.GetExecutingAssembly().FullName);

            return properties;
        }
        /// <summary>
        /// Loads the non-configurable properties for the application.
        /// </summary>
        /// <remarks>
        /// These properties are exposed by the server but cannot be changed by administrators.
        /// </remarks>
        protected override ServerProperties LoadServerProperties()
        {
            ServerProperties properties = new ServerProperties();

            properties.ManufacturerName = "OPC Foundation";
            properties.ProductName      = "OPC UA SDK Samples";
            properties.ProductUri       = "http://opcfoundation.org/UA/Samples/v1.0";
            properties.SoftwareVersion  = Utils.GetAssemblySoftwareVersion();
            properties.BuildNumber      = Utils.GetAssemblyBuildNumber();
            properties.BuildDate        = Utils.GetAssemblyTimestamp();

            // TBD - All applications have software certificates that need to added to the properties.

            // for (int ii = 0; ii < certificates.Count; ii++)
            // {
            //    properties.SoftwareCertificates.Add(certificates[ii]);
            // }

            return properties; 
        }