Example #1
0
        public void Equals()
        {
            var nvp = new NameValuePair<string>("test");
            nvp.Value.Add("one");
            nvp.Value.Add("two");

            var nvp2 = new NameValuePair<string>("test");
            nvp2.Value.Add("one");
            nvp2.Value.Add("two");

            var nvp3 = new NameValuePair<string>("test3");
            nvp3.Value.Add("one");
            nvp3.Value.Add("two");

            Assert.IsTrue(nvp == nvp2);
            Assert.IsFalse(nvp != nvp2);
            Assert.IsTrue(nvp.Equals(nvp2));
            Assert.IsTrue(nvp.Equals((object)nvp2));

            Assert.IsFalse(nvp == null);
            Assert.IsTrue(nvp != null);
            Assert.IsFalse(nvp.Equals(null));

            Assert.IsFalse(nvp.Equals("test"));
            Assert.IsFalse(nvp == nvp3);
            Assert.IsTrue(nvp != nvp3);
            Assert.IsFalse(nvp.Equals(nvp3));
            Assert.IsFalse(nvp.Equals((object)nvp3));
        }
        public void SetGetProperties()
        {
            var parameter = new BooleanParameter();
            var trueValue = new NameValuePair("TrueName", "TrueValue");
            var falseValue = new NameValuePair("FalseName", "FalseValue");
            parameter.TrueValue = trueValue;
            parameter.FalseValue = falseValue;
            Assert.AreEqual(typeof(string), parameter.DataType, "DataType does not match");
            Assert.AreSame(trueValue, parameter.TrueValue);
            Assert.AreSame(falseValue, parameter.FalseValue);
            Assert.IsNotNull(parameter.AllowedValues);
            Assert.AreEqual(2, parameter.AllowedValues.Length);
            Assert.AreEqual(trueValue.Name, parameter.AllowedValues[0]);
            Assert.AreEqual(falseValue.Name, parameter.AllowedValues[1]);

            parameter.IsRequired = false;
            Assert.AreEqual(false, parameter.IsRequired, "IsRequired does not match");
            parameter.IsRequired = true;
            Assert.AreEqual(true, parameter.IsRequired, "IsRequired does not match");
            parameter.Description = "Some description goes here";
            Assert.AreEqual("Some description goes here", parameter.Description, "Description does not match");
            parameter.Name = "Some name";
            Assert.AreEqual("Some name", parameter.Name, "Name does not match");
            Assert.AreEqual("Some name", parameter.DisplayName, "DisplayName does not match");
            parameter.DisplayName = "Another name";
            Assert.AreEqual("Another name", parameter.DisplayName, "DisplayName does not match");
        }
 public ExposedModuleFunction(string function,string description, string[] allowedNullParameters, NameValuePair[] parameterDescriptions)
 {
     _function = function;
     _description=description;
     _allowedNullParameters = allowedNullParameters;
     _parameterDescriptions = parameterDescriptions;
 }
        /// <summary>
        /// Generates parameter values from the incoming request values.
        /// </summary>
        /// <param name="result">The result.</param>
        public void GenerateSystemParameterValues(IIntegrationResult result)
        {
            var props = result.IntegrationProperties;
            foreach (var property in props.Keys)
            {
                // Generate the build value
                var key = string.Format("${0}", property);
                var value = (props[property] ?? string.Empty).ToString();
                result.IntegrationRequest.BuildValues[key] = value;

                // Add to the parameters
                var namedValue = new NameValuePair(key, value);
                if (result.Parameters.Contains(namedValue))
                {
                    // Replace an existing value
                    var index = result.Parameters.IndexOf(namedValue);
                    result.Parameters[index] = namedValue;
                }
                else
                {
                    // Add a new value
                    result.Parameters.Add(namedValue);
                }
            }
        }
        public void SetGetProperties()
        {
            var parameter = new DateParameter();
            var trueValue = new NameValuePair("TrueName", "TrueValue");
            var falseValue = new NameValuePair("FalseName", "FalseValue");
            Assert.IsNull(parameter.AllowedValues);
            Assert.AreEqual(typeof(DateTime), parameter.DataType, "DataType does not match");

            parameter.IsRequired = false;
            Assert.AreEqual(false, parameter.IsRequired, "IsRequired does not match");
            parameter.IsRequired = true;
            Assert.AreEqual(true, parameter.IsRequired, "IsRequired does not match");
            parameter.Description = "Some description goes here";
            Assert.AreEqual("Some description goes here", parameter.Description, "Description does not match");
            parameter.Name = "Some name";
            Assert.AreEqual("Some name", parameter.Name, "Name does not match");
            Assert.AreEqual("Some name", parameter.DisplayName, "DisplayName does not match");
            parameter.DisplayName = "Another name";
            Assert.AreEqual("Another name", parameter.DisplayName, "DisplayName does not match");

            var minValue = new DateTime(2010, 1, 1);
            parameter.MinimumValue = minValue;
            Assert.AreEqual(minValue, parameter.MinimumValue);

            var maxValue = new DateTime(2010, 1, 1);
            parameter.MaximumValue = maxValue;
            Assert.AreEqual(maxValue, parameter.MaximumValue);

            var defaultValue = "today";
            parameter.ClientDefaultValue = defaultValue;
            Assert.AreEqual(defaultValue, parameter.ClientDefaultValue);
        }
Example #6
0
 public void Constructor()
 {
     var nvp = new NameValuePair<string>("test");
     Assert.IsNotNull(nvp.Key);
     Assert.AreEqual("test", nvp.Key);
     Assert.IsNotNull(nvp.Value);
     CustomAssert.IsEmpty((ICollection)nvp.Value);
 }
Example #7
0
        public void GetHashCodeTests()
        {
            var nvp = new NameValuePair<string>("test");
            nvp.Value.Add("one");
            nvp.Value.Add("two");

            Assert.AreEqual("test".GetHashCode(), nvp.GetHashCode());
        }
Example #8
0
        public void String()
        {
            var nvp = new NameValuePair<string>("test");
            nvp.Value.Add("one");
            nvp.Value.Add("two");

            Assert.AreEqual("[test: one, two]", nvp.ToString());
        }
Example #9
0
 public void Add()
 {
     var nvp = new NameValuePair<string>("test");
     nvp.Value.Add("one");
     nvp.Value.Add("two");
     CustomAssert.IsNotEmpty((ICollection)nvp.Value);
     Assert.IsTrue(nvp.Value.Count == 2);
     Assert.AreEqual("one", nvp.Value[0]);
     Assert.AreEqual("two", nvp.Value[1]);
 }
 public GenericEvent(string name, NameValuePair[] attributes)
 {
     _name = name;
     foreach (NameValuePair nvp in attributes)
     {
         if (_pars.ContainsKey(nvp.Name))
             _pars.Remove(nvp.Name);
         _pars.Add(nvp.Name, nvp.Value);
     }
 }
        // synonyms hashtable is meant to be read-only translation of parsed string
        // keywords/synonyms to a known keyword string
        internal DbConnectionOptions(string connectionString, Hashtable synonyms)
        {
            _parsetable = new Hashtable();
            _usersConnectionString = ((null != connectionString) ? connectionString : "");

            // first pass on parsing, initial syntax check
            if (0 < _usersConnectionString.Length)
            {
                KeyChain = ParseInternal(_parsetable, _usersConnectionString, synonyms);
            }
        }
        internal DbConnectionOptions(string connectionString, IList<string> validKeywords)
        {
            DebugCheck.NotNull(validKeywords);

            _usersConnectionString = connectionString ?? "";

            // first pass on parsing, initial syntax check
            if (0 < _usersConnectionString.Length)
            {
                KeyChain = ParseInternal(_parsetable, _usersConnectionString, validKeywords);
            }
        }
Example #13
0
        public void HttpRequestheaders()
        {
            var ctx = new OwinContext("1.0", TokenSource.Token);

            NameValuePair host = new NameValuePair("HTTP_HOST", "localhost");
            ctx.SetOwinParametersFromFastCgiNvp(host);

            NameValuePair coolNewHeader = new NameValuePair("HTTP_COOL_NEW_HEADER", "anything");
            ctx.SetOwinParametersFromFastCgiNvp(coolNewHeader);

            Assert.AreEqual("localhost", ctx.RequestHeaders["Host"][0]);
            Assert.AreEqual("anything", ctx.RequestHeaders["Cool-New-Header"][0]);
        }
Example #14
0
        public void UriCheck()
        {
            var ctx = new OwinContext("1.0", TokenSource.Token);

            NameValuePair docUri = new NameValuePair("DOCUMENT_URI", "/about/terms");
            NameValuePair host = new NameValuePair("HTTP_HOST", "localhost");
            ctx.SetOwinParametersFromFastCgiNvp(docUri);
            ctx.SetOwinParametersFromFastCgiNvp(host);

            Assert.AreEqual("http://localhost/about/terms", ctx.CompleteUri);
            Assert.AreEqual(string.Empty, (string)ctx["owin.RequestPathBase"]);
            Assert.AreEqual("/about/terms", (string)ctx["owin.RequestPath"]);
        }
        public BaseMapSectionLabel(NameValuePair option)
        {
            Name = option.Name;
            Value = option.Value;

            Text = option.Name.ToUpper();

            TextAlignment = UITextAlignment.Center;

            Font = UIFont.FromName("HelveticaNeue-Bold", 11);

            Layer.BorderWidth = 0.5f;
        }
Example #16
0
        public MainViewModel()
        {
            this.ModeCollection = new ObservableCollection<NameValuePair<JryVideoDataSourceProviderManagerMode>>()
            {
                JryVideoDataSourceProviderManagerMode.Public.WithName(
                    nameof(JryVideoDataSourceProviderManagerMode.Public)),
                JryVideoDataSourceProviderManagerMode.Private.WithName(
                    nameof(JryVideoDataSourceProviderManagerMode.Private)),
            };
            this.selectedMode = this.ModeCollection[0];

            this.GetAgent().FlagChanged += this.MainViewModel_FlagChanged;
        }
 public void SetGetProperties()
 {
     ReplacementDynamicValue value = new ReplacementDynamicValue();
     value.FormatValue = "test parameter";
     Assert.AreEqual("test parameter", value.FormatValue, "FormatValue not being get/set correctly");
     value.PropertyName = "test property";
     Assert.AreEqual("test property", value.PropertyName, "PropertyName not being get/set correctly");
     var parameters = new NameValuePair[] 
     {
         new NameValuePair("name", "value")
     };
     value.Parameters = parameters;
     Assert.AreSame(parameters, value.Parameters);
 }
Example #18
0
        public NameValuePair FindOrCreate(string key)
        {
            NameValuePair nvp = Properties.Find(p => p.Name == key);
            if (nvp == null)
            {
                nvp = new NameValuePair()
                {
                    Name = key,
                    Value = ""
                };
                Properties.Add(nvp);
            }

            return nvp;
        }
 private static KeyValuePair <string, string> ToKeyValuePair(NameValuePair nvp)
 {
     return(new KeyValuePair <string, string>(nvp.Name, nvp.Value));
 }
Example #20
0
 /// <summary>
 /// 获取一行数据
 /// </summary>
 /// <param name="rowValues"></param>
 protected abstract void GetRowValues(ref NameValuePair rowValues);
        private static NameValuePair ParseInternal(Hashtable parsetable, string connectionString, Hashtable synonyms)
        {
            Debug.Assert(null != connectionString, "null connectionstring");
            var buffer = new StringBuilder();
            NameValuePair localKeychain = null, keychain = null;
#if DEBUG
            try
            {
#endif
            var nextStartPosition = 0;
            var endPosition = connectionString.Length;
            while (nextStartPosition < endPosition)
            {
                var startPosition = nextStartPosition;

                string keyname, keyvalue;
                nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, out keyname, out keyvalue);
                if (string.IsNullOrEmpty(keyname))
                {
                    // if (nextStartPosition != endPosition) { throw; }
                    break;
                }

#if DEBUG
                    Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
                    Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
                var realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
                if (!IsKeyNameValid(realkeyname))
                {
                    throw new ArgumentException(Strings.ADP_KeywordNotSupported(keyname));
                }
                parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)

                if (null != localKeychain)
                {
                    localKeychain = localKeychain.Next = new NameValuePair();
                }
                else
                {
                    // first time only - don't contain modified chain from UDL file
                    keychain = localKeychain = new NameValuePair();
                }
            }
#if DEBUG
            }
            catch (ArgumentException e)
            {
                ParseComparision(parsetable, connectionString, synonyms, e);
                throw;
            }
            ParseComparision(parsetable, connectionString, synonyms, null);
#endif
            return keychain;
        }
        public void UpsertCustomIntegrationProperty(NameValuePair nv)
        {
            int ms_index = this.CustomIntegrationProperties.IndexOf(nv);

            if (ms_index < 0)
            {
                this.CustomIntegrationProperties.Add(nv);
            }
            else
            {
                this.CustomIntegrationProperties[ms_index] = nv;
            }
        }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        public void Add(string name)
        {
            NameValuePair nvp = new NameValuePair(name);

            _list.Add(nvp);
        }
 public NameValuePair(string name, string value, NameValuePair next) : this(name, value)
 {
     _next = next;
 }
Example #25
0
 public static NameValuePair CreateNameValuePair(string name, string value)
 {
     NameValuePair nameValuePair = new NameValuePair();
     nameValuePair.Name = name;
     nameValuePair.Value = value;
     return nameValuePair;
 }
Example #26
0
 public IList <NameValuePair> Add(NameValuePair pair)
 {
     Repository.Add(pair);
     return(ClearFilter());
 }
        public static IEntityValue CreateMetadataValue(IEntityRuntimeModel runtimeModel, NameValuePair metadata, IUIEditorMetadataPropertiesAvailableStatus requestedProperties)
        {
            var newMetadata = new UIEditorMetadataValue(runtimeModel, new UIEditorMetadataPropertiesAvailableStatus());

            if (requestedProperties.Name)
            {
                newMetadata.Name = metadata.Name;
            }

            if (requestedProperties.Value)
            {
                newMetadata.Value = metadata.Value;
            }

            return(newMetadata);
        }
Example #28
0
        public void ForceBuild(IProjectSpecifier projectSpecifier, string sessionToken, Dictionary <string, string> parameters)
        {
            var manager = GetCruiseManager(projectSpecifier, sessionToken);

            manager.ForceBuild(projectSpecifier.ProjectName, NameValuePair.FromDictionary(parameters));
        }
Example #29
0
        public static void MigrateServerData()
        {
            locations     = locationRepository.Collection.AsQueryable().ToList();
            businessHours = businessHoursRepository.Collection.AsQueryable().ToList();
            credentials   = credentialsRepository.Collection.AsQueryable().ToList();
            //  disks = serverRepository.Collection.AsQueryable().ToList();
            //Damino Servers
            var dominoServers = new Mapper <Server>("DominoServer.json").Map();
            var disksettings  = new Mapper <DiskSetting>("DiskSetings.json").Map();

            foreach (var server in dominoServers)
            {
                server.DeviceType = Enums.ServerType.Domino.ToDescription();
                BuildServerData(server);
            }
            upsertData(dominoServers);
            //if (dominoServers.Count > 0)
            //    serverRepository.Insert(dominoServers);


            //IBM WebSphere

            var websphereCell = new Mapper <Server>("WebSphereCell.json").Map();

            foreach (var server in websphereCell)
            {
                server.Id         = ObjectId.GenerateNewId().ToString();
                server.DeviceType = Enums.ServerType.WebSphereCell.ToDescription();
                BuildServerData(server);
            }

            var websphereNode = new Mapper <Server>("WebSphereNode.json").Map();

            foreach (var server in websphereNode)
            {
                server.Id         = ObjectId.GenerateNewId().ToString();
                server.DeviceType = Enums.ServerType.WebSphereNode.ToDescription();
            }
            var websphereServer = new Mapper <Server>("WebSphere.json").Map();

            foreach (var server in websphereServer)
            {
                server.Id         = ObjectId.GenerateNewId().ToString();
                server.DeviceType = Enums.ServerType.WebSphere.ToDescription();
                BuildServerData(server);
            }
            foreach (Server node in websphereNode)
            {
                List <String> ListOfIds = new List <String>();
                String        CellName  = "";
                foreach (Server server in websphereServer.Where(i => i.DeviceName.Contains("~" + node.DeviceName + "]")).ToList())
                {
                    ListOfIds.Add(server.Id);
                    server.NodeId = node.Id;
                    CellName      = server.DeviceName.Substring(server.DeviceName.IndexOf("[") + 1, server.DeviceName.IndexOf("~") - server.DeviceName.IndexOf("[") - 1);
                    server.CellId = websphereCell.FirstOrDefault(i => i.DeviceName.Equals(CellName)).Id;
                }
                node.ServerId = ListOfIds;
                node.CellId   = websphereCell.FirstOrDefault(i => i.DeviceName.Equals(CellName)).Id;
            }

            foreach (Server cell in websphereCell)
            {
                List <WebSphereNode> nodes = new List <WebSphereNode>();
                foreach (Server node in websphereNode.Where(i => i.CellId == cell.Id))
                {
                    WebSphereNode wsNode = new WebSphereNode();
                    wsNode.HostName = node.IPAddress;
                    wsNode.NodeId   = node.Id;
                    wsNode.NodeName = node.DeviceName;
                    List <WebSphereServer> wsServer = new List <WebSphereServer>();
                    foreach (Server server in websphereServer.Where(i => i.NodeId == node.Id))
                    {
                        wsServer.Add(new WebSphereServer()
                        {
                            ServerId = server.Id, ServerName = server.DeviceName
                        });
                    }
                    wsNode.WebSphereServers = wsServer;
                    nodes.Add(wsNode);
                }
                cell.Nodes = nodes;
            }

            upsertData(websphereServer);
            upsertData(websphereCell);
            upsertData(websphereNode);


            //if (websphereServer.Count > 0)
            //    serverRepository.Insert(websphereServer);
            //if (websphereCell.Count > 0)
            //    serverRepository.Insert(websphereCell);
            //if (websphereNode.Count > 0)
            //    serverRepository.Insert(websphereNode);


            //IBM Connections
            var ConnectionServers = new Mapper <Server>("IBMConnections.json").Map();

            string query      = "SELECT S.ServerName,IT.EnableSimulationTests,IT.ResponseThreshold,TM.Tests from [vitalsigns].[dbo].[Servers] S inner join [vitalsigns].[dbo].[IBMConnectionsTests] IT ON IT.ServerId = S.Id Inner JOIN[vitalsigns].[dbo].[TestsMaster] TM ON IT.Id = TM.Id";
            var    testsTable = (MappingHelper.ExecuteQuery(query)).AsEnumerable().Select(x => new
            {
                ServerName            = x.Field <string>(0).Trim(),
                EnableSimulationTests = x.Field <bool>(1),
                ResponseThreshold     = x.Field <int?>(2),
                Test = x.Field <string>(3)
            }).ToList();

            foreach (var server in ConnectionServers)
            {
                server.DeviceType = Enums.ServerType.IBMConnections.ToDescription();
                var testRows = testsTable.Where(x => x.ServerName == server.DeviceName).ToList();
                List <NameValuePair> simulationTests = new List <NameValuePair>();
                List <Tests>         tests           = new List <Tests>();
                foreach (var row in testRows)
                {
                    if (row.EnableSimulationTests)
                    {
                        NameValuePair stest = new NameValuePair();
                        stest.Name  = row.Test;
                        stest.Value = row.ResponseThreshold.ToString();
                        simulationTests.Add(stest);

                        Tests test = new Tests();
                        test.TestName  = row.Test;
                        test.Threshold = row.ResponseThreshold;
                        tests.Add(test);
                    }
                }
                if (simulationTests.Count() > 0)
                {
                    server.SimulationTests = simulationTests;
                }
                BuildServerData(server);
            }

            upsertData(ConnectionServers);

            //if (ConnectionServers.Count > 0)
            //    serverRepository.Insert(ConnectionServers);


            //sametime server
            var sameTimeServers = new Mapper <Server>("Sametime.json").Map();

            query = "SELECT ID,AliasName From [vitalsigns].[dbo].[Credentials]";
            var credentialsTable = (MappingHelper.ExecuteQuery(query)).AsEnumerable().Select(x => new
            {
                Id        = x.Field <int?>(0),
                AliasName = x.Field <string>(1)
            }).ToList();

            foreach (var server in sameTimeServers)
            {
                server.DeviceType = Enums.ServerType.Sametime.ToDescription();
                BuildServerData(server);
                if (!string.IsNullOrEmpty(server.User1CredentialsId))
                {
                    int credId     = Convert.ToInt32(server.User1CredentialsId);
                    var credential = credentialsTable.FirstOrDefault(x => x.Id == credId);
                    if (credential != null)
                    {
                        server.User1CredentialsId = SetCredentials(credential.AliasName);
                    }
                    else
                    {
                        server.User1CredentialsId = null;
                    }
                }
                else
                {
                    server.User1CredentialsId = null;
                }
                if (!string.IsNullOrEmpty(server.User2CredentialsId))
                {
                    int credId     = Convert.ToInt32(server.User2CredentialsId);
                    var credential = credentialsTable.FirstOrDefault(x => x.Id == credId);
                    if (credential != null)
                    {
                        server.User2CredentialsId = SetCredentials(credential.AliasName);
                    }
                    else
                    {
                        server.User2CredentialsId = null;
                    }
                }
                else
                {
                    server.User2CredentialsId = null;
                }
            }

            upsertData(sameTimeServers);

            //if (sameTimeServers.Count > 0)
            //    serverRepository.Insert(sameTimeServers);
        }
Example #30
0
        public static void Run(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Error: Must have 2 parameters, one is config filename, "
                                  + "the other is the local filename to upload");
                return;
            }

            string conf_filename  = args[0];
            string local_filename = args[1];

            try
            {
                ClientGlobal.init(conf_filename);
                Console.WriteLine("network_timeout=" + ClientGlobal.g_network_timeout + "ms");
                Console.WriteLine("charset=" + ClientGlobal.g_charset);

                string        group_name;
                string        remote_filename;
                ServerInfo[]  servers;
                TrackerClient tracker       = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();

                StorageServer storageServer = null;

                StorageClient   client = new StorageClient(trackerServer, storageServer);
                byte[]          file_buff;
                NameValuePair[] meta_list;
                string[]        results;
                string          master_filename;
                string          prefix_name;
                string          file_ext_name;
                string          generated_slave_filename;
                int             errno;

                meta_list    = new NameValuePair[4];
                meta_list[0] = new NameValuePair("width", "800");
                meta_list[1] = new NameValuePair("heigth", "600");
                meta_list[2] = new NameValuePair("bgcolor", "#FFFFFF");
                meta_list[3] = new NameValuePair("author", "Mike");

                file_buff = Encoding.GetEncoding(ClientGlobal.g_charset).GetBytes("this is a test");
                Console.WriteLine("file length: " + file_buff.Length);

                group_name = null;
                StorageServer[] storageServers = tracker.getStoreStorages(trackerServer, group_name);
                if (storageServers == null)
                {
                    Console.WriteLine("get store storage servers fail, error code: " + tracker.ErrorCode);
                }
                else
                {
                    Console.WriteLine("store storage servers count: " + storageServers.Length);
                    for (int k = 0; k < storageServers.Length; k++)
                    {
                        Console.WriteLine((k + 1) + ". " + storageServers[k].InetSockAddr.Address + ":" + storageServers[k].InetSockAddr.Port);
                    }
                    Console.WriteLine("");
                }

                Stopwatch sw = new Stopwatch();
                sw.Start();
                results = client.upload_file(file_buff, "txt", meta_list);
                sw.Stop();
                Console.WriteLine("upload_file time used: " + sw.ElapsedMilliseconds + " ms");

                if (results == null)
                {
                    Console.WriteLine("upload file fail, error code: " + client.ErrorCode);
                    return;
                }
                else
                {
                    group_name      = results[0];
                    remote_filename = results[1];
                    Console.WriteLine("group_name: " + group_name + ", remote_filename: " + remote_filename);
                    Console.WriteLine(client.get_file_info(group_name, remote_filename));

                    servers = tracker.getFetchStorages(trackerServer, group_name, remote_filename);
                    if (servers == null)
                    {
                        Console.WriteLine("get storage servers fail, error code: " + tracker.ErrorCode);
                    }
                    else
                    {
                        Console.WriteLine("storage servers count: " + servers.Length);
                        for (int k = 0; k < servers.Length; k++)
                        {
                            Console.WriteLine((k + 1) + ". " + servers[k].Ip_Addr + ":" + servers[k].Port);
                        }
                        Console.WriteLine("");
                    }

                    meta_list    = new NameValuePair[4];
                    meta_list[0] = new NameValuePair("width", "1024");
                    meta_list[1] = new NameValuePair("heigth", "768");
                    meta_list[2] = new NameValuePair("bgcolor", "#000000");
                    meta_list[3] = new NameValuePair("title", "Untitle");

                    sw.Restart();
                    errno = client.set_metadata(group_name, remote_filename, meta_list, ProtoCommon.STORAGE_SET_METADATA_FLAG_MERGE);
                    sw.Stop();
                    Console.WriteLine("set_metadata time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine("set_metadata success");
                    }
                    else
                    {
                        Console.WriteLine("set_metadata fail, error no: " + errno);
                    }

                    meta_list = client.get_metadata(group_name, remote_filename);
                    if (meta_list != null)
                    {
                        for (int i = 0; i < meta_list.Length; i++)
                        {
                            Console.WriteLine(meta_list[i]._Name + " " + meta_list[i]._Value);
                        }
                    }

                    sw.Restart();
                    file_buff = client.download_file(group_name, remote_filename);
                    sw.Stop();
                    Console.WriteLine("download_file time used: " + sw.ElapsedMilliseconds + " ms");

                    if (file_buff != null)
                    {
                        Console.WriteLine("file length:" + file_buff.Length);
                        Console.WriteLine(Encoding.GetEncoding(ClientGlobal.g_charset).GetString(file_buff));
                    }

                    file_buff       = Encoding.GetEncoding(ClientGlobal.g_charset).GetBytes("this is a slave buff");
                    master_filename = remote_filename;
                    prefix_name     = "-part1";
                    file_ext_name   = "txt";
                    sw.Restart();
                    results = client.upload_file(group_name, master_filename, prefix_name, file_buff, file_ext_name, meta_list);
                    sw.Stop();
                    Console.WriteLine("upload_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (results != null)
                    {
                        Console.WriteLine("slave file group_name: " + results[0] + ", remote_filename: " + results[1]);

                        generated_slave_filename = ProtoCommon.genSlaveFilename(master_filename, prefix_name, file_ext_name);
                        if (!generated_slave_filename.Equals(results[1]))
                        {
                            Console.WriteLine("generated slave file: " + generated_slave_filename + "\n != returned slave file: " + results[1]);
                        }

                        Console.WriteLine(client.get_file_info(results[0], results[1]));
                    }

                    sw.Restart();
                    errno = client.delete_file(group_name, remote_filename);
                    sw.Stop();
                    Console.WriteLine("delete_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine("Delete file success");
                    }
                    else
                    {
                        Console.WriteLine("Delete file fail, error no: " + errno);
                    }
                }

                results = client.upload_file(local_filename, null, meta_list);
                if (results != null)
                {
                    string     file_id;
                    int        ts;
                    string     token;
                    string     file_url;
                    IPEndPoint inetSockAddr;

                    group_name      = results[0];
                    remote_filename = results[1];
                    file_id         = group_name + StorageClientEx.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remote_filename;

                    inetSockAddr = trackerServer.InetSockAddr;
                    file_url     = "http://" + inetSockAddr.Address;
                    if (ClientGlobal.g_tracker_http_port != 80)
                    {
                        file_url += ":" + ClientGlobal.g_tracker_http_port;
                    }
                    file_url += "/" + file_id;
                    if (ClientGlobal.g_anti_steal_token)
                    {
                        ts        = (int)ProtoCommon.DateTimeToUnixTimestamp(DateTime.Now);
                        token     = ProtoCommon.getToken(file_id, ts, ClientGlobal.g_secret_key);
                        file_url += "?token=" + token + "&ts=" + ts;
                    }

                    Console.WriteLine("group_name: " + group_name + ", remote_filename: " + remote_filename);
                    Console.WriteLine(client.get_file_info(group_name, remote_filename));
                    Console.WriteLine("file url: " + file_url);

                    errno = client.download_file(group_name, remote_filename, 0, 0, "d:\\" + remote_filename.Replace("/", "_"));
                    if (errno == 0)
                    {
                        Console.WriteLine("Download file success");
                    }
                    else
                    {
                        Console.WriteLine("Download file fail, error no: " + errno);
                    }

                    errno = client.download_file(group_name, remote_filename, 0, 0, new DownloadFileWriter("c:\\" + remote_filename.Replace("/", "-")));
                    if (errno == 0)
                    {
                        Console.WriteLine("Download file success");
                    }
                    else
                    {
                        Console.WriteLine("Download file fail, error no: " + errno);
                    }

                    master_filename = remote_filename;
                    prefix_name     = "-part2";
                    file_ext_name   = null;
                    sw.Restart();
                    results = client.upload_file(group_name, master_filename, prefix_name, local_filename, null, meta_list);
                    sw.Stop();
                    Console.WriteLine("upload_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (results != null)
                    {
                        Console.WriteLine("slave file group_name: " + results[0] + ", remote_filename: " + results[1]);

                        generated_slave_filename = ProtoCommon.genSlaveFilename(master_filename, prefix_name, file_ext_name);
                        if (!generated_slave_filename.Equals(results[1]))
                        {
                            Console.WriteLine("generated slave file: " + generated_slave_filename + "\n != returned slave file: " + results[1]);
                        }

                        Console.WriteLine(client.get_file_info(results[0], results[1]));
                    }
                }

                System.IO.FileInfo f;
                f             = new System.IO.FileInfo(local_filename);
                file_ext_name = Path.GetExtension(local_filename).Trim('.');

                results = client.upload_file(null, f.Length,
                                             new UploadLocalFileSender(local_filename), file_ext_name, meta_list);
                if (results != null)
                {
                    group_name      = results[0];
                    remote_filename = results[1];

                    Console.WriteLine("group name: " + group_name + ", remote filename: " + remote_filename);
                    Console.WriteLine(client.get_file_info(group_name, remote_filename));

                    master_filename = remote_filename;
                    prefix_name     = "-part3";
                    sw.Restart();
                    results = client.upload_file(group_name, master_filename, prefix_name, f.Length, new UploadLocalFileSender(local_filename), file_ext_name, meta_list);
                    sw.Stop();
                    Console.WriteLine("upload_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (results != null)
                    {
                        Console.WriteLine("slave file group_name: " + results[0] + ", remote_filename: " + results[1]);

                        generated_slave_filename = ProtoCommon.genSlaveFilename(master_filename, prefix_name, file_ext_name);
                        if (!generated_slave_filename.Equals(results[1]))
                        {
                            Console.WriteLine("generated slave file: " + generated_slave_filename + "\n != returned slave file: " + results[1]);
                        }

                        Console.WriteLine(client.get_file_info(results[0], results[1]));
                    }
                }
                else
                {
                    Console.WriteLine("Upload file fail, error no: " + errno);
                }

                storageServer = tracker.getFetchStorage(trackerServer, group_name, remote_filename);
                if (storageServer == null)
                {
                    Console.WriteLine("getFetchStorage fail, errno code: " + tracker.ErrorCode);
                    return;
                }
                /* for test only */
                Console.WriteLine("active test to storage server: " + ProtoCommon.activeTest(storageServer.getSocket()));

                storageServer.close();

                /* for test only */
                Console.WriteLine("active test to tracker server: " + ProtoCommon.activeTest(trackerServer.getSocket()));

                trackerServer.close();
            }
            catch (Exception ex)
            {
            }
        }
Example #31
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="name"></param>
 public void Add( string name )
 {
     NameValuePair nvp = new NameValuePair( name );
     _list.Add( nvp );
 }
 public void ForceBuild(string sessionToken, Dictionary <string, string> parameters, string userName)
 {
     client.SessionToken = sessionToken;
     client.DisplayName  = userName;
     client.ForceBuild(projectName, NameValuePair.FromDictionary(parameters));
 }
Example #33
0
        public static bool ReadConfig()
        {
            Stack <string> elements = new Stack <string>();

            try
            {
                ClearConfig();

                while (xmlReader.Read())
                {
                    switch (xmlReader.NodeType)
                    {
                    case XmlNodeType.Element:

                        bool isEmptyElement = false;

                        if (!String.IsNullOrEmpty(xmlReader.Name))
                        {
                            elements.Push(xmlReader.Name);
                            isEmptyElement = xmlReader.IsEmptyElement;
                        }

                        if (xmlReader.HasAttributes)
                        {
                            if (xmlReader.MoveToFirstAttribute())
                            {
                                NameValuePair nvpair = new NameValuePair();

                                do
                                {
                                    if (xmlReader.Name == "name")
                                    {
                                        nvpair.Name = xmlReader.Value;
                                    }

                                    if (xmlReader.Name == "value")
                                    {
                                        nvpair.Value = xmlReader.Value;
                                    }
                                }while (xmlReader.MoveToNextAttribute());

                                if (nvpair.IsValid())
                                {
                                    string xmlPath = "";

                                    foreach (string s in elements)
                                    {
                                        xmlPath = s + "/" + xmlPath;
                                    }

                                    nvpair.Name = xmlPath + nvpair.Name;

                                    configNameValuePairs.Add(nvpair);
                                }
                            }
                        }

                        if (isEmptyElement && elements.Count != 0)
                        {
                            elements.Pop();
                        }

                        break;

                    case XmlNodeType.Text:
                        // no need to support text yet
                        break;

                    case XmlNodeType.EndElement:

                        string peek = elements.Peek();

                        if (String.Compare(peek, xmlReader.Name, true) == 0)
                        {
                            elements.Pop();
                        }

                        break;
                    }
                }
            }
            catch //(Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }

            return(true);
        }
Example #34
0
        static bool TryParseNameValuePair(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out NameValuePair pair)
        {
            int    valueIndex, startIndex;
            bool   encoded = false;
            int?   id      = null;
            string name;

            pair = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            startIndex = index;
            if (!SkipParamName(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Invalid parameter name token at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            name = Encoding.ASCII.GetString(text, startIndex, index - startIndex);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            if (text[index] == (byte)'*')
            {
                // the parameter is either encoded or it has a part id
                index++;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }

                int value;
                if (ParseUtils.TryParseInt32(text, ref index, endIndex, out value))
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] == (byte)'*')
                    {
                        encoded = true;
                        index++;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }

                        if (index >= endIndex)
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                            }

                            return(false);
                        }
                    }

                    id = value;
                }
                else
                {
                    encoded = true;
                }
            }

            if (text[index] != (byte)'=')
            {
                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }
            }

            valueIndex = index;

            if (text[index] == (byte)'"')
            {
                ParseUtils.SkipQuoted(text, ref index, endIndex, throwOnError);
            }
            else if (options.ParameterComplianceMode == RfcComplianceMode.Strict)
            {
                ParseUtils.SkipToken(text, ref index, endIndex);
            }
            else
            {
                // Note: Google Docs, for example, does not always quote name/filename parameters
                // with spaces in the name. See https://github.com/jstedfast/MimeKit/issues/106
                // for details.
                while (index < endIndex && text[index] != (byte)';' && text[index] != (byte)'\r' && text[index] != (byte)'\n')
                {
                    index++;
                }
            }

            pair = new NameValuePair {
                ValueLength = index - valueIndex,
                ValueStart  = valueIndex,
                Encoded     = encoded,
                Name        = name,
                Id          = id
            };

            return(true);
        }
Example #35
0
        /// <summary>
        /// Gets the modifications.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public override Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
        {
            var revisionData = NameValuePair.ToDictionary(from.SourceControlData);

            if (to.LastIntegrationStatus == IntegrationStatus.Unknown)
            {
                ((SvnHistoryParser)historyParser).IntegrationStatusUnknown = true;
            }

            string wd = Path.GetFullPath(to.BaseFromWorkingDirectory(WorkingDirectory));

            if (WorkingFolderIsKnownAsSvnWorkingFolder(wd))
            {
                if (CleanUp)
                {
                    Execute(CleanupWorkingCopy(to));
                }

                if (Revert)
                {
                    Execute(RevertWorkingCopy(to));
                }

                if (this.DeleteObstructions)
                {
                    this.DeleteObstructionsFromWorking(to);
                }
            }
            else
            {
                Util.Log.Warning(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} is not a svn working folder", wd));
            }

            List <Modification> modifications  = new List <Modification>();
            List <string>       repositoryUrls = new List <string>();

            repositoryUrls.Add(TrunkUrl);

            if (CheckExternals)
            {
                ProcessResult resultOfSvnPropget = Execute(PropGetProcessInfo(to));
                List <string> externals          = ParseExternalsDirectories(resultOfSvnPropget);
                foreach (string external in externals)
                {
                    if (!repositoryUrls.Contains(external))
                    {
                        repositoryUrls.Add(external);
                    }
                }
            }

            foreach (string repositoryUrl in repositoryUrls)
            {
                var            lastRepositoryRevisionName = "SVN:LastRevision:" + repositoryUrl;
                Modification[] modsInRepository;
                string         lastRepositoryRevision = null;
                if (UseRevsionNumbers)
                {
                    // Since we are using the last revision number, see if there is any number stored to use
                    lastRepositoryRevision = revisionData.ContainsKey(lastRepositoryRevisionName)
                        ? revisionData[lastRepositoryRevisionName]
                        : null;
                    ProcessResult result = Execute(NewHistoryProcessInfoFromRevision(lastRepositoryRevision, to, repositoryUrl));
                    modsInRepository = ParseModifications(result, lastRepositoryRevision);
                }
                else
                {
                    // Use use the date range
                    ProcessResult result = Execute(NewHistoryProcessInfo(from, to, repositoryUrl));
                    modsInRepository = ParseModifications(result, from.StartTime, to.StartTime);
                }

                // If there are modifications, get the number and add them to the output
                if (modsInRepository != null)
                {
                    lastRepositoryRevision = Modification.GetLastChangeNumber(modsInRepository)
                                             ?? lastRepositoryRevision;
                    modifications.AddRange(modsInRepository);
                    revisionData[lastRepositoryRevisionName] = lastRepositoryRevision;
                }

                // Set the latest revision - this always need to be done just in case an external has triggered a build
                if (repositoryUrl == TrunkUrl)
                {
                    latestRevision = int.Parse(lastRepositoryRevision ?? "0", CultureInfo.CurrentCulture);
                    revisionData[lastRepositoryRevisionName] = lastRepositoryRevision;
                }
            }

            mods = modifications.ToArray();
            if (UrlBuilder != null)
            {
                UrlBuilder.SetupModification(mods);
            }
            FillIssueUrl(mods);

            // Store the latest revision number
            to.SourceControlData.Clear();
            NameValuePair.Copy(revisionData, to.SourceControlData);

            return(mods);
        }
Example #36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
        /// </summary>
        public ServerConfiguration()
        {
            UninstalledPlugins          = new string[] { };
            RemoteIPFilter              = new string[] { };
            LocalNetworkSubnets         = new string[] { };
            LocalNetworkAddresses       = new string[] { };
            CodecsUsed                  = new string[] { };
            ImageExtractionTimeoutMs    = 0;
            PathSubstitutions           = new PathSubstitution[] { };
            EnableSimpleArtistDetection = true;

            DisplaySpecialsWithinSeasons       = true;
            EnableExternalContentInSuggestions = true;

            ImageSavingConvention          = ImageSavingConvention.Compatible;
            PublicPort                     = DefaultHttpPort;
            PublicHttpsPort                = DefaultHttpsPort;
            HttpServerPortNumber           = DefaultHttpPort;
            HttpsPortNumber                = DefaultHttpsPort;
            EnableHttps                    = true;
            EnableDashboardResponseCaching = true;
            EnableAnonymousUsageReporting  = true;
            EnableCaseSensitiveItemIds     = true;

            EnableAutomaticRestart = true;
            AutoRunWebApp          = true;
            EnableRemoteAccess     = true;

            EnableUPnP   = true;
            MinResumePct = 5;
            MaxResumePct = 90;

            // 5 minutes
            MinResumeDurationSeconds = 300;

            LibraryMonitorDelay = 60;

            ContentTypes = new NameValuePair[] { };

            PreferredMetadataLanguage = "en";
            MetadataCountryCode       = "US";

            SortReplaceCharacters = new[] { ".", "+", "%" };
            SortRemoveCharacters  = new[] { ",", "&", "-", "{", "}", "'" };
            SortRemoveWords       = new[] { "the", "a", "an" };

            UICulture = "en-US";

            MetadataOptions = new[]
            {
                new MetadataOptions {
                    ItemType = "Book"
                },

                new MetadataOptions
                {
                    ItemType = "Movie"
                },

                new MetadataOptions
                {
                    ItemType = "MusicVideo",
                    DisabledMetadataFetchers = new [] { "The Open Movie Database" },
                    DisabledImageFetchers    = new [] { "The Open Movie Database", "FanArt" }
                },

                new MetadataOptions
                {
                    ItemType = "Series",
                    DisabledMetadataFetchers = new [] { "TheMovieDb" },
                    DisabledImageFetchers    = new [] { "TheMovieDb" }
                },

                new MetadataOptions
                {
                    ItemType = "MusicAlbum",
                    DisabledMetadataFetchers = new [] { "TheAudioDB" }
                },

                new MetadataOptions
                {
                    ItemType = "MusicArtist",
                    DisabledMetadataFetchers = new [] { "TheAudioDB" }
                },

                new MetadataOptions
                {
                    ItemType = "BoxSet"
                },

                new MetadataOptions
                {
                    ItemType = "Season",
                    DisabledMetadataFetchers = new [] { "TheMovieDb" },
                    DisabledImageFetchers    = new [] { "FanArt" }
                },

                new MetadataOptions
                {
                    ItemType = "Episode",
                    DisabledMetadataFetchers = new [] { "The Open Movie Database", "TheMovieDb" },
                    DisabledImageFetchers    = new [] { "The Open Movie Database", "TheMovieDb" }
                }
            };
        }
 /// <summary>
 /// Adds a new build value.
 /// </summary>
 /// <param name="name">The name of the build value.</param>
 /// <param name="value">The value of the build value.</param>
 /// <returns>The new build value.</returns>
 public NameValuePair AddBuildValue(string name, string value)
 {
     NameValuePair credential = new NameValuePair(name, value);
     buildValues.Add(credential);
     return credential;
 }
Example #38
0
        private float GetPrjParaValue(IProjectionCoordSystem prjCoordSystem, string paraName)
        {
            NameValuePair v = prjCoordSystem.GetParaByName(paraName);

            return(v != null ? (float)v.Value : 0f);
        }
        public NameValuePair GetCustomIntegrationProperty(string name)
        {
            NameValuePair nv = new NameValuePair(name, string.Empty);
            int ms_index = this.CustomIntegrationProperties.IndexOf(nv);
            if (ms_index < 0)
            {
                return null;
            }

            return CustomIntegrationProperties[ms_index];
        }
Example #40
0
        static bool TryParseNameValuePair(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out NameValuePair pair)
        {
            int  valueIndex, valueLength, startIndex;
            bool encoded = false;
            int? id      = null;

            byte[] value;
            string name;

            pair = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            startIndex = index;
            if (!SkipParamName(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter name token at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            name = Encoding.ASCII.GetString(text, startIndex, index - startIndex);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            if (text[index] == (byte)'*')
            {
                // the parameter is either encoded or it has a part id
                index++;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }

                int identifier;
                if (ParseUtils.TryParseInt32(text, ref index, endIndex, out identifier))
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] == (byte)'*')
                    {
                        encoded = true;
                        index++;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }

                        if (index >= endIndex)
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                            }

                            return(false);
                        }
                    }

                    id = identifier;
                }
                else
                {
                    encoded = true;
                }
            }

            if (text[index] != (byte)'=')
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            valueIndex = index;
            value      = text;

            if (text[index] == (byte)'"')
            {
                ParseUtils.SkipQuoted(text, ref index, endIndex, throwOnError);
                valueLength = index - valueIndex;
            }
            else if (options.ParameterComplianceMode == RfcComplianceMode.Strict)
            {
                ParseUtils.SkipToken(text, ref index, endIndex);
                valueLength = index - valueIndex;
            }
            else
            {
                // Note: Google Docs, for example, does not always quote name/filename parameters
                // with spaces in the name. See https://github.com/jstedfast/MimeKit/issues/106
                // for details.
                while (index < endIndex && text[index] != (byte)';' && text[index] != (byte)'\r' && text[index] != (byte)'\n')
                {
                    index++;
                }

                valueLength = index - valueIndex;

                if (index < endIndex && text[index] != (byte)';')
                {
                    // Note: https://github.com/jstedfast/MimeKit/issues/159 adds to this suckage
                    // by having a multi-line unquoted value with spaces... don't you just love
                    // mail software written by people who have never heard of standards?
                    using (var memory = new MemoryStream()) {
                        memory.Write(text, valueIndex, valueLength);

                        do
                        {
                            while (index < endIndex && (text[index] == (byte)'\r' || text[index] == (byte)'\n'))
                            {
                                index++;
                            }

                            valueIndex = index;

                            while (index < endIndex && text[index] != (byte)';' && text[index] != (byte)'\r' && text[index] != (byte)'\n')
                            {
                                index++;
                            }

                            memory.Write(text, valueIndex, index - valueIndex);
                        } while (index < endIndex && text[index] != ';');

                        value       = memory.ToArray();
                        valueLength = value.Length;
                        valueIndex  = 0;
                    }
                }

                // Trim trailing white space characters to work around issues such as the
                // one described in https://github.com/jstedfast/MimeKit/issues/278
                while (valueLength > valueIndex && value[valueLength - 1].IsWhitespace())
                {
                    valueLength--;
                }
            }

            pair = new NameValuePair {
                ValueLength = valueLength,
                ValueStart  = valueIndex,
                Encoded     = encoded,
                Value       = value,
                Name        = name,
                Id          = id
            };

            return(true);
        }
Example #41
0
 // ReSharper disable once UnusedMember.Local
 private static bool IsName(NameValuePair pair, string name)
 {
     return(pair.Name.Equals(name));
 }
Example #42
0
        //public static int Set_ComboBox(ComboBox cbo, Int64 setId)
        //{
        //    int setcboIndex = 0;
        //    int rtnValue = 0;
        //    int iLast = cbo.Items.Count;
        //    try
        //    {
        //        //for (int Ii = 0; Ii < iLast; Ii++)
        //        //{
        //        //    cbo.SelectedIndex = Ii;
        //        //    if (Convert.ToInt32(cbo.SelectedValue.ToString()) == setId)
        //        //    {
        //        //        MessageBox.Show("Text = " + cbo.Text + " Value: " + cbo.SelectedValue.ToString() + " Index: " + cbo.SelectedIndex.ToString());
        //        //        setcboIndex = Ii;
        //        //        break;
        //        //    }
        //        //}
        //        //return setcboIndex;
        //        //StringBuilder sb = new StringBuilder();
        //        if (cbo.Items.Count > 0)
        //        {
        //            string abc1 = "";
        //            string key1 = "";
        //            string abc2 = "";

        //            foreach (object item in cbo.Items)
        //            {
        //                abc1 = item.GetType().ToString();
        //                if (abc1 == "System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]")
        //                {
        //                    //MessageBox.Show("keyvalue pair type:");

        //                    KeyValuePair<int, string> Keyv1 = (KeyValuePair<int, string>)item;
        //                    // key1 = Keyv1.Value.ToString();
        //                    key1 = Keyv1.Key.ToString();
        //                    if (Convert.ToInt32(key1) == setId)
        //                    {
        //                        setcboIndex = rtnValue;
        //                        break;
        //                    }
        //                }
        //                else if (abc1 == "System.Data.DataRowView")
        //                {
        //                    DataRowView row = (DataRowView)item;
        //                    //abc1 = row.Row[cbo.DisplayMember].ToString();
        //                    //MessageBox.Show("Text = " + cbo.Text + " Value: " + cbo.SelectedValue.ToString() + " Index: " + cbo.SelectedIndex.ToString());


        //                    abc2 = row.Row[cbo.ValueMember].ToString();
        //                    if (Convert.ToInt32(abc2) == setId)
        //                    {
        //                        setcboIndex = rtnValue;
        //                        break;
        //                    }
        //                }
        //                else
        //                {
        //                    MessageBox.Show("Unknown type");
        //                }
        //                rtnValue++;
        //            }
        //        }
        //        return setcboIndex;
        //    }
        //    catch (Exception exp)
        //    {
        //        MessageBox.Show("Exception: " + exp.Message,"Set Combo Box");
        //        return 0;
        //    }
        //}
        #region SetCombo Integer

        public static int Set_ComboBox(ComboBox cbo, Int64 setId)
        {
            int setcboIndex = 0;
            int rtnValue    = 0;
            int iLast       = cbo.Items.Count;

            try
            {
                //for (int Ii = 0; Ii < iLast; Ii++)
                //{
                //    cbo.SelectedIndex = Ii;
                //    if (Convert.ToInt32(cbo.SelectedValue.ToString()) == setId)
                //    {
                //        MessageBox.Show("Text = " + cbo.Text + " Value: " + cbo.SelectedValue.ToString() + " Index: " + cbo.SelectedIndex.ToString());
                //        setcboIndex = Ii;
                //        break;
                //    }
                //}
                //return setcboIndex;
                //StringBuilder sb = new StringBuilder();
                if (cbo.Items.Count > 0)
                {
                    string lCboTypeKeyValue    = "";
                    string lCbokey             = "";
                    string lCboTypeDataRowView = "";

                    foreach (object item in cbo.Items)
                    {
                        lCboTypeKeyValue = item.GetType().ToString();
                        if (lCboTypeKeyValue == "System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]")
                        {
                            //MessageBox.Show("keyvalue pair type:");

                            KeyValuePair <int, string> Keyv1 = (KeyValuePair <int, string>)item;
                            // key1 = Keyv1.Value.ToString();
                            lCbokey = Keyv1.Key.ToString();
                            if (Convert.ToInt32(lCbokey) == setId)
                            {
                                setcboIndex = rtnValue;
                                break;
                            }
                        }
                        else if (lCboTypeKeyValue == "GUI_Task.Class.NameValuePair")
                        {
                            NameValuePair Keyv1 = (NameValuePair)item;
                            lCbokey = Keyv1.ValueInt.ToString();

                            if (Convert.ToInt32(lCbokey) == setId)
                            {
                                setcboIndex = rtnValue;
                                break;
                            }
                        }
                        else if (lCboTypeKeyValue == "System.Data.DataRowView")
                        {
                            DataRowView row = (DataRowView)item;
                            //abc1 = row.Row[cbo.DisplayMember].ToString();
                            //MessageBox.Show("Text = " + cbo.Text + " Value: " + cbo.SelectedValue.ToString() + " Index: " + cbo.SelectedIndex.ToString());


                            lCboTypeDataRowView = row.Row[cbo.ValueMember].ToString();
                            if (Convert.ToInt32(lCboTypeDataRowView) == setId)
                            {
                                setcboIndex = rtnValue;
                                break;
                            }
                        }
                        else
                        {
                            MessageBox.Show("Combo Setting, Unknown type");
                        }
                        rtnValue++;
                    }
                }
                return(setcboIndex);
            }
            catch (Exception exp)
            {
                MessageBox.Show("Exception: " + exp.Message, "Set Combo Box");
                return(0);
            }
        }
        public void ForceBuild()
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            Mock.Get(serverClient).SetupSet(_serverClient => _serverClient.SessionToken = It.IsAny <string>());
            Mock.Get(serverClient).Setup(_serverClient => _serverClient.ForceBuild("yyy", It.Is <List <NameValuePair> >(_parameters => _parameters.SequenceEqual(NameValuePair.FromDictionary(parameters)))));

            manager.ForceBuild(null, parameters, null);
            mocks.VerifyAll();
        }
Example #44
0
        private bool ParseArgsInternal(IEnumerable <string> args)
        {
            foreach (string s in args)
            {
                var pair = new NameValuePair(s);
                if (string.IsNullOrEmpty(pair.Name))
                {
                    continue;
                }

                if (IsNameOnly(pair, ARG_UI))
                {
                    IsUi = true;
                }
                else if (IsNameValue(pair, ARG_ACG))
                {
                    if (pair.Value.ToLower() == AcgState.hide.ToString())
                    {
                        Acg = AcgState.hide;
                    }
                    else if (pair.Value.ToLower() == AcgState.none.ToString())
                    {
                        Acg = AcgState.none;
                    }
                    else if (pair.Value.ToLower() == AcgState.show.ToString())
                    {
                        Acg = AcgState.show;
                    }
                    else
                    {
                        Console.Error.WriteLine("Error: The value {0} for --{1} is not valid", pair.Value, pair.Name);
                    }
                }
                else if (IsNameValue(pair, ARG_THREADS))
                {
                    int threads;
                    if (!int.TryParse(pair.Value, out threads))
                    {
                        Console.Error.WriteLine("Error: The value {0} for --{1} must be an integer", pair.Value, pair.Name); // Not L10N
                        return(false);
                    }
                    Threads = threads;
                }
                else if (IsNameValue(pair, ARG_PROCESSES)) // Not L10N
                {
                    int processes;
                    if (!int.TryParse(pair.Value, out processes))
                    {
                        Console.Error.WriteLine("Error: The value {0} for --{1} must be an integer", pair.Value, pair.Name); // Not L10N
                        return(false);
                    }
                    Processes = processes;
                }
                else if (IsNameValue(pair, ARG_SKYLINE_PATH))
                {
                    SkylinePath = pair.Value;
                }
                else if (IsNameValue(pair, ARG_FILE_PATH))
                {
                    FilePath = pair.Value;
                }
                else if (IsNameValue(pair, ARG_DATA_DIR))
                {
                    DataDir = pair.Value;
                }
                else if (IsNameValue(pair, ARG_DATA_FILTER))
                {
                    DataFilter = pair.Value;
                }
                else
                {
                    Console.Error.WriteLine("Error: Unexpected argument --{0}", pair.Name); // Not L10N
                    return(false);
                }
            }

            if (string.IsNullOrEmpty(SkylinePath))
            {
                SkylinePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SkylineDailyRunner.exe");
            }

            return(true);
        }
        ////=======//=======//=======//=======//=========
        public static void FillComboWithEnum( ComboBox pCbo, string pEnumName, bool pSort )
        {
            try
              {
            List<NameValuePair> ControlGroupList = new List<NameValuePair>();
            switch (pEnumName)
            {
              case "GLVoucher":
            {
              var values = Enum.GetValues(typeof(GLVoucher))
             .Cast<GLVoucher>()
             .Select(d => Tuple.Create((( int )d).ToString(), d.ToString()))
             .ToList();  // it is ok but it is comma seperated list.
              //
              foreach (var item in values)
              {
                string lName = item.Item2.ToString().Replace('_', ' '); ;
                string lValue = item.Item1.ToString();
                NameValuePair NvP = new NameValuePair(lName, Convert.ToInt32(lValue));
                ControlGroupList.Add(NvP);
              }
              break;
            }
              case "ControlAc":
            {
              var values = Enum.GetValues(typeof(ControlAc))
             .Cast<ControlAc>()
             .Select(d => Tuple.Create((( int )d).ToString(), d.ToString()))
             .ToList();  // it is ok but it is comma seperated list.
              //
              //values.Dump();
              foreach (var item in values)
              {
                string lName = item.Item2.ToString().Replace('_', ' '); ;
                string lValue = item.Item1.ToString();
                NameValuePair NvP = new NameValuePair(lName, Convert.ToInt32(lValue));
                ControlGroupList.Add(NvP);
              }
              break;
            }
              case "TranPriority":
            {
              var val = Enum.GetValues(typeof(TranPriorityId));
              var values = Enum.GetValues(typeof(TranPriorityId))
             .Cast<TranPriorityId>()
             .Select(d => Tuple.Create((( int )d).ToString(), d.ToString()))
             .ToList();  // it is ok but it is comma seperated list.
              //
              //values.Dump();
              foreach (var item in values)
              {
                string lName = item.Item2.ToString().Replace('_', ' '); ;
                string lValue = item.Item1.ToString();
                NameValuePair NvP = new NameValuePair(lName, Convert.ToInt32(lValue));
                ControlGroupList.Add(NvP);
              }
              break;
            }

              default:
            {

              break;
            }
            }
            if (pSort)
            {
              ControlGroupList.Sort(NameValuePair.NameComparison);
            }
            //
            pCbo.DataSource = ControlGroupList;
            pCbo.DisplayMember = "NameStr";
            pCbo.ValueMember = "ValueInt";
              }
              catch (Exception ex)
              {
            MessageBox.Show("Exception, Enumerator ComboBox: " + ex.Message);
              }
        }
        /// <summary>
        /// Reads a value.
        /// </summary>
        /// <param name="valueElement"></param>
        /// <returns></returns>
        private NameValuePair ReadValue(XmlElement valueElement)
        {
            // Make sure there are no child elements
            var fileSubNodes = valueElement.SelectNodes("*");
            if (fileSubNodes != null && fileSubNodes.Count > 0)
            {
                throw new NetReflectorException(string.Concat("value elements cannot contain any sub-items.", Environment.NewLine, "XML: ", valueElement.OuterXml));
            }

            // Read the value
            var newValue = new NameValuePair();
            newValue.Value = valueElement.InnerText;

            // Read the name
            newValue.Name = valueElement.GetAttribute("name"); ;
            return newValue;
        }
Example #47
0
        private GeneralEntityDataset getEntityDataset(List <NameValuePair> data, DateTime dateEdited)
        {
            KindKey       kindKey      = null;
            NameValuePair creationDate = null;
            var           metaData     = new KindMetaData()
            {
                chksum = 1,
                devid  = AppInstance.Instance.Configuration.Serial,
                facidx = 0
            };

            //we check if we are in an edit context and read values from there
            if (isInEditMode())
            {
                var jsonOldRecord   = this.Intent.GetStringExtra(Constants.BUNDLE_DATATOEDIT);
                var oldRecordEntity = JsonConvert
                                      .DeserializeObject <GeneralEntityDataset>(jsonOldRecord);
                kindKey      = new KindKey(oldRecordEntity.Id.Value);
                creationDate = oldRecordEntity.GetValue(Constants.SYS_FIELD_DATECREATED);
                if (!string.IsNullOrWhiteSpace(oldRecordEntity.KindMetaData))
                {
                    var oldMetaData = new KindMetaData().fromJson(new KindItem(oldRecordEntity.KindMetaData));
                    metaData.chksum = oldMetaData.chksum + 1;
                }
            }
            else
            {
                kindKey = new KindKey(AppInstance.Instance
                                      .LocalEntityStoreInstance.InstanceLocalDb.newId());
            }

            KindKey entityId = null;

            if (IsRegistrationEndPage())
            {
                //assign a key
                entityId = new KindKey(kindKey.Value);
                //we get the device size
                var moduleClientSummaries = getModuleClientSummaries(data);
                data.AddRange(moduleClientSummaries);
            }
            else
            {
                //also update client details but only if they have changes
                entityId = new KindKey(CurrentClient.EntityId.Value);
            }

            if (creationDate == null)
            {
                data.Add(new NameValuePair()
                {
                    Name  = Constants.SYS_FIELD_DATECREATED,
                    Value = dateEdited.ToString(System.Globalization.CultureInfo.InvariantCulture)
                });
            }

            var editDate = data
                           .Where(t => t.Name.Contains(Constants.SYS_FIELD_DATEEDITED))
                           .FirstOrDefault();

            if (editDate == null)
            {
                data.Add(new NameValuePair()
                {
                    Name  = Constants.SYS_FIELD_DATEEDITED,
                    Value = dateEdited.ToString(System.Globalization.CultureInfo.InvariantCulture)
                });
            }
            data.Add(new NameValuePair()
            {
                Name  = Constants.FIELD_ID,
                Value = kindKey.Value
            });
            data.Add(new NameValuePair()
            {
                Name  = Constants.FIELD_ENTITYID,
                Value = entityId.Value
            });

            var saveable = new GeneralEntityDataset()
            {
                Id           = kindKey,
                EntityId     = entityId,
                FormName     = _kindName.Value,
                FieldValues  = data,
                KindMetaData = metaData.getJson()
            };

            return(saveable);
        }
Example #48
0
        public void GetAndSetSensitiveSiteConfigs()
        {
            RunWebsiteTestScenario(
                (siteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
            {
                #region Get/Set Application settings

                const string settingName = "Application Setting1", settingValue = "Setting Value 1";
                var appSetting           = new NameValuePair()
                {
                    Name = settingName, Value = settingValue
                };
                var appSettingsResponse = webSitesClient.WebSites.UpdateAppSettings(
                    resourceGroupName,
                    siteName,
                    null,
                    new WebSiteNameValueParameters(new List <NameValuePair>()
                {
                    appSetting
                }, locationName));

                Assert.NotNull(appSettingsResponse.Resource);
                Assert.NotNull(appSettingsResponse.Resource.Properties);
                var appSettings = appSettingsResponse.Resource.Properties;
                Assert.Single(appSettings.Where(a => a.Name == settingName && a.Value == settingValue));

                appSettingsResponse = webSitesClient.WebSites.GetAppSettings(resourceGroupName,
                                                                             siteName, null);

                Assert.NotNull(appSettingsResponse.Resource);
                Assert.NotNull(appSettingsResponse.Resource.Properties);
                appSettings = appSettingsResponse.Resource.Properties;
                Assert.Single(appSettings.Where(a => a.Name == settingName && a.Value == settingValue));

                #endregion Get/Set Application settings

                #region Get/Set Metadata

                const string metadataName = "Metadata 1", metadataValue = "Metadata Value 1";
                var metadata = new NameValuePair()
                {
                    Name = metadataName, Value = metadataValue
                };
                var metadataResponse = webSitesClient.WebSites.UpdateMetadata(
                    resourceGroupName,
                    siteName,
                    null,
                    new WebSiteNameValueParameters()
                {
                    Location   = locationName,
                    Properties = new List <NameValuePair> {
                        metadata
                    }
                });

                Assert.NotNull(metadataResponse.Resource);
                Assert.NotNull(metadataResponse.Resource.Properties);
                var metadatas = metadataResponse.Resource.Properties;
                Assert.Single(metadatas.Where(m => m.Name == metadataName && m.Value == metadataValue));

                metadataResponse = webSitesClient.WebSites.GetMetadata(resourceGroupName,
                                                                       siteName, null);

                Assert.NotNull(metadataResponse.Resource);
                Assert.NotNull(metadataResponse.Resource.Properties);
                metadatas = metadataResponse.Resource.Properties;
                Assert.Single(metadatas.Where(m => m.Name == metadataName && m.Value == metadataValue));

                #endregion Get/Set Metadata

                #region Get/Set Connection strings

                const string connectionString = "ConnectionString 1", connectionStringValue = "ConnectionString Value 1";
                var connectionStringInfo      = new ConnectionStringInfo()
                {
                    ConnectionString = connectionString,
                    Name             = connectionStringValue,
                    Type             = DatabaseServerType.MySql
                };

                var connectionStringResponse = webSitesClient.WebSites.UpdateConnectionStrings(
                    resourceGroupName,
                    siteName,
                    null,
                    new WebSiteUpdateConnectionStringsParameters()
                {
                    Location   = locationName,
                    Properties = new List <ConnectionStringInfo>()
                    {
                        { connectionStringInfo }
                    }
                });

                Assert.NotNull(connectionStringResponse);
                Assert.NotNull(connectionStringResponse.Resource.Properties);
                var connectionStrings = connectionStringResponse.Resource.Properties;
                Assert.Single(connectionStrings.Where(c => c.Name == connectionStringInfo.Name && c.ConnectionString == connectionStringInfo.ConnectionString && c.Type == connectionStringInfo.Type));

                connectionStringResponse = webSitesClient.WebSites.GetConnectionStrings(resourceGroupName,
                                                                                        siteName, null);

                Assert.NotNull(connectionStringResponse);
                Assert.NotNull(connectionStringResponse.Resource.Properties);
                connectionStrings = connectionStringResponse.Resource.Properties;
                Assert.Single(connectionStrings.Where(c => c.Name == connectionStringInfo.Name && c.ConnectionString == connectionStringInfo.ConnectionString && c.Type == connectionStringInfo.Type));

                #endregion Get/Set Connection strings

                #region Get Publishing credentials

                var credentialsResponse = webSitesClient.WebSites.GetPublishingCredentials(resourceGroupName, siteName, null);

                Assert.NotNull(credentialsResponse.Resource);
                Assert.NotNull(credentialsResponse.Resource.Properties);
                Assert.Equal("$" + siteName, credentialsResponse.Resource.Properties.PublishingUserName);
                Assert.NotNull(credentialsResponse.Resource.Properties.PublishingPassword);

                #endregion Get Publishing credentials

                #region Get Publishing profile XML

                var publishingProfileResponse = webSitesClient.WebSites.GetPublishProfile(resourceGroupName, siteName, null);

                Assert.NotEmpty(publishingProfileResponse.PublishProfiles);

                #endregion Get Publishing profile XML

                webSitesClient.WebSites.Delete(resourceGroupName, siteName, null, new WebSiteDeleteParameters()
                {
                    DeleteAllSlots = true,
                    DeleteMetrics  = true
                });

                webSitesClient.WebHostingPlans.Delete(resourceGroupName, whpName);
            });
        }
Example #49
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void Add( string name, object value )
        {
            string sv = GetString( value );
            NameValuePair nvp = new NameValuePair( name, sv );

            _list.Add( nvp );

            int length = nvp.Name.Length + nvp.NameCnCharCount;
            if ( length > _maxNameLength )
                _maxNameLength = length;
        }
Example #50
0
        public PaymentHandler(List <PaypalItem> items, int uid)
        {
            if (apiContext == null)
            {
                GetApiContext();
            }
            userId = uid;

            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            var guid = Convert.ToString((new Random()).Next(100000));

            string DomainName = "http://localhost:20629";
            //string DomainName = "https://localhost:44394";
            var redirUrls = new RedirectUrls()
            {
                cancel_url = DomainName + "/Cancel/",
                return_url = DomainName + "/Wallet/PaymentSucess/"
            };

            // Add Items to List
            ItemList itemList = new ItemList();

            itemList.items = new List <Item>();

            double subtotal  = 0;
            double taxamount = 0;

            foreach (PaypalItem item in items)
            {
                List <NameValuePair> nl      = new List <NameValuePair>();
                NameValuePair        sizeadd = new NameValuePair();
                sizeadd.name  = "Size";
                sizeadd.value = item.size;
                nl.Add(sizeadd);

                PayPal.Api.Item tmp = new Item
                {
                    currency = item.currency,
                    price    = item.price.ToString(),
                    quantity = "1",
                    sku      = item.sku,
                };

                subtotal += (item.price * 1);
                itemList.items.Add(tmp);
            }

            taxamount = 0;

            var details = new Details()
            {
                tax      = taxamount.ToString(),
                shipping = "0",
                subtotal = subtotal.ToString()
            };

            double total = taxamount + _fixedShipping + subtotal;

            var amount = new Amount()
            {
                currency = _Currency,
                total    = total.ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                details  = details
            };

            var    transactionList = new List <Transaction>();
            Random rand            = new Random(DateTime.Now.Second);
            String invoice         = "INV-" + System.DateTime.Now.Ticks.ToString();

            transactionList.Add(new Transaction()
            {
                description    = "Transaction description.",
                invoice_number = invoice,
                amount         = amount,
                item_list      = itemList
            });

            PayPal.Api.Payment payment = new PayPal.Api.Payment()
            {
                intent        = "sale",
                payer         = payer,
                redirect_urls = redirUrls,
                transactions  = transactionList
            };

            var createdPayment = payment.Create(apiContext);

            //    PopulateOrder(invoice , items, amount);

            var links = createdPayment.links.GetEnumerator();

            while (links.MoveNext())
            {
                var link = links.Current;
                if (link.rel.ToLower().Trim().Equals("approval_url"))
                {
                    HttpContext.Current.Response.Redirect(link.href);
                }
            }
        }
 private static KeyValuePair<string, string> ToKeyValuePair(NameValuePair nvp)
 {
     return new KeyValuePair<string, string>(nvp.Name, nvp.Value);
 }
Example #52
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
        /// </summary>
        public ServerConfiguration()
        {
            Migrations = new string[] { };

            ImageSavingConvention               = ImageSavingConvention.Compatible;
            PublicPort                          = 8096;
            PublicHttpsPort                     = 8920;
            HttpServerPortNumber                = 8096;
            HttpsPortNumber                     = 8920;
            EnableHttps                         = false;
            EnableDashboardResponseCaching      = true;
            EnableDashboardResourceMinification = true;
            EnableAnonymousUsageReporting       = true;

            EnableAutomaticRestart = true;
            DenyIFrameEmbedding    = true;

            EnableUPnP = true;

            SharingExpirationDays = 30;
            MinResumePct          = 5;
            MaxResumePct          = 90;

            // 5 minutes
            MinResumeDurationSeconds = 300;

            EnableLibraryMonitor = AutoOnOff.Auto;
            LibraryMonitorDelay  = 60;

            EnableInternetProviders = true;
            FindInternetTrailers    = true;

            PathSubstitutions = new PathSubstitution[] { };
            ContentTypes      = new NameValuePair[] { };

            PreferredMetadataLanguage = "en";
            MetadataCountryCode       = "US";

            SortReplaceCharacters = new[] { ".", "+", "%" };
            SortRemoveCharacters  = new[] { ",", "&", "-", "{", "}", "'" };
            SortRemoveWords       = new[] { "the", "a", "an" };

            SeasonZeroDisplayName = "Specials";

            UICulture = "en-us";

            PeopleMetadataOptions = new PeopleMetadataOptions();

            MetadataOptions = new[]
            {
                new MetadataOptions(1, 1280)
                {
                    ItemType = "Book"
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "Movie",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicVideo",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "Series",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicAlbum",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 0,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicArtist",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default
                        // They do look great, but most artists won't have them, which means a banner view isn't really possible
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        // Don't download this by default
                        // Generally not used
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default
                        // Generally not used
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "BoxSet",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        }
                    }
                },

                new MetadataOptions(0, 1280)
                {
                    ItemType     = "Season",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 0,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Thumb
                        }
                    },
                    DisabledMetadataFetchers = new [] { "The Open Movie Database", "TheMovieDb" }
                },

                new MetadataOptions(0, 1280)
                {
                    ItemType     = "Episode",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 0,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        }
                    },
                    DisabledMetadataFetchers = new [] { "The Open Movie Database" },
                    DisabledImageFetchers    = new [] { "TheMovieDb" }
                }
            };
        }
Example #53
0
        static bool TryParseNameValuePair(byte[] text, ref int index, int endIndex, bool throwOnError, out NameValuePair pair)
        {
            int    valueIndex, startIndex;
            bool   encoded = false;
            int?   id      = null;
            string name;

            pair = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            startIndex = index;
            if (!SkipParamName(text, ref index, endIndex))
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Invalid parameter name token at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            name = Encoding.ASCII.GetString(text, startIndex, index - startIndex);

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            if (text[index] == (byte)'*')
            {
                // the parameter is either encoded or it has a part id
                index++;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                {
                    return(false);
                }

                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }

                int value;
                if (ParseUtils.TryParseInt32(text, ref index, endIndex, out value))
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    if (index >= endIndex)
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                        }

                        return(false);
                    }

                    if (text[index] == (byte)'*')
                    {
                        encoded = true;
                        index++;

                        if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                        {
                            return(false);
                        }

                        if (index >= endIndex)
                        {
                            if (throwOnError)
                            {
                                throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                            }

                            return(false);
                        }
                    }

                    id = value;
                }
                else
                {
                    encoded = true;
                }
            }

            if (text[index] != (byte)'=')
            {
                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }
            }

            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
            {
                return(false);
            }

            if (index >= endIndex)
            {
                if (index >= endIndex)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete parameter at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }
            }

            valueIndex = index;

            if (text[index] == (byte)'"')
            {
                ParseUtils.SkipQuoted(text, ref index, endIndex, throwOnError);
            }
            else
            {
                ParseUtils.SkipToken(text, ref index, endIndex);
            }

            pair = new NameValuePair {
                ValueLength = index - valueIndex,
                ValueStart  = valueIndex,
                Encoded     = encoded,
                Name        = name,
                Id          = id
            };

            return(true);
        }
Example #54
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
        /// </summary>
        public ServerConfiguration()
        {
            LocalNetworkAddresses       = new string[] { };
            CodecsUsed                  = new string[] { };
            ImageExtractionTimeoutMs    = 0;
            EnableLocalizedGuids        = true;
            PathSubstitutions           = new PathSubstitution[] { };
            EnableSimpleArtistDetection = true;

            DisplaySpecialsWithinSeasons       = true;
            EnableExternalContentInSuggestions = true;

            ImageSavingConvention          = ImageSavingConvention.Compatible;
            PublicPort                     = DefaultHttpPort;
            PublicHttpsPort                = DefaultHttpsPort;
            HttpServerPortNumber           = DefaultHttpPort;
            HttpsPortNumber                = DefaultHttpsPort;
            EnableHttps                    = false;
            EnableDashboardResponseCaching = true;
            EnableAnonymousUsageReporting  = true;
            EnableCaseSensitiveItemIds     = true;

            EnableAutomaticRestart = true;

            EnableUPnP            = true;
            SharingExpirationDays = 30;
            MinResumePct          = 5;
            MaxResumePct          = 90;

            // 5 minutes
            MinResumeDurationSeconds = 300;

            LibraryMonitorDelay = 60;

            ContentTypes = new NameValuePair[] { };

            PreferredMetadataLanguage = "en";
            MetadataCountryCode       = "US";

            SortReplaceCharacters = new[] { ".", "+", "%" };
            SortRemoveCharacters  = new[] { ",", "&", "-", "{", "}", "'" };
            SortRemoveWords       = new[] { "the", "a", "an" };

            SeasonZeroDisplayName = "Specials";

            UICulture = "en-us";

            MetadataOptions = new[]
            {
                new MetadataOptions(1, 1280)
                {
                    ItemType = "Book"
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "Movie",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicVideo",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    },

                    DisabledImageFetchers = new [] { "FanArt" }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "Series",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicAlbum",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 0,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        }
                    },
                    DisabledMetadataFetchers = new [] { "TheAudioDB" }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicArtist",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default
                        // They do look great, but most artists won't have them, which means a banner view isn't really possible
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        // Don't download this by default
                        // Generally not used
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    },
                    DisabledMetadataFetchers = new [] { "TheAudioDB" }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "BoxSet",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        }
                    }
                },

                new MetadataOptions(0, 1280)
                {
                    ItemType     = "Season",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 0,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Thumb
                        }
                    },
                    DisabledMetadataFetchers = new [] { "TheMovieDb" },
                    DisabledImageFetchers    = new [] { "FanArt" }
                },

                new MetadataOptions(0, 1280)
                {
                    ItemType     = "Episode",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 0,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        }
                    },
                    DisabledMetadataFetchers = new [] { "The Open Movie Database", "TheMovieDb" },
                    DisabledImageFetchers    = new [] { "The Open Movie Database", "TheMovieDb" }
                }
            };
        }
Example #55
0
        public static Transaction getTransaction(string transactionId)
        {
            Transaction trans = new Transaction();

            trans.merchantTransactionId = transactionId;
            trans.timestamp             = DateTime.Now;
            trans.amount   = new Decimal(10.99);
            trans.currency = "USD";

            TransactionStatusType status = TransactionStatusType.Failed;

            trans.status = status;

            string divisionNumber = "5498";

            trans.divisionNumber = divisionNumber;

            NameValuePair nvp = new NameValuePair();

            nvp.name            = "litle:reportGroup";
            nvp.value           = "Test";
            trans.nameValues    = new NameValuePair[1];
            trans.nameValues[0] = nvp;

            string subscriptionId = transactionId;

            trans.subscriptionId = subscriptionId;

            string customerId = transactionId;

            trans.customerId = customerId;

            string paymentMethodId = transactionId;

            trans.paymentMethodId = paymentMethodId;

            TransactionStatusType resultType;
            string why;

            // split requested results into Captured & Failed: Hard & Soft Fails
            char c     = transactionId[transactionId.Length - 1];
            int  index = c - 0x30;

            switch (index % 2)
            {
            case 0:
                // To use a Card that will be Captured:
                resultType = TransactionStatusType.Captured;
                why        = null;
                break;

            default:
                // To use a Card that will be Failed:
                resultType = TransactionStatusType.Failed;
                switch (index % 3)
                {
                case 0:
                    // Soft Fail:
                    why = whyFail_Soft;
                    break;

                default:
                    // Hard Fail:
                    why = whyFail_Hard;
                    break;
                }
                break;
            }
            string creditCardAccount = getCreditCardAccount(resultType, why);

            trans.creditCardAccount = creditCardAccount;

            string creditCardExpirationDate = "202208";

            trans.creditCardExpirationDate = creditCardExpirationDate;

            string authCode = "302";

            trans.authCode = authCode;


            // Additional data members:
            string affiliateId = "Affiliate" + divisionNumber;

            trans.affiliateId = affiliateId;
            string affiliateSubId = "SubAffiliate" + divisionNumber;

            trans.affiliateSubId = affiliateSubId;
            string billingAddressCity = "Any City";

            trans.billingAddressCity = billingAddressCity;
            string billingAddressCountry = "US";

            trans.billingAddressCountry = billingAddressCountry;
            string billingAddressCounty = "Any County";

            trans.billingAddressCounty = billingAddressCounty;
            string billingAddressDistrict = "Any State (i.e. District)";

            trans.billingAddressDistrict = billingAddressDistrict;
            string billingAddressLine1 = "123 Main (Address Line 1)";

            trans.billingAddressLine1 = billingAddressLine1;
            string billingAddressLine2 = "Suite 5 (Address Line 2)";

            trans.billingAddressLine2 = billingAddressLine2;
            string billingAddressLine3 = "Internet Widgets Co. Ltd. (Address Line 3)";

            trans.billingAddressLine3 = billingAddressLine3;
            string billingAddressPostalCode = "94002";

            trans.billingAddressPostalCode = billingAddressPostalCode;
            DateTime startDate = DateTime.Now.AddYears(-1);

            trans.subscriptionStartDate = startDate;

            return(trans);
        }
Example #56
0
        private async Task <string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
        {
            var username = info.Username;

            // Reset the token if there's no username
            if (string.IsNullOrWhiteSpace(username))
            {
                return(null);
            }

            var password = info.Password;

            if (string.IsNullOrWhiteSpace(password))
            {
                return(null);
            }

            // Avoid hammering SD
            if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
            {
                return(null);
            }

            NameValuePair savedToken = null;

            if (!_tokens.TryGetValue(username, out savedToken))
            {
                savedToken = new NameValuePair();
                _tokens.TryAdd(username, savedToken);
            }

            if (!string.IsNullOrWhiteSpace(savedToken.Name) && !string.IsNullOrWhiteSpace(savedToken.Value))
            {
                long ticks;
                if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks))
                {
                    // If it's under 24 hours old we can still use it
                    if ((DateTime.UtcNow.Ticks - ticks) < TimeSpan.FromHours(20).Ticks)
                    {
                        return(savedToken.Name);
                    }
                }
            }

            await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);

                savedToken.Name  = result;
                savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
                return(result);
            }
            catch (HttpException ex)
            {
                if (ex.StatusCode.HasValue)
                {
                    if ((int)ex.StatusCode.Value == 400)
                    {
                        _tokens.Clear();
                        _lastErrorResponse = DateTime.UtcNow;
                    }
                }
                throw;
            }
            finally
            {
                _tokenSemaphore.Release();
            }
        }
 private void _AppendElementAttributes(XmlContextFile file, NameValuePair[] attributes)
 {
     if (attributes != null)
     {
         foreach (NameValuePair nvp in attributes)
         {
             file.WriteStartAttribute(nvp.Name);
             file.WriteValue(nvp.Value);
             file.WriteEndAttribute();
         }
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerConfiguration" /> class.
        /// </summary>
        public ServerConfiguration()
            : base()
        {
            ImageSavingConvention               = ImageSavingConvention.Compatible;
            PublicPort                          = 8096;
            PublicHttpsPort                     = 8920;
            HttpServerPortNumber                = 8096;
            HttpsPortNumber                     = 8920;
            EnableHttps                         = false;
            EnableDashboardResponseCaching      = true;
            EnableDashboardResourceMinification = true;

            EnableAutomaticRestart = true;

            EnableUPnP = true;

            MinResumePct = 5;
            MaxResumePct = 90;

            // 5 minutes
            MinResumeDurationSeconds = 300;

            RealtimeMonitorDelay = 30;

            EnableInternetProviders = true;
            FindInternetTrailers    = true;

            PathSubstitutions = new PathSubstitution[] { };
            ContentTypes      = new NameValuePair[] { };

            PreferredMetadataLanguage = "en";
            MetadataCountryCode       = "US";

            SortReplaceCharacters = new[] { ".", "+", "%" };
            SortRemoveCharacters  = new[] { ",", "&", "-", "{", "}", "'" };
            SortRemoveWords       = new[] { "the", "a", "an" };

            SeasonZeroDisplayName = "Specials";

            EnableRealtimeMonitor = true;

            UICulture = "en-us";

            PeopleMetadataOptions = new PeopleMetadataOptions();

            InsecureApps8 = new[]
            {
                "Chromecast",
                "iOS",
                "Unknown app",
                "MediaPortal",
                "Media Portal",
                "iPad",
                "iPhone",
                "Roku",
                "Windows Phone"
            };

            MetadataOptions = new[]
            {
                new MetadataOptions(1, 1280)
                {
                    ItemType = "Book"
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "Movie",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 3,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "Series",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 2,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Primary
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Banner
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Thumb
                        },

                        new ImageOption
                        {
                            Limit = 1,
                            Type  = ImageType.Logo
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicAlbum",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default as it's rarely used.
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Disc
                        }
                    }
                },

                new MetadataOptions(1, 1280)
                {
                    ItemType     = "MusicArtist",
                    ImageOptions = new []
                    {
                        new ImageOption
                        {
                            Limit    = 1,
                            MinWidth = 1280,
                            Type     = ImageType.Backdrop
                        },

                        // Don't download this by default
                        // They do look great, but most artists won't have them, which means a banner view isn't really possible
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Banner
                        },

                        // Don't download this by default
                        // Generally not used
                        new ImageOption
                        {
                            Limit = 0,
                            Type  = ImageType.Art
                        }
                    }
                },

                new MetadataOptions(0, 1280)
                {
                    ItemType = "Season"
                }
            };
        }
 /// <summary>
 /// Writes a value.
 /// </summary>
 /// <param name="writer"></param>
 /// <param name="elementName"></param>
 /// <param name="value"></param>
 private void WriteValue(XmlWriter writer, NameValuePair value, string elementName)
 {
     writer.WriteStartElement(elementName);
     if (!string.IsNullOrEmpty(value.Name)) writer.WriteAttributeString("name", value.Name);
     writer.WriteString(value.Value);
     writer.WriteEndElement();
 }
Example #60
0
        //private readonly static System.Text.RegularExpressions.Regex HttpHeaderRegex = new System.Text.RegularExpressions.Regex(@"HTTP_(([^ _])+(_?))+");
        public void SetOwinParametersFromFastCgiNvp(NameValuePair nameValuePair)
        {
            if (nameValuePair.Name == "SERVER_PROTOCOL")
            {
                Set("owin.RequestProtocol", nameValuePair.Value);
            }
            else if (nameValuePair.Name == "REQUEST_METHOD")
            {
                Set("owin.RequestMethod", nameValuePair.Value.ToUpperInvariant());
            }
            else if (nameValuePair.Name == "QUERY_STRING")
            {
                Set("owin.RequestQueryString", nameValuePair.Value);
            }
            else if (nameValuePair.Name == "HTTPS" && nameValuePair.Value == "on")
            {
                Set("owin.RequestScheme", "https");
            }
            else if (nameValuePair.Name == "DOCUMENT_URI")
            {
                Set("owin.RequestPathBase", string.Empty);
                Set("owin.RequestPath", nameValuePair.Value);
            }

            // HTTP_* parameters (these represent the http request header), such as:
            // HTTP_CONNECTION: keep-alive
            // HTTP_ACCEPT: text/html... etc.
            // HTTP_USER_AGENT: Mozilla/5.0
            // HTTP_ACCEPT_ENCODING
            // HTTP_ACCEPT_LANGUAGE
            // HTTP_COOKIE
            // many others..
            else if (nameValuePair.Name.StartsWith("HTTP_"))
            {
                //TODO: Avoid creating strings and create a decent algorithm for this conversion
                // Replace _ by - and pascal case single words to create pretty http headers
                string[] headerNameParts = nameValuePair.Name.Split('_');
                var      builder         = new System.Text.StringBuilder(nameValuePair.NameLength - 5);

                int i = 1;
                foreach (string part in headerNameParts.Skip(1))
                {
                    builder.Append(part[0]);
                    builder.Append(part.Substring(1, part.Length - 1).ToLowerInvariant());

                    if (i < headerNameParts.Length - 1)
                    {
                        builder.Append('-');
                    }

                    ++i;
                }

                SetRequestHeader(builder.ToString(), nameValuePair.Value);
            }

//			else if (nameValuePair.Name == "HTTP_HOST")
//				SetRequestHeader("Host", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_ACCEPT")
//				SetRequestHeader("Accept", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_ACCEPT_ENCODING")
//				SetRequestHeader("Accept-Encoding", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_ACCEPT_LANGUAGE")
//				SetRequestHeader("Accept-Language", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_CONNECTION")
//				SetRequestHeader("Connection", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_CONTENT_LENGTH")
//				SetRequestHeader("Content-Length", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_ORIGIN")
//				SetRequestHeader("Origin", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_X_REQUESTED_WITH")
//				SetRequestHeader("X-Requested-With", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_USER_AGENT")
//				SetRequestHeader("User-Agent", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_CONTENT_TYPE")
//				SetRequestHeader("Content-Type", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_REFERER")
//				SetRequestHeader("Referer", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_AUTHORIZATION")
//				SetRequestHeader("Authorization", nameValuePair.Value);
//			else if (nameValuePair.Name == "HTTP_COOKIE")
//				SetRequestHeader("Cookie", nameValuePair.Value);
        }