private static DataTable GetDatabases(IMyMetaTestContext criteria, IMyMetaPlugin plugin)
        {
            if (_databases == null)
            {
                _databases = plugin.Databases;
                if (criteria.DefaultDatabaseOnly)
                {
                    List<DataRow> rowsToDelete = new List<DataRow>();
                    string defaultDb = plugin.DefaultDatabase;
                    if (!string.IsNullOrEmpty(defaultDb))
                    {
                        defaultDb = defaultDb.Trim();
                        foreach (DataRow dbRow in _databases.Rows)
                        {
                            string dbname = dbRow["CATALOG_NAME"].ToString();
                            if (dbname != defaultDb) rowsToDelete.Add(dbRow);
                        }
                    }
                    if (rowsToDelete.Count != (_databases.Rows.Count - 1))
                    {
                        rowsToDelete.Clear();
                        for (int i = 1; i < _databases.Rows.Count; i++) rowsToDelete.Add(_databases.Rows[i]);
                    }

                    foreach (DataRow dbRow in rowsToDelete) _databases.Rows.Remove(dbRow);
                }
            }
            return _databases;
        }
        /// <summary>
        /// Füllt die Seite mit Inhalt auf, der bei der Navigation übergeben wird. Gespeicherte Zustände werden ebenfalls
        /// bereitgestellt, wenn eine Seite aus einer vorherigen Sitzung neu erstellt wird.
        /// </summary>
        /// <param name="navigationParameter">Der Parameterwert, der an
        /// <see cref="Frame.Navigate(Type, Object)"/> übergeben wurde, als diese Seite ursprünglich angefordert wurde.
        /// </param>
        /// <param name="pageState">Ein Wörterbuch des Zustands, der von dieser Seite während einer früheren Sitzung
        /// beibehalten wurde. Beim ersten Aufrufen einer Seite ist dieser Wert NULL.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // Zulassen, dass das anfänglich anzuzeigende Element vom gespeicherten Seitenzustand überschrieben wird
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"];
            }

            ChampionsViewModel championsViewModel = (ChampionsViewModel)App.Current.Resources["championsViewModel"];
            if (championsViewModel != null)
            {
                if (!championsViewModel.Loaded) await championsViewModel.LoadDataAsync();
                this.DefaultViewModel["Items"] = championsViewModel.Champions.OrderBy(c => c.displayName).ToList();
                Champion champion = championsViewModel.Champions.First<Champion>(c => c.id == (int)navigationParameter);
                this.flipView.SelectedItem = champion;

                List<ChampionItemDetailPageView> views = new List<ChampionItemDetailPageView>();
                ChampionItemDetailPageView lore = new ChampionItemDetailPageView("Lore");
                ChampionItemDetailPageView overview = new ChampionItemDetailPageView("Overview");
                ChampionItemDetailPageView tips = new ChampionItemDetailPageView("Tips");

                views.Add(overview);
                views.Add(lore);
                views.Add(tips);

                this.DefaultViewModel["Views"] = views;
            }
        }
Example #3
1
        public static string[] Split(string str, char[] separators, int maxComponents, StringSplitOptions options)
        {
            ContractUtils.RequiresNotNull(str, "str");
            #if SILVERLIGHT || WP75
            if (separators == null) return SplitOnWhiteSpace(str, maxComponents, options);

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = str.IndexOfAny(separators, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + 1;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
            #else
            return str.Split(separators, maxComponents, options);
            #endif
        }
        public override IList<ErrorInfo> Validate()
        {
            var errorList = new List<ErrorInfo>();

            if(Date == DateTime.MaxValue || Date == DateTime.MinValue)
                errorList.Add(new ErrorInfo("Date","EmployeeCost_InvalidDate"));

            if (Details == null || Details.Count == 0)
            {
                errorList.Add(new ErrorInfo("Details", "EmployeeCost_RequireDetails"));
            }
            else
            {
                if (Details.GroupBy(d => d.EmployeeId).Any(g => g.Count() > 1))
                    errorList.Add(new ErrorInfo("Details", "EmployeeCost_DuplicateEmployee"));

                for (var i = 0; i < Details.Count; i++)
                {
                    var detailErrors = Details[i].Validate();
                    if (detailErrors != null && detailErrors.Count > 0)
                    {
                        errorList.AddRange(detailErrors.Select(detailError => new ErrorInfo("Details[" + i + "]." + detailError.PropertyName, detailError.Message)));
                    }
                }
            }

            return errorList;
        }
Example #5
0
        /// <summary>
        /// Returns a list of visual branches which are around the given commit.
        /// </summary>
        /// <param name="commit"></param>
        /// <param name="repo"></param>
        /// <returns></returns>
        public static List<Branch> GetBranchesAroundCommit(Commit commit, ObservableCollection<Branch> branches)
        {
            List<Branch> list = new List<Branch>();

            // Loop through all branches and determine if they are around the specified commit.
            foreach (Branch branch in branches)
            {
                // Tip has to be found and in case multiple branches share the tree, get rid of the others -- messes up visual position counting.
                if (branch.Tip == null || list.Any(b => branch.Tip.Branches.Contains(b)) || list.Any(b => b.Tip.Branches.Contains(branch)))
                    continue;

                // The branch's tip must be newer/same than the commit.
                if (branch.Tip.Date >= commit.Date) // TODO: && first commit-ever must be older? We might not need to do that... ... ?
                {
                    list.Add(branch);
                }
                else
                {
                    // If there's a branch with a tip commit older than commit.Date, then it's around this commit if they don't share a single branch.
                    bool foundThisBranch = branch.Tip.Branches.Any(b => commit.Branches.Contains(b));

                    if (foundThisBranch == false)
                        list.Add(branch);
                }
            }

            return list;
        }
Example #6
0
        private void CreateModel()
        {
            int steps = (int)(1 / 0.05);
            double side = 100;

            // Generate the vertices
            Points = new List<Point3D>();
            for (int i = 0; i <= steps; i++)
            {
                double t = (double)i / steps;
                double x = side * Math.Cos(t * 2 * Math.PI);
                double y = side * Math.Sin(t * 2 * Math.PI);

                Points.Add(new Point3D(x, y, -side));
            }

            Points.Add(new Point3D(0, 0, -side));
            Points.Add(new Point3D(0, 0, side));

            // Generate the faces
            Faces = new List<int[]>();
            for (int i = 0; i < steps; i++)
            {
                int[] face = { i, i + 1, Points.Count-1};
                int[] sectorBottom = { i, i+1, Points.Count - 2};
                Faces.Add(face);
                Faces.Add(sectorBottom);
            }

            FacePoints = 3;
        }
Example #7
0
        public static string[] GetInfo(string filename)
        {
            List<string> fileinfo = new List<string>();

            TagLib.File tagFile = TagLib.File.Create(filename);
            string artiest = tagFile.Tag.FirstPerformer;
            string titel = tagFile.Tag.Title;

            if (artiest == null || artiest == "")
            {
                // Controleer of de artiest staat aangegeven bij de titel
                if (titel == null || titel == "")
                {
                    titel = System.IO.Path.GetFileNameWithoutExtension(filename);
                }

                if (titel != null && titel != "")
                {
                    // Controleer of de titel gesplits kan worden
                    string[] title = titel.Split(new char[] {'-'});
                    if (title.Length > 1)
                    {
                        artiest = title[0].Trim();
                        titel = title[1].Trim();
                    }
                }
            }

            fileinfo.Add(artiest);
            fileinfo.Add(titel);
            fileinfo.Add(tagFile.Properties.Duration.TotalSeconds.ToString());

            return fileinfo.ToArray();
        }
 public DiscountingBasisSwapEngine(Handle<YieldTermStructure> discountCurve1 , 
                              Handle<YieldTermStructure> discountCurve2) 
 {
    discountCurve_ = new List<Handle<YieldTermStructure>>();
    discountCurve_.Add(discountCurve1);
    discountCurve_.Add(discountCurve2);
 }
		/// <summary>
		/// The to attributes.
		/// </summary>
		/// <param name="label">
		/// The label.
		/// </param>
		/// <param name="icon">
		/// The icon.
		/// </param>
		/// <param name="id">
		/// The id.
		/// </param>
		/// <param name="cssClass">
		/// The CSS class.
		/// </param>
		/// <returns>
		/// The <see cref="HtmlAttribute"/>.
		/// </returns>
		private static HtmlAttribute[] ToAttributes(string label, string icon, string id, string cssClass)
		{
			var attributes = new List<HtmlAttribute>();

			if (!string.IsNullOrEmpty(id))
			{
				attributes.Add(new HtmlAttribute(HtmlTextWriterAttribute.Id, id));
			}

			if (!string.IsNullOrEmpty(cssClass))
			{
				attributes.Add(new HtmlAttribute(HtmlTextWriterAttribute.Class, cssClass));
			}

			if (!string.IsNullOrEmpty(label))
			{
				attributes.Add(new HtmlAttribute("label", label));
			}

			if (!string.IsNullOrEmpty(icon))
			{
				attributes.Add(new HtmlAttribute("icon", icon));
			}

			return attributes.ToArray();
		}
Example #10
0
        /// <summary>
        ///  ��ѯʵ��
        /// </summary>
        /// <param name="id">ModelId ���</param>
        /// <returns>ModelCategory</returns>
        public IList<ModelCategory> CategoryAll(out string resultMsg, Int32 ParentCateg = 0,string IsNav = null)
        {
            resultMsg = string.Empty;
            IList<ModelCategory> list = new List<ModelCategory>();
            try
            {
                //�洢��������
                string sql = "usp_category_select_all";

                //�������
                IList<DBParameter> parm = new List<DBParameter>();
                parm.Add(new DBParameter() { ParameterName = "@ParentCateg", ParameterValue = ParentCateg, ParameterInOut = BaseDict.ParmIn, ParameterType = DbType.Int32 });
                parm.Add(new DBParameter() { ParameterName = "@IsNav", ParameterValue = IsNav, ParameterInOut = BaseDict.ParmIn, ParameterType = DbType.String });

                //��ѯִ��
                using (IDataReader dr = DBHelper.ExecuteReader(sql, true, parm))
                {
                    list = GetModel(dr);
                }
            }
            catch (Exception ex)
            {
                resultMsg = string.Format("{0} {1}", BaseDict.ErrorPrefix, ex.ToString());
            }
            return list;
        }
        public static List<LimitData> BuildStaticUclLimit(ChartBase dataContext, bool calculatedCLs)
        {
            var list = new List<LimitData>();

            if (calculatedCLs)
            {
                var category = 1;
                for (var i = 0; i < dataContext.DataSource.Count; i++)
                {
                    list.Add(new LimitData(category, dataContext.UCL));
                    category++;
                }                
            }
            else
            {
                var category = 1;
                for (var i = 0; i < dataContext.DataSource.Count; i++)
                {
                    list.Add(new LimitData(category, dataContext.ParentPanel.CustomUCL));
                    category++;
                }
            }

            return list;
        }
        /// <summary>
        /// Does setup of AutoCAD IO. 
        /// This method will need to be invoked once before any other methods of this
        /// utility class can be invoked.
        /// </summary>
        /// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param>
        /// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param>
        public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret)
        {
            try
            {
                String clientId = autocadioclientid;
                String clientSecret = autocadioclientsecret;

                Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/");
                container = new AIO.Operations.Container(uri);
                container.Format.UseJson();

                using (var client = new HttpClient())
                {
                    var values = new List<KeyValuePair<string, string>>();
                    values.Add(new KeyValuePair<string, string>("client_id", clientId));
                    values.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                    values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                    var requestContent = new FormUrlEncodedContent(values);
                    var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);
                    _accessToken = resValues["token_type"] + " " + resValues["access_token"];
                    if (!string.IsNullOrEmpty(_accessToken))
                    {
                        container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message));
                container = null;
                throw;
            }
        }
                private ImmutableArray<int> ComputePathFromRoot(SyntaxNode node)
                {
                    var path = new List<int>();
                    var root = _tree.GetRoot();

                    while (node != root)
                    {
                        for (; node.Parent != null; node = node.Parent)
                        {
                            var index = GetChildIndex(node);
                            path.Add(index);
                        }

                        // if we were part of structure trivia, continue searching until we get to the true root
                        if (node.IsStructuredTrivia)
                        {
                            var trivia = node.ParentTrivia;
                            var triviaIndex = GetTriviaIndex(trivia);
                            path.Add(triviaIndex);
                            var tokenIndex = GetChildIndex(trivia.Token);
                            path.Add(tokenIndex);
                            node = trivia.Token.Parent;
                            continue;
                        }
                        else if (node != root)
                        {
                            throw new InvalidOperationException(CSharpWorkspaceResources.Node_does_not_descend_from_root);
                        }
                    }

                    path.Reverse();
                    return path.ToImmutableArray();
                }
Example #14
0
 public override List<Type> getWeaknesses()
 {
     List<Type> weak = new List<Type>();
     weak.Add(new Electric());
     weak.Add(new Grass());
     return weak;
 }
    void Test_diclist()
    {
        Dictionary <string, List<string>> myDic
            = new Dictionary<string, List<string>> ();
        string keystr;

        // command 1
        keystr = "hello";
        var res1ls = new List<string> ();
        res1ls.Add ("hello, Mike");
        res1ls.Add ("tadano shikabane no youda");
        res1ls.Add ("This number is not currently registered");
        myDic.Add (keystr, res1ls);

        // command 2
        keystr = "Ca va bien?";
        var res2ls = new List<string> ();
        res2ls.Add ("Merci, beaucoup");
        res2ls.Add ("honjitsu wa sentenn nari");
        res2ls.Add ("Je nous peut pas parler Francaise.");
        myDic.Add (keystr, res2ls);

        //		displayAllElementWithKey (ref myDic, /* searchKey=*/"hello");
        for (int loop=0; loop<10; loop++) {
            findElementWithKey (ref myDic, /* searchKey=*/"hello");
        }
    }
Example #16
0
        static void Main(string[] args)
        {
            List<int> list = new List<int>
            {
                3,2,
            }; // 3, 2

            list.Add(5); // 3, 2, 5
            list.Add(6); // 3, 2, 5, 6
            list.Remove(5); // 3, 2, 6

            Queue<int> queue = new Queue<int>();
            queue.Enqueue(3);// 3
            queue.Enqueue(8);// 3, 8
            queue.Dequeue(); // 8

            Stack<int> stack = new Stack<int>();
            stack.Push(2); // 2
            stack.Push(7); // 7, 2
            stack.Push(8); // 8, 7, 2
            stack.Pop();   // 7, 2

            foreach (var i in stack)
            {
                Console.WriteLine(i);
            }

            LinkedList<int> linkedList = new LinkedList<int>();
            linkedList.AddFirst(9); // 9
            linkedList.AddAfter(linkedList.Find(9), 5); // 9, 5
            linkedList.Remove(9); // 5

            Console.Read();
        }
Example #17
0
        //---------------------------------------------------------------------
        public List<EbVector3> navigate(EbVector3 from_world, EbVector3 to_world, uint max_step)
        {
            EbVector2 from_grid = _world2gird(from_world);
            EbVector2 to_grid = _world2gird(to_world);

            List<EbVector3> route_points = new List<EbVector3>();
            if (_isInGrid(from_grid) && _isInGrid(to_grid))
            {
                if (mPixelNav.search((int)from_grid.x, (int)from_grid.y, (int)to_grid.x, (int)to_grid.y, max_step))
                {
                    for (int i = 1; i < mPixelNav.Route.Count - 1; ++i)
                    {
                        route_points.Add(_grid2world(mPixelNav.Route[i]));
                    }
                    route_points.Add(to_world);
                }
                else
                {
                    for (int i = 1; i < mPixelNav.Route.Count; ++i)
                    {
                        route_points.Add(_grid2world(mPixelNav.Route[i]));
                    }
                }
            }

            return route_points;
        }
        public IMediaType GetMediaType(string acceptHeader)
        {
            if (string.IsNullOrEmpty(acceptHeader)) return mediaTypes.Default;

            var types = acceptHeader.Split(',');
            var acceptedMediaType = new List<QualifiedMediaType>();

            foreach (var type in types)
            {
                var parsedFormat = ParseFormat(type);

                if (IsDefaultFormat(parsedFormat.Format))
                {
                    acceptedMediaType.Add(new QualifiedMediaType(mediaTypes.Default, parsedFormat.Qualifier));
                }
                else
                {
                    var mediaType = mediaTypes.Find(parsedFormat.Format);
                    if (mediaType != null) acceptedMediaType.Add(new QualifiedMediaType(mediaType, parsedFormat.Qualifier));
                }
            }

            if (acceptedMediaType.Count == 0) throw new AcceptHeaderNotSupportedException();
            return MostQualifiedMediaType(acceptedMediaType);
        }
Example #19
0
        public static List<OptionSetItem> GetOptionSetValues(string entityLogicalName, string attributeLogicalName, bool? allowEmpty)
        {
            if (allowEmpty == null) allowEmpty = false;
            string cacheKey = entityLogicalName + "." + attributeLogicalName + "." + allowEmpty.ToString();

            if (_optionsCache.ContainsKey(cacheKey))
                return _optionsCache[cacheKey];
            else
            {
                AttributeMetadata attribute = LoadAttributeMetadata(entityLogicalName, attributeLogicalName);
                PicklistAttributeMetadata pickList = (PicklistAttributeMetadata)attribute;
                List<OptionSetItem> opts = new List<OptionSetItem>();
                if (allowEmpty.Value)
                    opts.Add(new OptionSetItem());

                foreach (OptionMetadata o in pickList.OptionSet.Options)
                {
                    OptionSetItem a = new OptionSetItem();
                    a.Name = o.Label.UserLocalizedLabel.Label;
                    a.Value = o.Value.Value;
                    opts.Add(a);
                }

                return opts;
            }
        }
Example #20
0
		public static List<CallbackResult> Get(ClientInfo clientInfo)
		{
			lock (CallbackResultItems)
			{
				var result = new List<CallbackResult>();
				if (clientInfo.IsDisconnecting)
				{
					var callbackResult = new CallbackResult()
					{
						CallbackResultType = CallbackResultType.Disconnecting
					};
					result.Add(callbackResult);
					return result;
				}
				foreach (var callbackResultItem in CallbackResultItems)
				{
					if (callbackResultItem.Index > clientInfo.CallbackIndex)
					{
						if (!(callbackResultItem.CallbackResult.GKProgressCallback != null && callbackResultItem.CallbackResult.GKProgressCallback.IsCanceled))
							result.Add(callbackResultItem.CallbackResult);
					}
				}
				clientInfo.CallbackIndex = Index;
				return result;
			}
		}
        private string[] SanitizeArgs(string[] args)
        {
            var commands = new List<string>();
            var enumerator = args.GetEnumerator();
            StringBuilder builder = null;
            while (enumerator.MoveNext())
            {
                var arg = enumerator.Current as string;
                if (arg.StartsWith(_token))
                {
                    if (builder != null) commands.Add(builder.ToString());
                    builder = new StringBuilder();
                    builder.Append(arg);
                }
                else
                {
                    builder.Append($" {arg}");
                }
            }


            commands.Add(builder.ToString());

            return commands.ToArray();
        }
Example #22
0
    static List<int> MakeMegre(List<int> left, List<int> right)
    {
        List<int> result = new List<int>();

        while (left.Count > 0 || right.Count > 0)
        {
            if (left.Count > 0 && right.Count > 0)
            {
                if (left[0] <= right[0])
                {
                    result.Add(left[0]);
                    left.RemoveAt(0);
                }
                else
                {
                    result.Add(right[0]);
                    right.RemoveAt(0);
                }
            }
            else if (left.Count > 0)
            {
                result.Add(left[0]);
                left.RemoveAt(0);
            }
            else if (right.Count > 0)
            {
                result.Add(right[0]);
                right.RemoveAt(0);
            }

            return result;
        }
    }
 public ICollection<Event> GetEvents(string name, int year)
 {
     List<Event> eventer = new List<Event>();
     var ev1 = new Event()
     {
         Id = 1,
         Date = new DateTime(2015, 4, 14),
         Name = "Folkeparken"
     };
     var ev2 = new Event()
     {
         Id = 1,
         Date = new DateTime(2015, 5, 11),
         Name = "Krokenmila"
     };
     var ev3 = new Event()
     {
         Id = 1,
         Date = new DateTime(2015, 6, 8),
         Name = "Folkeparken"
     };
     eventer.Add(ev1);
     eventer.Add(ev2);
     eventer.Add(ev3);
     return eventer;
 }
Example #24
0
        public override List<SqlParameter> CreateInsertParameters(IModel obj, ref SqlParameter returnValue)
        {
            FinanceBusinessInvoice inv_financebusinessinvoice_ref = (FinanceBusinessInvoice)obj;

            List<SqlParameter> paras = new List<SqlParameter>();
            returnValue.Direction = ParameterDirection.Output;
            returnValue.SqlDbType = SqlDbType.Int;
            returnValue.ParameterName = "@RefId";
            returnValue.Size = 4;
            paras.Add(returnValue);

            SqlParameter businessinvoiceidpara = new SqlParameter("@BusinessInvoiceId", SqlDbType.Int, 4);
            businessinvoiceidpara.Value = inv_financebusinessinvoice_ref.BusinessInvoiceId;
            paras.Add(businessinvoiceidpara);

            SqlParameter financeinvoiceidpara = new SqlParameter("@FinanceInvoiceId", SqlDbType.Int, 4);
            financeinvoiceidpara.Value = inv_financebusinessinvoice_ref.FinanceInvoiceId;
            paras.Add(financeinvoiceidpara);

            SqlParameter balapara = new SqlParameter("@Bala", SqlDbType.Decimal, 9);
            balapara.Value = inv_financebusinessinvoice_ref.Bala;
            paras.Add(balapara);

            return paras;
        }
Example #25
0
 public BookCollection()
 {
     books = new List<Book>();
     books.Add(new Book { Id = 1, Name = "Война и мир", Author = "Л. Толстой", Price = 220 });
     books.Add(new Book { Id = 2, Name = "Отцы и дети", Author = "И. Тургенев", Price = 180 });
     books.Add(new Book { Id = 3, Name = "Чайка", Author = "А. Чехов", Price = 150 });
 }
        public dynamic Process(NancyModule nancyModule, AuthenticateCallbackData model)
        {
            Response response = nancyModule.Response.AsRedirect("~/");

            if (nancyModule.IsAuthenticated())
            {
                response = nancyModule.Response.AsRedirect("~/account/#identityProviders");
            }

            if (model.Exception != null)
            {
                nancyModule.Request.AddAlertMessage("error", model.Exception.Message);
            }
            else
            {
                UserInformation information = model.AuthenticatedClient.UserInformation;
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, information.Id));
                claims.Add(new Claim(ClaimTypes.AuthenticationMethod, model.AuthenticatedClient.ProviderName));

                if (!String.IsNullOrEmpty(information.UserName))
                {
                    claims.Add(new Claim(ClaimTypes.Name, information.UserName));
                }

                if (!String.IsNullOrEmpty(information.Email))
                {
                    claims.Add(new Claim(ClaimTypes.Email, information.Email));
                }

                nancyModule.SignIn(claims);
            }

            return response;
        }
Example #27
0
 public override Template Visit(GlobalBlock block)
 {
     Template template = new Template("<list; separator=\"\n\">");
     List<Template> list = new List<Template>();
     bool last = false;
     AstNode last_node = null;
     foreach (var node in block.List)
     {
         bool current = node is FuncDef || node is Class || node is Enum || node is Import || node is GlobalUsing || node is Namespace;
         if ((last || current) && !(last_node is Import && node is Import))
         {
             Template tp = new Template("\n<node>");
             tp.Add("node", node.Accept(this));
             list.Add(tp);
         }
         else
         {
             list.Add(node.Accept(this));
         }
         last = current;
         last_node = node;
     }
     template.Add("list", list);
     return template;
 }
Example #28
0
        public Athlete()
        {
            BikeCadenceRanges = new List<ICadenceRange>(5);
            BikePowerEnergyRanges = new List<IEnergySystemRange>(6);
            BikeHeartRateEnergyRanges = new List<IEnergySystemRange>(6);
            // Can externally define these ranges later.
            BikeCadenceRanges.Add(new CadenceRange(0, 40, WorkoutCadenceFocus.None));
            BikeCadenceRanges.Add(new CadenceRange(40, 65, WorkoutCadenceFocus.Grinding));
            BikeCadenceRanges.Add(new CadenceRange(65, 80, WorkoutCadenceFocus.Climbing));
            BikeCadenceRanges.Add(new CadenceRange(80, 100, WorkoutCadenceFocus.Normal));
            BikeCadenceRanges.Add(new CadenceRange(100, 250, WorkoutCadenceFocus.Spinning));

            BikePowerEnergyRanges.Add(new EnergySystemRange(0, 55, WorkoutEnergySystemFocus.Zone1));
            BikePowerEnergyRanges.Add(new EnergySystemRange(55, 75, WorkoutEnergySystemFocus.Zone2));
            BikePowerEnergyRanges.Add(new EnergySystemRange(75, 90, WorkoutEnergySystemFocus.Zone3));
            BikePowerEnergyRanges.Add(new EnergySystemRange(90, 105, WorkoutEnergySystemFocus.Zone4));
            BikePowerEnergyRanges.Add(new EnergySystemRange(105, 120, WorkoutEnergySystemFocus.Zone5));
            BikePowerEnergyRanges.Add(new EnergySystemRange(120, 10000, WorkoutEnergySystemFocus.Zone6));

            BikeHeartRateEnergyRanges.Add(new EnergySystemRange(0, 81, WorkoutEnergySystemFocus.Zone1));
            BikeHeartRateEnergyRanges.Add(new EnergySystemRange(81, 89, WorkoutEnergySystemFocus.Zone2));
            BikeHeartRateEnergyRanges.Add(new EnergySystemRange(90, 94, WorkoutEnergySystemFocus.Zone3));
            BikeHeartRateEnergyRanges.Add(new EnergySystemRange(94, 103, WorkoutEnergySystemFocus.Zone4));
            BikeHeartRateEnergyRanges.Add(new EnergySystemRange(103, 105, WorkoutEnergySystemFocus.Zone5));
            BikeHeartRateEnergyRanges.Add(new EnergySystemRange(105, 10000, WorkoutEnergySystemFocus.Zone6));

            // Run Pace
            //        Zone 1 Slower than 129% of FTP
            //Zone 2 114% to 129% of FTP
            //Zone 3 106% to 113% of FTP
            //Zone 4 99% to 105% of FTP
            //Zone 5a 97% to 100% of FTP
            //Zone 5b 90% to 96% of FTP
            //Zone 5c Faster than 90% of FTP
        }
        protected override List<Value> values(Vessel vessel, GameEvent events)
        {
            List<Value> values = new List<Value> ();

            int count = 0;
            if (vessel != null) {
                foreach (Part p in vessel.Parts) {
                    if (p.partInfo.name.Equals (partName)) {
                        ++count;
                    }
                }
            }
            if(maxPartCount == -1) {
                if (vessel == null) {
                    values.Add (new Value ("Part", partCount + "x " + partName));
                } else {
                    values.Add (new Value ("Part", partCount + "x " + partName, "" + count, count >= partCount));
                }
            } else {
                if (vessel == null) {
                    values.Add (new Value ("max part", maxPartCount + "x " + partName));
                } else {
                    values.Add (new Value ("max part", maxPartCount + "x " + partName, "" + count, count <= maxPartCount));
                }
            }

            return values;
        }
        private byte[] GetLengthBytes()
        {
            var payloadLengthBytes = new List<byte>(9);

            if (PayloadLength > ushort.MaxValue)
            {
                payloadLengthBytes.Add(127);
                byte[] lengthBytes = BitConverter.GetBytes(PayloadLength);
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(lengthBytes);
                payloadLengthBytes.AddRange(lengthBytes);
            }
            else if (PayloadLength > 125)
            {
                payloadLengthBytes.Add(126);
                byte[] lengthBytes = BitConverter.GetBytes((UInt16) PayloadLength);
                if (BitConverter.IsLittleEndian)
                    Array.Reverse(lengthBytes);
                payloadLengthBytes.AddRange(lengthBytes);
            }
            else
            {
                payloadLengthBytes.Add((byte) PayloadLength);
            }

            payloadLengthBytes[0] += (byte) (IsMasked ? 128 : 0);

            return payloadLengthBytes.ToArray();
        }
Example #31
0
        private IEnumerator UploadWWW(string url, string requestType, List <IMultipartFormSection> body, System.Action <UnityWebRequest> callback)
        {
            byte[] byteBoundary = UnityWebRequest.GenerateBoundary();
            byte[] generated    = UnityWebRequest.SerializeFormSections(body, byteBoundary);

            List <byte> generatedList = new List <byte>();

            for (int i = 0; i < generated.Length; i++)
            {
                generatedList.Add(generated[i]);
            }

            // add end-boundary
            byte[] endBoundary = Encoding.ASCII.GetBytes("\r\n--" + Encoding.ASCII.GetString(byteBoundary) + "--");
            for (int i = 0; i < endBoundary.Length; i++)
            {
                generatedList.Add(endBoundary[i]);
            }


            UnityWebRequest req = new UnityWebRequest(url);

            req.method = requestType;

            AddHeadersToRequest(req);

            //string boundary = Encoding.ASCII.GetString(UnityWebRequest.GenerateBoundary());

            //string strEndBoundary = "\r\n--" + boundary + "--";

            //string formdataTemplate = "\r\n--" + boundary +
            //                         "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            //Dictionary<string, string> fields = new Dictionary<string, string>();
            //fields.Add("actionid", "testaction2");
            //fields.Add("actionname", "testaction2");
            //fields.Add("actiondesc", "a new action");

            //string strBody = "";

            //foreach (KeyValuePair<string, string> pair in fields)
            //{
            //    string formitem = string.Format(formdataTemplate, pair.Key, pair.Value);
            //    strBody += formitem;
            //}

            //strBody += strEndBoundary;

            //Debug.Log(strBody);

            //byte[] bytes = Encoding.ASCII.GetBytes(strBody);

            req.uploadHandler = new UploadHandlerRaw(generatedList.ToArray());
            // req.uploadHandler.contentType = "multipart/form-data; boundary=" + boundary;
            req.uploadHandler.contentType = "multipart/form-data; boundary=" + Encoding.ASCII.GetString(byteBoundary);

            req.downloadHandler = new DownloadHandlerBuffer();

            yield return(req.Send());

            if (callback != null)
            {
                callback(req);
            }
        }
Example #32
0
            private String getConvoNodeScript(String convName, Node node)
            {
                String script = "";
                List<NodeItem> items = (List<NodeItem>)node.Items;
                NodeTextBoxItem nameItem = (NodeTextBoxItem)items[0];
                script += "\tnew ScriptObject(" + convName + "_" + nameItem.Text + ") {" + Environment.NewLine;
                script += "\t\tclass = \"ConversationNode\";" + Environment.NewLine;
                script += "\t\tcanSave = \"1\";" + Environment.NewLine;
                script += "\t\tcanSaveDynamicFields = \"1\";" + Environment.NewLine;
                int outNodeCount = items.Count - int.Parse(m_settings.Attributes["[Default]"]["CONVOOUTNODESTART"]);
                int start = int.Parse(m_settings.Attributes["[Default]"]["CONVOOUTNODESTART"]);
                NodeTextBoxItem nodeText = (NodeTextBoxItem)items[1];
                script += "\t\t\tdisplayText = \"" + conditionText(nodeText.Text) + "\";" + Environment.NewLine;
                script += "\t\t\tnumOutLinks = " + outNodeCount + ";" + Environment.NewLine;

                String target = "";
                List<String> foundNodes = new List<String>();
                for (int i = start; i < items.Count; i++)
                {
                    NodeCompositeItem textItem = (NodeCompositeItem)items[i];
                    String Text = "";
                    String Method = "";
                    foreach(ItemTextBoxPart part in textItem.Parts)
                    {
                        if (part.Name == "ConvText")
                            Text = part.Text;
                        if (part.Name == "ConvMethod")
                            Method = part.Text;
                    }
                    NodeOutputConnector conn = (NodeOutputConnector)textItem.Output;
                    foreach (NodeConnection con in conn.Connectors)
                    {
                        bool found = false;
                        if (con.To.Node == textItem.Node)
                            continue;
                        foreach (NodeConnection targetCon in con.To.Node.Connections)
                        {
                            if (targetCon.From.Item != textItem)
                                continue;
                            foreach (NodeItem item in con.To.Node.Items)
                            {
                                if (item.Name == "NodeName" && item.GetType().ToString() == "Graph.Items.NodeTextBoxItem")
                                {
                                    NodeTextBoxItem targetItem = (NodeTextBoxItem)item;
                                    if (foundNodes.Contains(targetItem.Text))
                                        continue;
                                    target = targetItem.Text;
                                    foundNodes.Add(target);
                                    found = true;
                                }
                                if (item.Name == "NodeName" && item.GetType().ToString() == "Graph.Items.NodeLabelItem")
                                {
                                    NodeLabelItem targetItem = (NodeLabelItem)item;
                                    if (foundNodes.Contains(targetItem.Text))
                                        continue;
                                    target = targetItem.Text;
                                    foundNodes.Add(target);
                                    found = true;
                                }
                                if (found)
                                    continue;
                            }
                        }
                    }
                    script += "\t\t\tbutton" + (i - start).ToString() + "next = " + convName + "_" + target + ";" + Environment.NewLine;
                    script += "\t\t\tbutton" + (i - start).ToString() + " = \"" + conditionText(Text) + "\";" + Environment.NewLine;
                    if (Method != "Enter script method")
                        script += "\t\t\tbutton" + (i - start).ToString() + "cmd = \"" + conditionText(Method) + ";\";" + Environment.NewLine;
                }
                script += "\t};" + Environment.NewLine;
                m_log.WriteLine("Generated Conversation Node " + nameItem.Text);
                return script;
            }
Example #33
0
        private static void populateMeshStruct(ref meshStruct mesh) {
            StreamReader stream = File.OpenText(mesh.fileName);
            string entireText = stream.ReadToEnd();
            stream.Close();
            using (StringReader reader = new StringReader(entireText)) {
                string currentText = reader.ReadLine();

                char[] splitIdentifier = { ' ' };
                char[] splitIdentifier2 = { '/' };
                string[] brokenString;
                string[] brokenBrokenString;
                int f = 0;
                int f2 = 0;
                int v = 0;
                int vn = 0;
                int vt = 0;
                int vt1 = 0;
                int vt2 = 0;
                while (currentText != null) {
                    if (!currentText.StartsWith("f ") && !currentText.StartsWith("v ") && !currentText.StartsWith("vt ") &&
                        !currentText.StartsWith("vn ") && !currentText.StartsWith("g ") && !currentText.StartsWith("usemtl ") &&
                        !currentText.StartsWith("mtllib ") && !currentText.StartsWith("vt1 ") && !currentText.StartsWith("vt2 ") &&
                        !currentText.StartsWith("vc ") && !currentText.StartsWith("usemap ")) {
                        currentText = reader.ReadLine();
                        if (currentText != null) {
                            currentText = currentText.Replace("  ", " ");
                        }
                    } else {
                        currentText = currentText.Trim();
                        brokenString = currentText.Split(splitIdentifier, 50);
                        switch (brokenString[0]) {
                            case "g":
                                break;
                            case "usemtl":
                                break;
                            case "usemap":
                                break;
                            case "mtllib":
                                break;
                            case "v":
                                mesh.vertices[v] = new Vector3(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]),
                                                         System.Convert.ToSingle(brokenString[3]));
                                v++;
                                break;
                            case "vt":
                                mesh.uv[vt] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]));
                                vt++;
                                break;
                            case "vt1":
                                mesh.uv[vt1] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]));
                                vt1++;
                                break;
                            case "vt2":
                                mesh.uv[vt2] = new Vector2(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]));
                                vt2++;
                                break;
                            case "vn":
                                mesh.normals[vn] = new Vector3(System.Convert.ToSingle(brokenString[1]), System.Convert.ToSingle(brokenString[2]),
                                                        System.Convert.ToSingle(brokenString[3]));
                                vn++;
                                break;
                            case "vc":
                                break;
                            case "f":

                                int j = 1;
                                List<int> intArray = new List<int>();
                                while (j < brokenString.Length && ("" + brokenString[j]).Length > 0) {
                                    Vector3 temp = new Vector3();
                                    brokenBrokenString = brokenString[j].Split(splitIdentifier2, 3);    //Separate the face into individual components (vert, uv, normal)
                                    temp.x = System.Convert.ToInt32(brokenBrokenString[0]);
                                    if (brokenBrokenString.Length > 1)                                  //Some .obj files skip UV and normal
                                    {
                                        if (brokenBrokenString[1] != "")                                    //Some .obj files skip the uv and not the normal
                                        {
                                            temp.y = System.Convert.ToInt32(brokenBrokenString[1]);
                                        }
                                        temp.z = System.Convert.ToInt32(brokenBrokenString[2]);
                                    }
                                    j++;

                                    mesh.faceData[f2] = temp;
                                    intArray.Add(f2);
                                    f2++;
                                }
                                j = 1;
                                while (j + 2 < brokenString.Length)     //Create triangles out of the face data.  There will generally be more than 1 triangle per face.
                                {
                                    mesh.triangles[f] = intArray[0];
                                    f++;
                                    mesh.triangles[f] = intArray[j];
                                    f++;
                                    mesh.triangles[f] = intArray[j + 1];
                                    f++;

                                    j++;
                                }
                                break;
                        }
                        currentText = reader.ReadLine();
                        if (currentText != null) {
                            currentText = currentText.Replace("  ", " ");       //Some .obj files insert double spaces, this removes them.
                        }
                    }
                }
            }
        }
Example #34
0
    private void CalculatePassengerMovement(Vector3 velocity) {
        HashSet<Transform> movedPassengers = new HashSet<Transform>();
        passengerMovement = new List<PassengerMovement>();

        float directionX = Mathf.Sign(velocity.x);
        float directionY = Mathf.Sign(velocity.y);

        /*Vertically moving platform*/
        if (velocity.y != 0) {
            float rayLength = Mathf.Abs(velocity.y) + skinWidth;

            for (int i = 0; i < verticalRayCount; i++) {
                Vector2 rayOrigin = directionY == -1 ? raycastOrigins.bottomLeft : raycastOrigins.topLeft;
                rayOrigin += Vector2.right * (verticalRaySpacing * i);

                RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, passengerMask);
                /*hit.distance checks if the player is inside the platform*/
                if (hit && hit.distance != 0) {
                    if (!movedPassengers.Contains(hit.transform)) {
                        float pushX = directionY == 1 ? velocity.x : 0;
                        float pushY = velocity.y - (hit.distance - skinWidth) * directionY;
                        passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), directionY == 1, true));

                        movedPassengers.Add(hit.transform);
                    }
                }
            }
        }

        /*Horizontally moving platform*/
        if (velocity.x != 0) {
            float rayLength = Mathf.Abs(velocity.x) + skinWidth;

            for (int i = 0; i < horizontalRayCount; i++) {
                Vector2 rayOrigin = directionX == -1 ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight;
                rayOrigin += Vector2.up * (horizontalRaySpacing * i);

                RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, passengerMask);

                if (hit && hit.distance != 0) {
                    if (!movedPassengers.Contains(hit.transform)) {
                        float pushX = velocity.x - (hit.distance - skinWidth) * directionX;
                        float pushY = -skinWidth;
                        passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), false, true));

                        movedPassengers.Add(hit.transform);
                    }
                }
            }
        }

        /*Passenger is on top of horizontally moving platform*/
        if(directionY == -1 || velocity.y == 0 && velocity.x != 0) {
            float rayLength = skinWidth * 2;

            for (int i = 0; i < verticalRayCount; i++) {
                Vector2 rayOrigin = raycastOrigins.topLeft + Vector2.right * (verticalRaySpacing * i);

                RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up, rayLength, passengerMask);
                if (hit && hit.distance != 0) {
                    if (!movedPassengers.Contains(hit.transform)) {
                        float pushX = velocity.x;
                        float pushY = velocity.y - (hit.distance - skinWidth) * directionY;
                        passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), true, false));

                        movedPassengers.Add(hit.transform);
                    }
                }
            }
        }

    }
Example #35
0
        private void ProcessIncludedText(string page)
        {
            bool include            = true;
            bool specialDontInclude = false;
            int  i = 0;

            StringBuilder text = new StringBuilder();

            while (i < page.Length)
            {
                if (page[i] == '<')
                {
                    include = false;
                    string toCheck;
                    i++;

                    if (i + 25 < page.Length)
                    {
                        toCheck = page.Substring(i, 24);
                        if (toCheck == "div id=\"cnnGlobalFooter\"")
                        {
                            break;
                        }
                    }
                    if (i + 34 < page.Length)
                    {
                        toCheck = page.Substring(i, 34);
                        if (toCheck == "div class=\"cnnSCRightColBorderBox\"")
                        {
                            break;
                        }
                    }
                    if (i + 24 < page.Length)
                    {
                        toCheck = page.Substring(i, 24);
                        if (toCheck == "p class=\"cnnAttribution\"")
                        {
                            break;
                        }
                    }
                    if (i + 19 < page.Length)
                    {
                        toCheck = page.Substring(i, 19);
                        if (toCheck == "p class=\"cnnTopics\"")
                        {
                            break;
                        }
                    }
                    if (i + 6 < page.Length)
                    {
                        toCheck = page.Substring(i, 6);
                        if (toCheck == "script")
                        {
                            specialDontInclude = true;
                        }
                    }

                    continue;
                }
                if (page[i] == '>')
                {
                    if (specialDontInclude)
                    {
                        specialDontInclude = false;
                        i++;
                    }
                    else
                    {
                        include = true;
                        i++;
                    }
                    continue;
                }
                if (include)
                {
                    text.Append(page[i]);
                }
                i++;
            }


            Regex linkReg = new Regex("<a href=\"http:[^\"]+\"");

            foreach (Match m in linkReg.Matches(page))
            {
                Uri tmp = new Uri(m.Value.Substring(9, m.Value.Length - 10));
                if (!allLinks.Contains(tmp))
                {
                    allLinks.Add(tmp);
                }
            }

            pureText = text.ToString().Trim();
        }
Example #36
0
        /// <summary>
        /// Generate the necessary parameters
        /// </summary>
        public List <KeyValuePair <string, string> > GetParams()
        {
            var p = new List <KeyValuePair <string, string> >();

            if (From != null)
            {
                p.Add(new KeyValuePair <string, string>("From", From.ToString()));
            }

            if (To != null)
            {
                p.Add(new KeyValuePair <string, string>("To", To.ToString()));
            }

            if (StatusCallback != null)
            {
                p.Add(new KeyValuePair <string, string>("StatusCallback", StatusCallback.AbsoluteUri.TrimEnd('/')));
            }

            if (StatusCallbackMethod != null)
            {
                p.Add(new KeyValuePair <string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString()));
            }

            if (StatusCallbackEvent != null)
            {
                p.AddRange(StatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("StatusCallbackEvent", prop)));
            }

            if (Timeout != null)
            {
                p.Add(new KeyValuePair <string, string>("Timeout", Timeout.Value.ToString()));
            }

            if (Record != null)
            {
                p.Add(new KeyValuePair <string, string>("Record", Record.Value.ToString().ToLower()));
            }

            if (Muted != null)
            {
                p.Add(new KeyValuePair <string, string>("Muted", Muted.Value.ToString().ToLower()));
            }

            if (Beep != null)
            {
                p.Add(new KeyValuePair <string, string>("Beep", Beep));
            }

            if (StartConferenceOnEnter != null)
            {
                p.Add(new KeyValuePair <string, string>("StartConferenceOnEnter", StartConferenceOnEnter.Value.ToString().ToLower()));
            }

            if (EndConferenceOnExit != null)
            {
                p.Add(new KeyValuePair <string, string>("EndConferenceOnExit", EndConferenceOnExit.Value.ToString().ToLower()));
            }

            if (WaitUrl != null)
            {
                p.Add(new KeyValuePair <string, string>("WaitUrl", WaitUrl.AbsoluteUri.TrimEnd('/')));
            }

            if (WaitMethod != null)
            {
                p.Add(new KeyValuePair <string, string>("WaitMethod", WaitMethod.ToString()));
            }

            if (EarlyMedia != null)
            {
                p.Add(new KeyValuePair <string, string>("EarlyMedia", EarlyMedia.Value.ToString().ToLower()));
            }

            if (MaxParticipants != null)
            {
                p.Add(new KeyValuePair <string, string>("MaxParticipants", MaxParticipants.Value.ToString()));
            }

            if (ConferenceRecord != null)
            {
                p.Add(new KeyValuePair <string, string>("ConferenceRecord", ConferenceRecord));
            }

            if (ConferenceTrim != null)
            {
                p.Add(new KeyValuePair <string, string>("ConferenceTrim", ConferenceTrim));
            }

            if (ConferenceStatusCallback != null)
            {
                p.Add(new KeyValuePair <string, string>("ConferenceStatusCallback", ConferenceStatusCallback.AbsoluteUri.TrimEnd('/')));
            }

            if (ConferenceStatusCallbackMethod != null)
            {
                p.Add(new KeyValuePair <string, string>("ConferenceStatusCallbackMethod", ConferenceStatusCallbackMethod.ToString()));
            }

            if (ConferenceStatusCallbackEvent != null)
            {
                p.AddRange(ConferenceStatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("ConferenceStatusCallbackEvent", prop)));
            }

            if (RecordingChannels != null)
            {
                p.Add(new KeyValuePair <string, string>("RecordingChannels", RecordingChannels));
            }

            if (RecordingStatusCallback != null)
            {
                p.Add(new KeyValuePair <string, string>("RecordingStatusCallback", RecordingStatusCallback.AbsoluteUri.TrimEnd('/')));
            }

            if (RecordingStatusCallbackMethod != null)
            {
                p.Add(new KeyValuePair <string, string>("RecordingStatusCallbackMethod", RecordingStatusCallbackMethod.ToString()));
            }

            if (SipAuthUsername != null)
            {
                p.Add(new KeyValuePair <string, string>("SipAuthUsername", SipAuthUsername));
            }

            if (SipAuthPassword != null)
            {
                p.Add(new KeyValuePair <string, string>("SipAuthPassword", SipAuthPassword));
            }

            if (Region != null)
            {
                p.Add(new KeyValuePair <string, string>("Region", Region));
            }

            if (ConferenceRecordingStatusCallback != null)
            {
                p.Add(new KeyValuePair <string, string>("ConferenceRecordingStatusCallback", ConferenceRecordingStatusCallback.AbsoluteUri.TrimEnd('/')));
            }

            if (ConferenceRecordingStatusCallbackMethod != null)
            {
                p.Add(new KeyValuePair <string, string>("ConferenceRecordingStatusCallbackMethod", ConferenceRecordingStatusCallbackMethod.ToString()));
            }

            if (RecordingStatusCallbackEvent != null)
            {
                p.AddRange(RecordingStatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("RecordingStatusCallbackEvent", prop)));
            }

            if (ConferenceRecordingStatusCallbackEvent != null)
            {
                p.AddRange(ConferenceRecordingStatusCallbackEvent.Select(prop => new KeyValuePair <string, string>("ConferenceRecordingStatusCallbackEvent", prop)));
            }

            return(p);
        }
        static void GenerateOverloadedMethod(TypeBuilder typeBuilder,
                                             MethodInfo methodToIntercept,
                                             MethodInfo anonymousDelegate,
                                             FieldInfo fieldProxy)
        {
            // Get method parameters
            ParameterInfo[] parameters         = methodToIntercept.GetParameters();
            List <Type>     parameterTypes     = new List <Type>();
            List <Type>     parameterRealTypes = new List <Type>();

            foreach (ParameterInfo parameter in parameters)
            {
                parameterTypes.Add(parameter.ParameterType);

                if (parameter.IsOut || parameter.ParameterType.IsByRef)
                {
                    parameterRealTypes.Add(parameter.ParameterType.GetElementType());
                }
                else
                {
                    parameterRealTypes.Add(parameter.ParameterType);
                }
            }

            // Define overriden method
            MethodBuilder method =
                typeBuilder.DefineMethod(methodToIntercept.Name,
                                         MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual,
                                         methodToIntercept.ReturnType,
                                         parameterTypes.ToArray());

            Type[] genericParameterTypes = SetupGenericMethodArguments(methodToIntercept, method);

            ILGenerator il = method.GetILGenerator();

            // Locals for reflection method info and parameter array, for calls to proxy.Invoke()
            il.DeclareLocal(typeof(MethodInfo));
            il.DeclareLocal(typeof(object[]));

            // Local for the return value
            if (methodToIntercept.ReturnType != typeof(void))
            {
                il.DeclareLocal(methodToIntercept.ReturnType);
            }

            // Initialize default values for out parameters
            for (int idx = 0; idx < parameters.Length; ++idx)
            {
                if (parameters[idx].IsOut && !parameters[idx].IsIn)
                {
                    il.Emit(OpCodes.Ldarg_S, idx + 1);
                    il.Emit(OpCodes.Initobj, parameterRealTypes[idx]);
                }
            }

            // Call to MethodInfo.GetCurrentMethod() and cast to MethodInfo
            il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetCurrentMethod", BindingFlags.Static | BindingFlags.Public));
            il.Emit(OpCodes.Castclass, typeof(MethodInfo));
            il.Emit(OpCodes.Stloc_0);

            // Create an array equal to the size of the # of parameters
            il.Emit(OpCodes.Ldc_I4_S, parameters.Length);
            il.Emit(OpCodes.Newarr, typeof(object));
            il.Emit(OpCodes.Stloc_1);

            // Populate the array
            for (int idx = 0; idx < parameters.Length; ++idx)
            {
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Ldc_I4_S, idx);
                il.Emit(OpCodes.Ldarg_S, idx + 1);

                if (parameters[idx].IsOut || parameters[idx].ParameterType.IsByRef)
                {
                    il.Emit(OpCodes.Ldobj, parameterRealTypes[idx]);
                }

                if (parameterRealTypes[idx].IsValueType || parameterRealTypes[idx].IsGenericParameter)
                {
                    il.Emit(OpCodes.Box, parameterRealTypes[idx]);
                }

                il.Emit(OpCodes.Stelem_Ref);
            }

            // Parameter 0 (this argument) for the call to Invoke
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, fieldProxy);

            // Parameter 1 (target) for the call to Invoke
            il.Emit(OpCodes.Ldarg_0);

            // Parameter 2 (method) for the call to Invoke
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Callvirt, typeof(MethodInfo).GetMethod("GetBaseDefinition"));

            // Parameter 3 (parameter array) for the call to Invoke
            il.Emit(OpCodes.Ldloc_1);

            // Parameter 4 (anonymous delegate) for the call to Invoke
            il.Emit(OpCodes.Ldarg_0);

            if (genericParameterTypes.Length > 0)
            {
                il.Emit(OpCodes.Ldftn, anonymousDelegate.MakeGenericMethod(genericParameterTypes));
            }
            else
            {
                il.Emit(OpCodes.Ldftn, anonymousDelegate);
            }

            il.Emit(OpCodes.Newobj, typeof(ILEmitProxy.InvokeDelegate).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) }));

            // Call Invoke
            il.Emit(OpCodes.Callvirt, typeof(ILEmitProxy).GetMethod("Invoke"));

            // Retrieve the return value from Invoke
            if (methodToIntercept.ReturnType == typeof(void))
            {
                il.Emit(OpCodes.Pop);
            }
            else
            {
                // Cast or unbox, dependening on whether it's a class or value type
                if (methodToIntercept.ReturnType.IsClass)
                {
                    il.Emit(OpCodes.Castclass, methodToIntercept.ReturnType);
                }
                else
                {
                    il.Emit(OpCodes.Unbox_Any, methodToIntercept.ReturnType);
                }

                // Store the value into the temporary
                il.Emit(OpCodes.Stloc_2);

                // Load the return value
                il.Emit(OpCodes.Ldloc_2);
            }

            // Set out/ref values before returning
            for (int idx = 0; idx < parameters.Length; ++idx)
            {
                if (parameters[idx].IsOut || parameters[idx].ParameterType.IsByRef)
                {
                    il.Emit(OpCodes.Ldarg_S, idx + 1);
                    il.Emit(OpCodes.Ldloc_1);
                    il.Emit(OpCodes.Ldc_I4_S, idx);
                    il.Emit(OpCodes.Ldelem_Ref);

                    if (parameterRealTypes[idx].IsValueType)
                    {
                        il.Emit(OpCodes.Unbox_Any, parameterRealTypes[idx]);
                    }
                    else
                    {
                        il.Emit(OpCodes.Castclass, parameterRealTypes[idx]);
                    }

                    il.Emit(OpCodes.Stobj, parameterRealTypes[idx]);
                }
            }

            il.Emit(OpCodes.Ret);
        }
Example #38
0
        protected void OkClick(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                try
                {
                    if (RolesDefineConfig.GetConfig().IsCurrentUserInRoles("ProcessAdmin") == false)
                        throw new OperationDeniedException("只有管理员可以进行此操作");

                    RolesDefineConfig.GetConfig().IsCurrentUserInRoles("ProcessAdmin").FalseThrow("只有管理员可以进行此操作");

                    if (string.IsNullOrEmpty(this.ddPg.SelectedValue) == false)
                    {
                        var old = WfApplicationAuthAdapter.Instance.Load(this.ddApp.SelectedValue, this.ddPg.SelectedValue, this.chkAdjuster.Checked ? WfApplicationAuthType.FormAdmin : WfApplicationAuthType.FormViewer);
                        if (old == null)
                            old = new WfApplicationAuth() { ApplicationName = this.ddApp.SelectedValue, AuthType = this.chkAdjuster.Checked ? WfApplicationAuthType.FormAdmin : WfApplicationAuthType.FormViewer, ProgramName = this.ddPg.SelectedItem.Value };

                        old.RoleID = this.inputRole.Text;
                        old.RoleDescription = this.inputRoleName.Value;

                        WfApplicationAuthAdapter.Instance.Update(old);
                        WebUtility.CloseWindow();
                    }
                    else
                    {
                        var appName = this.ddApp.SelectedValue;
                        var authType = this.chkAdjuster.Checked ? WfApplicationAuthType.FormAdmin : WfApplicationAuthType.FormViewer;
                        var old = WfApplicationAuthAdapter.Instance.Load(appName, authType);
                        var appPrograms = WfApplicationAdapter.Instance.LoadProgramsByApplication(appName);

                        var roleID = this.inputRole.Text;
                        var roleDescription = this.inputRoleName.Value;

                        List<WfApplicationAuth> auths = new List<WfApplicationAuth>(appPrograms.Count);
                        foreach (var item in appPrograms)
                        {
                            WfApplicationAuth auth = old.Find(m => m.ApplicationName == appName && m.AuthType == authType && m.ProgramName == item.CodeName);
                            if (auth == null)
                            {
                                auths.Add(new WfApplicationAuth() { ApplicationName = appName, AuthType = authType, ProgramName = item.CodeName, RoleID = roleID, RoleDescription = roleDescription });
                            }
                            else if (auth.RoleID != roleID)
                            {
                                auth.RoleID = roleID;
                                auth.RoleDescription = roleDescription;
                                auths.Add(auth);
                            }
                        }

                        using (System.Transactions.TransactionScope scope = MCS.Library.Data.TransactionScopeFactory.Create())
                        {
                            foreach (var item in auths)
                            {
                                WfApplicationAuthAdapter.Instance.Update(item);
                            }

                            scope.Complete();
                        }

                        WebUtility.CloseWindow();
                    }
                }
                catch (Exception ex)
                {
                    WebUtility.ShowClientError(ex);
                }
            }
        }
Example #39
0
        /// <summary>
        /// 批量导入校验
        /// </summary>
        public ActionResult MultitudeVaild(string nums, string uid)
        {
            var dat = nums.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            int storeCollocationId   = _storeProductCollocationContract.StoreProductCollocations.Where(o => o.Guid == uid).Select(x => x.Id).FirstOrDefault();
            var result               = new OperationResult(OperationResultType.Error, "");
            var validListFromCache   = (List <Product_Model>)SessionAccess.Get(SESSION_KEY_VALID_LIST + uid) ?? new List <Product_Model>();
            var invalidlistFromCache = (List <Product_Model>)SessionAccess.Get(SESSION_KEY_INVALID_LIST + uid) ?? new List <Product_Model>();
            var storeCollocation     = _storeProductCollocationContract.StoreProductCollocations.Where(o => !o.IsDeleted && o.IsEnabled)
                                       .Where(o => o.Id == storeCollocationId)
                                       .Include(o => o.StoreCollocationInfoItems)
                                       .FirstOrDefault();


            string strMessage = string.Empty;

            var modelList = dat.Select(barcode => new Product_Model {
                ProductBarcode = barcode, UUID = Guid.NewGuid().ToString()
            }).ToList();


            var checkRes = CheckCollcationEntity(storeCollocation);

            if (!checkRes.Item1)
            {
                invalidlistFromCache.Add(new Product_Model {
                    ProductBarcode = string.Empty
                });
            }
            else //批量校验
            {
                var tmpValidModels = new List <Product_Model>();
                //var allValid = true;
                var orderblankItemsFromDb = storeCollocation.StoreCollocationInfoItems.ToList();
                foreach (var modelToCheck in modelList)
                {
                    var res = CheckBarcode(modelToCheck, validListFromCache, invalidlistFromCache, orderblankItemsFromDb, storeCollocationId);
                    if (!res.Item1)
                    {
                        //allValid = false;
                        modelToCheck.Notes = res.Item2;
                        invalidlistFromCache.Add(modelToCheck);
                    }
                    else
                    {
                        tmpValidModels.Add(modelToCheck);
                        validListFromCache.Add(modelToCheck);
                    }
                }
                if (tmpValidModels.Count > 0)
                {
                    var optRes = BatchAddCollocationItem(storeCollocation, orderblankItemsFromDb, tmpValidModels.ToArray());
                    if (optRes.ResultType != OperationResultType.Success)
                    {
                        invalidlistFromCache.Add(new Product_Model {
                            ProductBarcode = string.Empty, Notes = optRes.Message
                        });
                    }
                }
            }

            SessionAccess.Set(SESSION_KEY_VALID_LIST + uid, validListFromCache);
            SessionAccess.Set(SESSION_KEY_INVALID_LIST + uid, invalidlistFromCache);
            result.Data       = new { validCount = validListFromCache.Count, invalidCount = invalidlistFromCache.Count };
            result.ResultType = OperationResultType.Success;
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Example #40
0
        public void Initialize(EnvironmentInfo environmentInfo, CleanupScoreManager scoreManager, AudioSource objectCollisionAudioSource)
        {
            List <GameObject> objectCollisionDestinations = new List <GameObject>();

            objectCollisionDestinations.Add(scoreManager.gameObject);
            objectCollisionDestinations.Add(this.playbackRecorder.gameObject);

            foreach (GameObject graspable in this.graspables)
            {
                CollisionTransferer collisionTransferer = graspable.AddComponent <CollisionTransferer>();

                collisionTransferer.Initialize(objectCollisionDestinations, Score.GetObjectCollisionVeloticyThreshold(), 0.1f, objectCollisionAudioSource);
            }


            this.graspablesPositionsMap   = null;             //key:GraspablePositionInfo,   value:Graspables
            this.destinationsPositionsMap = null;             //key:DestinationPositionInfo, value:DestinationCandidate

            switch (this.executionMode)
            {
            // For the competition. Read generated data.
            case ExecutionMode.Competition:
            {
                this.DeactivateGraspingCandidatesPositions();

                // Grasping target object
                this.graspingTarget = (from graspable in this.graspables where graspable.name == environmentInfo.graspingTargetName select graspable).First();

                if (this.graspingTarget == null)
                {
                    throw new Exception("Grasping target not found. name=" + environmentInfo.graspingTargetName);
                }

                // Graspables positions map
                this.graspablesPositionsMap = new Dictionary <RelocatableObjectInfo, GameObject>();

                foreach (RelocatableObjectInfo graspablePositionInfo in environmentInfo.graspablesPositions)
                {
                    GameObject graspableObj = (from graspable in this.graspables where graspable.name == graspablePositionInfo.name select graspable).First();

                    if (graspableObj == null)
                    {
                        throw new Exception("Graspable object not found. name=" + graspablePositionInfo.name);
                    }

                    this.graspablesPositionsMap.Add(graspablePositionInfo, graspableObj);
                }

                // Destination object
                this.destination = (from destinationCandidate in this.destinationCandidates where destinationCandidate.name == environmentInfo.destinationName select destinationCandidate).First();

                if (this.destination == null)
                {
                    throw new Exception("Destination not found. name=" + environmentInfo.destinationName);
                }

                // Add Placement checker to triggers
                this.AddPlacementChecker(this.destination);


                // Destination candidates position map
                this.destinationsPositionsMap = new Dictionary <RelocatableObjectInfo, GameObject>();

                foreach (RelocatableObjectInfo destinationPositionInfo in environmentInfo.destinationsPositions)
                {
                    GameObject destinationObj = (from destinationCandidate in this.destinationCandidates where destinationCandidate.name == destinationPositionInfo.name select destinationCandidate).First();

                    if (destinationObj == null)
                    {
                        throw new Exception("Destination candidate not found. name=" + destinationPositionInfo.name);
                    }

                    this.destinationsPositionsMap.Add(destinationPositionInfo, destinationObj);
                }

                break;
            }

            // For data generation.
            case ExecutionMode.DataGeneration:
            {
//					this.graspingTarget     = CleanupModeratorTools.GetGraspingTargetObject();
//					this.cleanupDestination = CleanupModeratorTools.GetDestinationObject();

                this.graspablesPositionsMap   = this.CreateGraspablesPositionsMap();
                this.destinationsPositionsMap = this.CreateDestinationsPositionsMap();

                break;
            }

            default:
            {
                throw new Exception("Illegal Execution mode. mode=" + CleanupConfig.Instance.configFileInfo.executionMode);
            }
            }

            foreach (KeyValuePair <RelocatableObjectInfo, GameObject> pair in this.graspablesPositionsMap)
            {
                pair.Value.transform.position    = pair.Key.position;
                pair.Value.transform.eulerAngles = pair.Key.eulerAngles;

//				Debug.Log(pair.Key.name + " : " + pair.Value.name);
            }

            foreach (KeyValuePair <RelocatableObjectInfo, GameObject> pair in this.destinationsPositionsMap)
            {
                pair.Value.transform.position    = pair.Key.position;
                pair.Value.transform.eulerAngles = pair.Key.eulerAngles;

//				Debug.Log(pair.Key.name + " : " + pair.Value.name);
            }

            this.rosConnections = SIGVerseUtils.FindObjectsOfInterface <IRosConnection>();

            SIGVerseLogger.Info("ROS connection : count=" + this.rosConnections.Length);


            // Set up the voice (Using External executable file)
            this.speechProcess = new System.Diagnostics.Process();
            this.speechProcess.StartInfo.FileName       = Application.dataPath + "/" + SpeechExePath;
            this.speechProcess.StartInfo.CreateNoWindow = true;
            this.speechProcess.StartInfo.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Hidden;

            this.isSpeechUsed = System.IO.File.Exists(this.speechProcess.StartInfo.FileName);

            this.speechInfoQue = new Queue <SpeechInfo>();

            SIGVerseLogger.Info("Text-To-Speech: " + Application.dataPath + "/" + SpeechExePath);


            this.hasPressedButtonToStartRecordingAvatarMotion = false;
            this.hasPressedButtonToStopRecordingAvatarMotion  = false;

            this.isPlacementSucceeded = null;

            this.ResetPointingStatus();
        }
 public List<Vector3> oneStep(Vector3 start, List<Vector4> beenThere)
 {
     List<Vector3> data = new List<Vector3>();
     List<Vector3> comp = new List<Vector3>();
     foreach (Vector4 temp in beenThere)
     {
         comp.Add(new Vector3(temp));
     }
     List<Vector3> Choices = location(Main.FEmpty);
     foreach (Vector3 pos in Choices)
     {
         if (start.X == pos.X && start.Z + 1 == pos.Z && pos.Y - start.Y <= 1 && !comp.Contains(start.offSet(0, 0, 1))) { data.Add(pos); }
         if (start.X == pos.X && start.Z - 1 == pos.Z && pos.Y - start.Y <= 1 && !comp.Contains(start.offSet(0, 0, -1))) { data.Add(pos); }
         if (start.X + 1 == pos.X && start.Z == pos.Z && pos.Y - start.Y <= 1 && !comp.Contains(start.offSet(1, 0, 0))) { data.Add(pos); }
         if (start.X - 1 == pos.X && start.Z == pos.Z && pos.Y - start.Y <= 1 && !comp.Contains(start.offSet(-1, 0, 0))) { data.Add(pos); }
     }
     return data;
 }
Example #42
0
        public AutomaticDestination(byte[] rawBytes, string sourceFile)
        {
            if (rawBytes.Length == 0)
            {
                throw new Exception("Empty file");
            }

            SourceFile = sourceFile;

            var appid = Path.GetFileName(sourceFile).Split('.').FirstOrDefault();
            if (appid != null)
            {
                var aid = new AppIdInfo(appid);
                AppId = aid;
            }
            else
            {
                AppId = new AppIdInfo("Unable to determine AppId");
            }

            _oleContainer = new OleCfFile(rawBytes, sourceFile);

            Directory = _oleContainer.Directory;

            var destList =
                _oleContainer.Directory.SingleOrDefault(t => t.DirectoryName.ToLowerInvariant() == "destlist");
            if (destList != null && destList.DirectorySize > 0)
            {
                var destBytes = _oleContainer.GetPayloadForDirectory(destList);

                DestList = new DestList(destBytes);
            }


            DestListEntries = new List<AutoDestList>();

            if (DestList != null)
            {
                DestListCount = DestList.Header.NumberOfEntries;
                DestListVersion = DestList.Header.Version;
                LastUsedEntryNumber = DestList.Header.LastEntryNumber;

                foreach (var entry in DestList.Entries)
                {
                    var dirItem =
                        _oleContainer.Directory.SingleOrDefault(
                            t =>
                                string.Equals(t.DirectoryName, entry.EntryNumber.ToString("X"),
                                    StringComparison.InvariantCultureIgnoreCase));

                    if (dirItem != null)
                    {
                        var sfn = $"{sourceFile}_Directory name_{dirItem.DirectoryName:X}";

                        var p = _oleContainer.GetPayloadForDirectory(dirItem);

                        var dlnk = new LnkFile(p, sfn);

                        var dle = new AutoDestList(entry, dlnk,entry.InteractionCount);

                        DestListEntries.Add(dle);
                    }
                    else
                    {
                        var dleNull = new AutoDestList(entry, null,entry.InteractionCount);

                        DestListEntries.Add(dleNull);
                    }
                }
            }
        }
Example #43
0
 public void ClearScreen()
 {
     _clearIndices.Add(_outputs.Count);
 }
Example #44
0
        private void layoutOption(List<String> _temporary)//选项 8个
        {
            mbordercontrol = new PaperBorderControl();
           
            mBorders = new List<Border>();

            mImagecontrol = new PaperImageControl();

            vImages = new List<Image>();

            cutLine();


            // 载入选项
            for (int i = 0; i < _temporary.Count; i++)// 8 是选项 ps:在内部就可以显示border 放外部循环就不行
            {
                //border 
                b = mbordercontrol.GenBorder(102, 94);
                mBorders.Add(b);
                PapertestCanvas.Children.Add(b);
                

                //image
                im = new Image();
                im = mImagecontrol.GetImage(82, 74);
                BitmapImage bitim = new BitmapImage();
                bitim.BeginInit();
               // bitim.UriSource = new Uri("\\PCAT;component\\Images\\" + _temporary[i] + ".bmp", UriKind.Relative);
                bitim.EndInit();
                im.Stretch = Stretch.Fill;
                im.Source = bitim;
                vImages.Add(im);
                PapertestCanvas.Children.Add(im);
               
                //Event

                im.MouseDown += new MouseButtonEventHandler(im_MouseDown);
                im.MouseEnter += new MouseEventHandler(im_MouseEnter);
                im.MouseLeave += new MouseEventHandler(im_MouseLeave);

                if (i < (_temporary.Count / 2))
                {

                    Canvas.SetTop(b, actual_y + bordertop);//
                    Canvas.SetLeft(b, actual_x + borderleft);// 
                    borderleft = borderleft + borderadd;

                    Canvas.SetTop(im, actual_y + imagetop);//
                    Canvas.SetLeft(im, actual_x + imageleft);//
                    imageleft = imageleft + imageadd;
                    
                    
                    
                }
                else 
                {
                    Canvas.SetTop(b, actual_y + bordertop2);// 
                    Canvas.SetLeft(b, actual_x + borderleft2);// 
                    borderleft2 = borderleft2 + borderadd;

                    Canvas.SetTop(im, actual_y + imagetop2);//
                    Canvas.SetLeft(im, actual_x + imageleft2);//
                    imageleft2 = imageleft2 + imageadd;
                    
                }
             }//---for

        }
Example #45
0
        /// <summary>
        /// Handle the drag/drop event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbl_DragDrop(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(DataFormats.FileDrop) || ((string[])e.Data.GetData(DataFormats.FileDrop)).Length != 1)
            {
                return;
            }
            string FileName = "";

            try
            {
                FileName = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                if (sender == lblDropMode)
                {
                    ProcessFile <int, String>(Modes, FileName, "ID_MODE(", ")", "= ", "", lblCountModes, "modes");
                }
                else if (sender == lblDropUserTypeFile)
                {
                    ProcessFile <int, String>(UserTypeNames, FileName, "USER(", ")", "= ", "", lblCountUserType, "usertypes");
                }
                else if (sender == lblDropUserName)
                {
                    ProcessFile <int, String>(UserNames, FileName, "USER(", ")", "= ", "", lblCountUserNames, "usernames");
                }
                else if (sender == lblDropArea)
                {
                    ProcessFile <int, String>(Areas, FileName, "ID_AREA(", ")", "= ", "", lblCountAreas, "areas");
                }
                else if (sender == lblDropPermission)
                {
                    ProcessFile <int[], bool>(Permissions, FileName, "_AREA_MODE(", ")", "= ", "", lblCountPermissions, "permissions");
                }
                else if (sender == lblDropOldOperatorships)
                {
                    ProcessFile(OldPermissions, FileName, lblCountAreas, "operatorships");
                }
                else if (sender == lblDropUserTypeToModeLinkages)
                {
                    String     InLine;
                    List <int> MappedTypes = null;
                    UserTypeToModeLinkages.Clear();
                    using (StreamReader sRd = new StreamReader(FileName))
                        while ((InLine = sRd.ReadLine()) != null)
                        {
                            if (InLine.StartsWith("USRTYP,"))
                            {
                                int StartStr = InLine.IndexOf("ID='") + 4;
                                UserTypeToModeLinkages.Add(InLine.Substring(StartStr, InLine.IndexOf("'", StartStr + 1) - StartStr), MappedTypes = new List <int>());
                            }
                            else if (InLine.StartsWith("UMODE,"))
                            {
                                MappedTypes.Add(int.Parse(InLine.Substring(InLine.LastIndexOf('=') + 1)));
                            }
                        }

                    foreach (List <int> MappedType in UserTypeToModeLinkages.Values)
                    {
                        MappedType.TrimExcess();
                    }
                    lblCountUserTypeToModeLinkages.Text = UserTypeToModeLinkages.Count.ToString() + " user->mode";
                }

                //Now, if we have enough data, produce our list
                if (Permissions.Count > 0 && Areas.Count > 0 && UserNames.Count > 0 && UserTypeNames.Count > 0 && Modes.Count > 0 && UserTypeToModeLinkages.Count > 0)
                {
                    NewPermissions.Clear();

                    //Now, perform our merging
                    List <String> MissingUsers = new List <String>();
                    List <int>    MissingAreas = new List <int>();
                    Dictionary <String, String> UserNameToUserType = new Dictionary <string, string>();

                    List <int> UserTypeToModeLinkage;
                    foreach (KeyValuePair <int, string> User in UserNames)
                    {
                        if (!UserTypeToModeLinkages.TryGetValue(UserTypeNames[User.Key], out UserTypeToModeLinkage))
                        {
                            MissingUsers.Add(UserTypeNames[User.Key]);
                        }
                        else
                        {
                            UserNameToUserType.Add(User.Value, UserTypeNames[User.Key]);
                            List <String> OutAreas = new List <string>();
                            String        FoundArea;
                            foreach (KeyValuePair <int[], bool> kvp in Permissions)
                            {
                                if (kvp.Value && UserTypeToModeLinkage.Contains(kvp.Key[1]))
                                {
                                    if (!Areas.TryGetValue(kvp.Key[0], out FoundArea))
                                    {
                                        MissingAreas.Add(kvp.Key[0]);
                                    }
                                    else if (!OutAreas.Contains(FoundArea))
                                    {
                                        OutAreas.Add(FoundArea);
                                    }
                                }
                            }
                            OutAreas.Sort(StringComparer.CurrentCultureIgnoreCase);
                            if (OutAreas.Count > 0)
                            {
                                NewPermissions.Add(User.Value, OutAreas.ToArray());
                            }
                        }
                    }


                    //Now, clear our ListView
                    lvOutputs.Items.Clear();
                    if (OldPermissions.Count > 0)
                    {
                        String[] FoundPermissions;
                        foreach (KeyValuePair <String, String[]> kvp in NewPermissions)
                        {
                            if (!OldPermissions.TryGetValue(kvp.Key, out FoundPermissions))
                            {
                                ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                                lvI.SubItems.Add(UserNameToUserType[kvp.Key]);
                                lvI.SubItems.Add("Yes");
                                lvI.SubItems.Add(String.Join(",", kvp.Value));
                                lvI.SubItems.Add("");
                            }
                            else
                            {
                                List <String> Additions = new List <string>();
                                List <String> Removals  = new List <string>();
                                foreach (String str in FoundPermissions)
                                {
                                    if (Array.IndexOf(kvp.Value, str) == -1)
                                    {
                                        Removals.Add(str);
                                    }
                                }
                                foreach (String str in kvp.Value)
                                {
                                    if (Array.IndexOf(FoundPermissions, str) == -1)
                                    {
                                        Additions.Add(str);
                                    }
                                }
                                if (Additions.Count + Removals.Count > 0)
                                {
                                    ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                                    lvI.SubItems.Add(UserNameToUserType[kvp.Key]);
                                    lvI.SubItems.Add("");
                                    lvI.SubItems.Add(String.Join(",", Additions.ToArray()));
                                    lvI.SubItems.Add(String.Join(",", Removals.ToArray()));
                                }
                            }
                        }

                        //Now, pull in our old ones that are missing
                        foreach (KeyValuePair <String, String[]> kvp in OldPermissions)
                        {
                            if (!NewPermissions.ContainsKey(kvp.Key))
                            {
                                ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                                lvI.SubItems.Add("Old");
                                lvI.SubItems.Add(String.Join(",", kvp.Value.ToArray()));
                                lvI.SubItems.Add("");
                            }
                        }
                    }
                    else
                    {
                        foreach (KeyValuePair <String, String[]> kvp in NewPermissions)
                        {
                            ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                            lvI.SubItems.Add(UserNameToUserType[kvp.Key]);

                            lvI.SubItems.Add("Yes");
                            lvI.SubItems.Add(String.Join(",", kvp.Value));
                            lvI.SubItems.Add("");
                        }
                    }

                    lvOutputs.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                    lvOutputs.Sort();
                    if (MissingAreas.Count > 0)
                    {
                        MessageBox.Show("Missing " + MissingAreas.Count.ToString() + " areas: " + String.Join(", ", MissingAreas.ToArray()));
                    }


                    if (MissingUsers.Count > 0)
                    {
                        MessageBox.Show("Missing " + MissingUsers.Count.ToString() + " users: " + String.Join(", ", MissingUsers.ToArray()));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading file " + FileName + ":" + ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #46
0
        public override void Init()
        {
            MyShaderDir = ShadersDir + "WorkshopShaders\\";

            //Crear loader
            var loader = new TgcSceneLoader();

            //Cargar mesh
            scene = loader.loadSceneFromFile(MediaDir + "ModelosTgc\\Teapot\\Teapot-TgcScene.xml");

            mesh          = scene.Meshes[0];
            mesh.Scale    = new Vector3(1f, 1f, 1f);
            mesh.Position = new Vector3(-100f, -5f, 0f);

            // Arreglo las normales
            var adj = new int[mesh.D3dMesh.NumberFaces * 3];

            mesh.D3dMesh.GenerateAdjacency(0, adj);
            mesh.D3dMesh.ComputeNormals(adj);

            //Cargar Shader personalizado
            effect =
                TgcShaders.loadEffect(MyShaderDir + "ToonShading.fx");

            // le asigno el efecto a la malla
            mesh.Effect    = effect;
            mesh.Technique = "DefaultTechnique";

            // Creo las instancias de malla
            instances = new List <TgcMesh>();
            for (var i = -5; i < 5; i++)
            {
                for (var j = -5; j < 5; j++)
                {
                    var instance = mesh.createMeshInstance(mesh.Name + i);
                    instance.move(i * 50, (i + j) * 5, j * 50);
                    instances.Add(instance);
                }
            }

            Modifiers.addBoolean("blurActivated", "activar blur", false);
            Modifiers.addVertex3f("LightPosition", new Vector3(-100, -100, -100),
                                  new Vector3(100, 100, 100), new Vector3(0, 40, 0));
            Modifiers.addFloat("Ambient", 0, 1, 0.5f);
            Modifiers.addFloat("Diffuse", 0, 1, 0.6f);
            Modifiers.addFloat("Specular", 0, 1, 0.5f);
            Modifiers.addFloat("SpecularPower", 1, 100, 16);

            Camara = new TgcRotationalCamera(new Vector3(20, 20, 0), 300, TgcRotationalCamera.DEFAULT_ZOOM_FACTOR, 1.5f,
                                             Input);

            // Creo un depthbuffer sin multisampling, para que sea compatible con el render to texture

            // Nota:
            // El render to Texture no es compatible con el multisampling en dx9
            // Por otra parte la mayor parte de las placas de ultima generacion no soportan
            // mutisampling para texturas de punto flotante con lo cual
            // hay que suponer con generalidad que no se puede usar multisampling y render to texture

            // Para resolverlo hay que crear un depth buffer que no tenga multisampling,
            // (de lo contrario falla el zbuffer y se producen artifacts tipicos de que no tiene zbuffer)

            // Si uno quisiera usar el multisampling, la tecnica habitual es usar un RenderTarget
            // en lugar de una textura.
            // Por ejemplo en c++:
            //
            // Render Target formato color buffer con multisampling
            //
            //  g_pd3dDevice->CreateRenderTarget(Ancho,Alto,
            //          D3DFMT_A8R8G8B8, D3DMULTISAMPLE_2_SAMPLES, 0,
            //          FALSE, &g_pRenderTarget, NULL);
            //
            // Luego, ese RenderTarget NO ES una textura, y nosotros necesitamos acceder a esos
            // pixeles, ahi lo que se hace es COPIAR del rendertartet a una textura,
            // para poder trabajar con esos datos en el contexto del Pixel shader:
            //
            // Eso se hace con la funcion StretchRect:
            // copia de rendertarget ---> sceneSurface (que es la superficie asociada a una textura)
            // g_pd3dDevice->StretchRect(g_pRenderTarget, NULL, g_pSceneSurface, NULL, D3DTEXF_NONE);
            //
            // Esta tecnica se llama downsampling
            // Y tiene el costo adicional de la transferencia de memoria entre el rendertarget y la
            // textura, pero que no traspasa los limites de la GPU. (es decir es muy performante)
            // no es lo mismo que lockear una textura para acceder desde la CPU, que tiene el problema
            // de transferencia via AGP.

            g_pDepthStencil =
                D3DDevice.Instance.Device.CreateDepthStencilSurface(
                    D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth,
                    D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight,
                    DepthFormat.D24S8, MultiSampleType.None, 0, true);

            // inicializo el render target
            g_pRenderTarget = new Texture(D3DDevice.Instance.Device,
                                          D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth
                                          , D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                          Format.X8R8G8B8, Pool.Default);

            effect.SetValue("g_RenderTarget", g_pRenderTarget);

            // inicializo el mapa de normales
            g_pNormals = new Texture(D3DDevice.Instance.Device,
                                     D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth
                                     , D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                     Format.A16B16G16R16F, Pool.Default);

            effect.SetValue("g_Normals", g_pNormals);

            // Resolucion de pantalla
            effect.SetValue("screen_dx", D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth);
            effect.SetValue("screen_dy", D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight);

            //Se crean 2 triangulos con las dimensiones de la pantalla con sus posiciones ya transformadas
            // x = -1 es el extremo izquiedo de la pantalla, x=1 es el extremo derecho
            // Lo mismo para la Y con arriba y abajo
            // la Z en 1 simpre
            CustomVertex.PositionTextured[] vertices =
            {
                new CustomVertex.PositionTextured(-1,  1, 1, 0, 0),
                new CustomVertex.PositionTextured(1,   1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1,  -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured),
                                        4, D3DDevice.Instance.Device, Usage.Dynamic | Usage.WriteOnly,
                                        CustomVertex.PositionTextured.Format, Pool.Default);
            g_pVBV3D.SetData(vertices, 0, LockFlags.None);
        }
Example #47
0
        ///<summary>
        ///    Authenticate multiple users
        ///</summary>

        private async Task <User> Authenticate()
        {
            User tempPhoto   = null;
            User targetUser  = null;
            var  txt         = new TextBlock();
            bool neverBroken = true;

            try
            {
                if (isCapturing == false)
                {
                    throw new Exception("Need to start Capturing");
                }
                if (isDetecting == true)
                {
                    throw new Exception("Detection is already running!");
                }
                isDetecting = true;

                string uniqueId = GenerateUniqueId();
                tempPhoto = await TakePhoto(uniqueId);

                tempPhoto.uniqueId = uniqueId;
                List <String> faceId_rectList = await MakeRequestFaceDetect(await ApplicationData.Current.TemporaryFolder.GetFileAsync(tempPhoto.uniqueId));

                foreach (string faceId_rect in faceId_rectList)
                {
                    tempPhoto.FaceId = faceId_rect.Split('_')[0];
                    Print("Ricerca volto corrispettivo...");
                    List <String> faceIds = new List <string>();
                    if (Users.Count > 0)
                    {
                        foreach (User u in Users)
                        {
                            faceIds.Add(u.FaceId);
                        }
                        List <String> foundFaceIds = await MakeRequestFindSimilar(tempPhoto.FaceId, faceIds);

                        Print("Match con l'utente...");
                        foreach (User u in Users)
                        {
                            foreach (String foundFaceId in foundFaceIds)
                            {
                                if (u.FaceId == foundFaceId)
                                {
                                    targetUser = u;
                                    break;
                                }
                            }
                        }
                    }
                    Image originalImage = new Image()
                    {
                        Width = 300, Source = tempPhoto.PhotoFace.Source
                    };
                    RectangleGeometry geo = new RectangleGeometry();
                    geo.Rect = new Rect(int.Parse(faceId_rect.Split('_')[2]) * 15 / 32, int.Parse(faceId_rect.Split('_')[1]) * 15 / 32, int.Parse(faceId_rect.Split('_')[3]) * 15 / 32, int.Parse(faceId_rect.Split('_')[4]) * 15 / 32);
                    tempPhoto.PhotoFace.Clip = geo;

                    if (targetUser == null)
                    {
                        await Say("ATTENZIONE! VOLTO NON AUTENTICATO! INSERISCI BIGLIETTO E PRONUNCIA 'BIGLIETTO INSERITO'");

                        neverBroken = false;
                        break;
                    }
                    else
                    {
                        photoContainer.Children.Add(targetUser.PhotoFace);
                        Grid.SetRow(targetUser.PhotoFace, photoContainer.RowDefinitions.Count - 1);
                        Grid.SetColumn(targetUser.PhotoFace, photoContainer.ColumnDefinitions.Count - 1);
                        txt.HorizontalAlignment = HorizontalAlignment.Center;
                        txt.VerticalAlignment   = VerticalAlignment.Bottom;
                        txt.Text = "Durata residua biglietto: " + targetUser.expirationDate.Subtract(DateTime.Now).ToString();
                        photoContainer.Children.Add(txt);
                        Grid.SetRow(txt, photoContainer.RowDefinitions.Count - 1);
                        Grid.SetColumn(txt, photoContainer.ColumnDefinitions.Count - 1);
                        await Say("Autenticato! Grazie!");

                        await Task.Delay(1000);

                        ResetAll();
                        tempPhoto.PhotoFace = originalImage;
                        photoContainer.Children.Add(tempPhoto.PhotoFace);
                        Grid.SetRow(tempPhoto.PhotoFace, 0);
                        Grid.SetColumn(tempPhoto.PhotoFace, 0);
                        targetUser = null;
                    }
                }
                var file = await ApplicationData.Current.TemporaryFolder.GetFileAsync(tempPhoto.uniqueId);

                await file.DeleteAsync();

                ResetAll();
                if (neverBroken)
                {
                    tempPhoto = null;
                }
            }
            catch (Exception ex)
            {
                Print(ex.Message);
            }
            finally
            {
                isDetecting = false;
            }
            return(tempPhoto);
        }
Example #48
0
        private void layoutOptionFive(List<String> _temporary)
        {
            mbordercontrol = new PaperBorderControl();

            mBorders = new List<Border>();

            mImagecontrol = new PaperImageControl();

            vImages = new List<Image>();

            cutLine();

            cut_line.Width = 660 + 180; //分割线加长

            imageleft = 130 - 85;

            borderleft = 120 - 85;
            // 载入选项
            for (int i = 0; i < _temporary.Count; i++)// 8 是选项 ps:在内部就可以显示border 放外部循环就不行
            {
                //border 
                b = mbordercontrol.GenBorder(102, 94);
                mBorders.Add(b);
                PapertestCanvas.Children.Add(b);


                //image
                im = new Image();

                im.Stretch = Stretch.Fill;

                System.Drawing.Image picc = System.Drawing.Image.FromFile("Paper\\PaperRes\\Test\\PaS\\" + _temporary[i] + ".bmp");
                System.Drawing.Bitmap bmpc = new System.Drawing.Bitmap(picc);

                IntPtr hBitmapc = bmpc.GetHbitmap();
                System.Windows.Media.ImageSource WpfBitmapc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmapc, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(82, 74));//FromEmptyOptions() 源图像大小
                im.Source = WpfBitmapc;

                //im = mImagecontrol.GetImage(82, 74);
                //BitmapImage bitim = new BitmapImage();
                //bitim.BeginInit();
                //bitim.UriSource = new Uri("\\PCAT;component\\Images\\" + _temporary[i] + ".bmp", UriKind.Relative);
                //bitim.EndInit();
                //im.Stretch = Stretch.Fill;
                //im.Source = bitim;
                vImages.Add(im);
                PapertestCanvas.Children.Add(im);

                //Event

                im.MouseDown += new MouseButtonEventHandler(im_MouseDown);
                im.MouseEnter += new MouseEventHandler(im_MouseEnter);
                im.MouseLeave += new MouseEventHandler(im_MouseLeave);

                
                    Canvas.SetTop(b, actual_y + bordertop);//
                    Canvas.SetLeft(b, actual_x + borderleft);// 
                    borderleft = borderleft + borderadd;

                    Canvas.SetTop(im, actual_y + imagetop);//
                    Canvas.SetLeft(im, actual_x + imageleft);//
                    imageleft = imageleft + imageadd;



                
            }//---for
        }
Example #49
0
        public bool ReadDataFromCsvFile(string filePath)
        {
            var meterPointCode       = new List <string>();
            var serialNumber         = new List <string>();
            var plantCode            = new List <string>();
            var dateTime             = new List <string>();
            var dataType             = new List <string>();
            var energy               = new List <string>();
            var maximumDemand        = new List <string>();
            var timeofMaxDemand      = new List <string>();
            var units                = new List <string>();
            var status               = new List <string>();
            var period               = new List <string>();
            var dlsActive            = new List <string>();
            var billingResetCount    = new List <string>();
            var billingResetDateTime = new List <string>();
            var rate = new List <string>();

            if (String.IsNullOrEmpty(filePath))
            {
                return(false);
            }
            using (var reader = new StreamReader($@"{filePath}"))
            {
                while (!reader.EndOfStream)
                {
                    var splits = reader.ReadLine()?.Split(',');
                    if (splits != null && splits.Length != 0)
                    {
                        meterPointCode.Add(splits[0]);
                        serialNumber.Add(splits[1]);
                        plantCode.Add(splits[2]);
                        dateTime.Add(splits[3]);
                        dataType.Add(splits[4]);
                        energy.Add(splits[5]);
                        maximumDemand.Add(splits[6]);
                        timeofMaxDemand.Add(splits[7]);
                        units.Add(splits[8]);
                        status.Add(splits[9]);
                        period.Add(splits[10]);
                        dlsActive.Add(splits[11]);
                        billingResetCount.Add(splits[12]);
                        billingResetDateTime.Add(splits[13]);
                        rate.Add(splits[14]);
                    }
                }
                MeterPointCodeList       = meterPointCode;
                SerialNumberList         = serialNumber;
                PlantCodeList            = plantCode;
                DateTimeList             = dateTime;
                DataTypeList             = dataType;
                EnergyList               = energy;
                MaximumDemandList        = maximumDemand;
                TimeofMaxDemandList      = timeofMaxDemand;
                UnitsList                = units;
                StatusList               = status;
                PeriodList               = period;
                DlsActiveList            = dlsActive;
                BillingResetCountList    = billingResetCount;
                BillingResetDateTimeList = billingResetDateTime;
                RateList = rate;
            }
            return(true);
        }
        private async Task <HttpResponseMessage> HttpResponseMessage(HttpRequest request, CancellationToken cancellationToken)
        {
            var queryBuilder = new StringBuilder(request.QueryUrl);

            if (request.QueryParameters != null)
            {
                ApiHelper.AppendUrlWithQueryParameters(queryBuilder, request.QueryParameters, ArrayDeserializationFormat, ParameterSeparator);
            }

            //validate and preprocess url
            string queryUrl = ApiHelper.CleanUrl(queryBuilder);

            HttpRequestMessage requestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(queryUrl),
                Method     = request.HttpMethod,
            };

            if (request.Headers != null)
            {
                foreach (var headers in request.Headers)
                {
                    requestMessage.Headers.TryAddWithoutValidation(headers.Key, headers.Value);
                }
            }

            if (!string.IsNullOrEmpty(request.Username))
            {
                var byteArray = Encoding.UTF8.GetBytes(request.Username + ":" + request.Password);
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                     Convert.ToBase64String(byteArray));
            }

            if (request.HttpMethod.Equals(HttpMethod.Delete) || request.HttpMethod.Equals(HttpMethod.Post) || request.HttpMethod.Equals(HttpMethod.Put) || request.HttpMethod.Equals(new HttpMethod("PATCH")))
            {
                bool multipartRequest = request.FormParameters != null &&
                                        (request.FormParameters.Any(f => f.Value is MultipartContent) || request.FormParameters.Any(f => f.Value is FileStreamInfo));

                if (request.Body != null)
                {
                    if (request.Body is FileStreamInfo file)
                    {
                        requestMessage.Content = new StreamContent(file.FileStream);
                        if (!string.IsNullOrWhiteSpace(file.ContentType))
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
                        }
                        else if (request.Headers.Any(h => h.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase)))
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(
                                request.Headers.First(h =>
                                                      h.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase)).Value);
                        }
                        else
                        {
                            requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        }
                    }
                    else if (request.Headers.ContainsKey("content-type") && string.Equals(request.Headers["content-type"],
                                                                                          "application/json; charset=utf-8", StringComparison.OrdinalIgnoreCase))
                    {
                        requestMessage.Content = new StringContent((string)request.Body ?? string.Empty, Encoding.UTF8,
                                                                   "application/json");
                    }
                    else if (request.Headers.ContainsKey("content-type"))
                    {
                        byte[] bytes = null;

                        if (request.Body is Stream)
                        {
                            Stream s = (Stream)request.Body;
                            using (BinaryReader br = new BinaryReader(s))
                            {
                                bytes = br.ReadBytes((int)s.Length);
                            }
                        }
                        else if (request.Body is byte[])
                        {
                            bytes = (byte[])request.Body;
                        }
                        else
                        {
                            bytes = Encoding.UTF8.GetBytes((string)request.Body);
                        }

                        requestMessage.Content = new ByteArrayContent(bytes ?? Array.Empty <byte>());

                        try
                        {
                            requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.Headers["content-type"]);
                        }
                        catch (Exception)
                        {
                            requestMessage.Content.Headers.TryAddWithoutValidation("content-type", request.Headers["content-type"]);
                        }
                    }
                    else
                    {
                        requestMessage.Content = new StringContent(request.Body.ToString() ?? string.Empty, Encoding.UTF8,
                                                                   "text/plain");
                    }
                }
                else if (multipartRequest)
                {
                    MultipartFormDataContent formContent = new MultipartFormDataContent();

                    foreach (var param in request.FormParameters)
                    {
                        if (param.Value is FileStreamInfo fileParam)
                        {
                            var fileContent = new MultipartFileContent(fileParam);
                            formContent.Add(fileContent.ToHttpContent(param.Key));
                        }
                        else if (param.Value is MultipartContent wrapperObject)
                        {
                            formContent.Add(wrapperObject.ToHttpContent(param.Key));
                        }
                        else
                        {
                            formContent.Add(new StringContent(param.Value.ToString()), param.Key);
                        }
                    }

                    requestMessage.Content = formContent;
                }
                else if (request.FormParameters != null)
                {
                    var parameters = new List <KeyValuePair <string, string> >();
                    foreach (var param in request.FormParameters)
                    {
                        parameters.Add(new KeyValuePair <string, string>(param.Key, param.Value.ToString()));
                    }
                    requestMessage.Content = new FormUrlEncodedContent(parameters);
                }
            }
            return(await client.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false));
        }
Example #51
0
        static void Main(string[] args)
        {
            //filename of script
            string filename = " ";
            string clientid;
            //ClientID random or user introduced
            int clientID = 0;
            //Type of algorithm
            string algorithm = "x"; // pre definido ou escolher no inicio?
            //Type of implementation
            string mode = "b";


            //PuppetMaster initialization

            if (args.Length == 5)
            {
                //if defined in script
                filename  = args[0];
                clientid  = args[1];
                algorithm = args[2];
                Servers.Add(args[3]);
                mode = args[4];
                Int32.TryParse(clientid, out clientID);
                Console.WriteLine(clientID);
            }
            if (args.Length == 4)
            {
                //if not defined in script
                Servers.Add("tcp://localhost:50001/S");
                filename  = args[0];
                clientid  = args[1];
                algorithm = args[2];
                mode      = args[3];
                Int32.TryParse(clientid, out clientID);
                Console.WriteLine(clientID);
            }
            //Command Line initialization with script
            if (args.Length == 1)
            {
                filename = args[0];
                Console.WriteLine("Introduza o numero unico do cliente");
                clientid = Console.ReadLine();

                Int32.TryParse(clientid, out clientID);
            }
            //Command Line initialization without a script
            if (args.Length == 0)
            {
                Console.WriteLine("Introduza o nome do script que pretende executar");
                filename = Console.ReadLine();
                Console.WriteLine("Introduza o numero unico do cliente");
                clientid = Console.ReadLine();

                Int32.TryParse(clientid, out clientID);
            }
            if (algorithm == "x")
            {
                if (mode == "a")
                {
                    ClientType = new AdvXL_Client(Servers, clientID);
                }
                if (mode == "b")
                {
                    ClientType = new XL_Client(Servers, clientID);
                }
            }
            if (algorithm == "s")
            {
                if (mode == "a")
                {
                    ClientType = new AdvSMR_Client(Servers, clientID);
                }
                if (mode == "b")
                {
                    ClientType = new SMR_Client(Servers, clientID);
                }
            }



            try
            {
                //Get the script from the script folder
                string filePath = AuxFunctions.GetProjPath() + "\\scripts\\Client\\" + filename;

                //Initializes a file executer to execute a script file, passes the client to execute the operations on
                FileExecuter exec = new FileExecuter(ClientType);

                //Executes the script file
                exec.ExecuteFile(filePath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            Console.ReadLine();
        }
Example #52
0
 public void AddEmployee(Employee empObj)
 {
     employees.Add(empObj);
     HeadCount++;
 }
Example #53
0
        public Cocept()
        {
            Relations relations = new Relations();

            Console.WriteLine("Матрица смежности:");
            for (int i = 0; i < relations.size; i++)
            {
                for (int j = 0; j < relations.size; j++)
                {
                    Console.Write(relations.matrix[i, j] + " ");
                }
                Console.WriteLine();
            }

            HashSet <List <int> > crossing = new HashSet <List <int> >();

            for (int i = 0; i < relations.size; i++)
            {
                List <int> tempCrossing = new List <int>();
                for (int j = 0; j < relations.size; j++)
                {
                    if (relations.matrix[j, i] == 1)
                    {
                        tempCrossing.Add(j + 1);
                    }
                }
                crossing.Add(tempCrossing);
            }

            while (true)
            {
                int flag = crossing.Count();

                for (int i = 0; i < crossing.Count; i++)
                {
                    for (int j = i + 1; j < crossing.Count; j++)
                    {
                        List <int> tempCrossing = new List <int>();
                        foreach (var item in crossing.ElementAt(i))
                        {
                            if (crossing.ElementAt(j).Contains(item))
                            {
                                tempCrossing.Add(item);
                            }
                        }
                        bool flag2 = true;
                        for (int l = 0; l < crossing.Count; l++)
                        {
                            if (tempCrossing.Count == crossing.ElementAt(l).Count)
                            {
                                for (int t = 0; t < crossing.ElementAt(l).Count; t++)
                                {
                                    if (!(crossing.ElementAt(l).Contains(tempCrossing[t])))
                                    {
                                        break;
                                    }
                                    flag2 = false;
                                }
                            }
                        }
                        if (flag2)
                        {
                            if (tempCrossing.Count == 0)
                            {
                                if (!(crossing.ElementAt(crossing.Count - 1).Count == 0))
                                {
                                    crossing.Add(tempCrossing);
                                }
                            }
                            else
                            {
                                crossing.Add(tempCrossing);
                            }
                        }
                    }
                }

                if (flag == crossing.Count())
                {
                    break;
                }
            }

            List <int> allElement = new List <int>();

            for (int i = 1; i < relations.size; i++)
            {
                allElement.Add(i);
            }

            bool flag4 = true;

            for (int l = 0; l < crossing.Count; l++)
            {
                if (allElement.Count == crossing.ElementAt(l).Count)
                {
                    for (int t = 0; t < crossing.ElementAt(l).Count; t++)
                    {
                        if (!(crossing.ElementAt(l).Contains(allElement[t])))
                        {
                            break;
                        }
                        flag4 = false;
                    }
                }
            }

            if (flag4)
            {
                crossing.Add(allElement);
            }

            List <List <List <int> > > neighbours = new List <List <List <int> > >();

            for (int i = 0; i < crossing.Count; i++)
            {
                neighbours.Add(new List <List <int> >());
                for (int j = 0; j < crossing.Count; j++)
                {
                    bool flag = true;
                    if (i != j)
                    {
                        for (int k = 0; k < crossing.ElementAt(i).Count; k++)
                        {
                            if (!(crossing.ElementAt(j).Contains(crossing.ElementAt(i)[k])))
                            {
                                flag = false;
                                break;
                            }
                        }
                    }
                    if (flag && i != j)
                    {
                        neighbours.ElementAt(i).Add(crossing.ElementAt(j));
                    }
                }
            }

            //идем по всем пересечениям
            for (int i = 0; i < crossing.Count; i++)
            {
                List <List <int> > temp = new List <List <int> >(neighbours.ElementAt(i));
                //по соседям пересечения
                for (int j = 0; j < temp.Count; j++)
                {
                    //ищем номер соседа в пересечении
                    int numb = 0;
                    for (int n = 0; n < crossing.Count; n++)
                    {
                        if (crossing.ElementAt(n).Count == temp[j].Count)
                        {
                            bool flag = true;
                            for (int l = 0; l < crossing.ElementAt(n).Count; l++)
                            {
                                if (!(crossing.ElementAt(n)[l] == temp[j][l]))
                                {
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag)
                            {
                                numb = n;
                                break;
                            }
                        }
                    }
                    for (int n = 0; n < neighbours.ElementAt(numb).Count; n++)
                    {
                        if (temp.Contains(neighbours.ElementAt(numb)[n]))
                        {
                            neighbours.ElementAt(i).Remove(neighbours.ElementAt(numb)[n]);
                        }
                    }
                }
            }

            List <List <List <int> > > levels = new List <List <List <int> > >();

            levels.Add(neighbours.ElementAt(neighbours.Count - 1));

            bool flag3 = true;

            while (flag3)
            {
                levels.Add(new List <List <int> >());
                for (int i = 0; i < levels.ElementAt(levels.Count - 2).Count; i++)
                {
                    int numb = 0;
                    for (int n = 0; n < crossing.Count; n++)
                    {
                        if (crossing.ElementAt(n).Count == levels.ElementAt(levels.Count - 2)[i].Count)
                        {
                            bool flag = true;
                            for (int l = 0; l < crossing.ElementAt(n).Count; l++)
                            {
                                if (!(crossing.ElementAt(n)[l] == levels.ElementAt(levels.Count - 2)[i][l]))
                                {
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag)
                            {
                                numb = n;
                                break;
                            }
                        }
                    }
                    for (int j = 0; j < neighbours.ElementAt(numb).Count; j++)
                    {
                        if (!(levels[levels.Count - 1].Contains(neighbours.ElementAt(numb)[j])))
                        {
                            levels[levels.Count - 1].Add(neighbours.ElementAt(numb)[j]);
                            if (neighbours.ElementAt(numb)[j].Count == relations.size)
                            {
                                flag3 = false;
                            }
                        }
                    }
                }
            }

            string alph = "abcdefghijklmnopqrstuvwxyz";

            for (int i = 0; i < levels.Count; i++)
            {
                Console.WriteLine("{0} уровень:", i);
                foreach (var item in levels[i])
                {
                    List <int> temp = new List <int>();
                    Console.Write("{");
                    foreach (var num in item)
                    {
                        Console.Write(num + " ");
                        temp.Add(num);
                    }
                    Console.Write("}");

                    Console.Write("{");
                    for (int j = 0; j < relations.size; j++)
                    {
                        bool flag = true;
                        for (int j2 = 0; j2 < temp.Count; j2++)
                        {
                            if (relations.matrix[temp[j2] - 1, j] == 0)
                            {
                                flag = false;
                            }
                        }
                        if (flag)
                        {
                            Console.Write(alph.ElementAt(j) + " ");
                        }
                    }
                    Console.Write("}");
                }
                Console.WriteLine();
            }

            int index = 0;

            foreach (var item in crossing)
            {
                Console.Write("{");
                foreach (var num in item)
                {
                    Console.Write(num + " ");
                }
                Console.Write("}:");
                foreach (var neigb in neighbours[index])
                {
                    Console.Write("{");
                    foreach (var num in neigb)
                    {
                        Console.Write(num + " ");
                    }
                    Console.Write("}");
                }
                Console.WriteLine();
                index++;
            }
        }
Example #54
0
    private void displayTable(object sender, EventArgs e, String s)
    {
        //initial set up...Counter for the number of rows, and 
        int countTotalJobs = 0;
        String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
        System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(connectionString);
        sc.Open();

        System.Data.SqlClient.SqlCommand countJobPostings = new System.Data.SqlClient.SqlCommand();



        //This indicates that all interest groups were selected/default!
        if (s.Equals(" "))
        {
            //default
            countJobPostings.CommandText = "SELECT count( SchoolApproval.OpportunityEntityID) FROM OpportunityEntity INNER JOIN SchoolApproval ON " +
                "OpportunityEntity.OpportunityEntityID = SchoolApproval.OpportunityEntityID where OpportunityEntity.OpportunityType = 'JOB' and schoolApproval.approvedflag = 'Y'" +
                " and SchoolApproval.SchoolEntityID = " + Session["schoolID"];


        }
        //This indicates that there were some interest groups that were selected in the drop down menu
        else
        {
            //have to utilize distinct due to the nature of data duplication with interest groups. Cannot have two cards that are exactly the same
            countJobPostings.CommandText = "SELECT COUNT(DISTINCT OpportunityEntity.OpportunityEntityID) AS Expr1 FROM OpportunityEntity INNER JOIN " +
                "OpportunityInterestGroups ON OpportunityEntity.OpportunityEntityID = OpportunityInterestGroups.OpportunityEntityID INNER JOIN  " +
                "InterestGroups ON OpportunityInterestGroups.InterestGroupID = InterestGroups.InterestGroupID INNER JOIN " +
                "SchoolApproval ON OpportunityEntity.OpportunityEntityID = SchoolApproval.OpportunityEntityID WHERE(OpportunityEntity.OpportunityType = 'JOB') " +
                "AND(SchoolApproval.SchoolEntityID = 12) AND(SchoolApproval.ApprovedFlag = 'Y') and (" + s + ")";

        }

        String test = s;

        countJobPostings.Connection = sc;
        System.Data.SqlClient.SqlDataReader reader = countJobPostings.ExecuteReader();




        while (reader.Read())
        {
            countTotalJobs = reader.GetInt32(0);
        }

        sc.Close();




        sc.Open();


        System.Data.SqlClient.SqlCommand pullJobInfo = new System.Data.SqlClient.SqlCommand();

        if (s.Equals(" "))
        {
            pullJobInfo.CommandText = "SELECT  Organization.OrganizationName, JobListing.JobTitle, JobListing.JobDescription," +
            " Organization.Image, Organization.ExternalLink, JobListing.Location, JobListing.Deadline, JobListing.NumOfApplicants, Organization.OrganizationDescription," +
            " JobListing.JobListingID FROM SchoolApproval INNER JOIN OpportunityEntity ON SchoolApproval.OpportunityEntityID = OpportunityEntity.OpportunityEntityID INNER JOIN JobListing" +
            " ON OpportunityEntity.OpportunityEntityID = JobListing.JobListingID INNER JOIN Organization ON JobListing.OrganizationID = Organization.OrganizationEntityID " +
            "where SchoolApproval.ApprovedFlag = 'Y' and OpportunityEntity.OpportunityType = 'JOB' and SchoolApproval.SchoolEntityID = " + Session["schoolID"];

        }
        else
        {
            pullJobInfo.CommandText = "SELECT distinct Organization.OrganizationName, JobListing.JobTitle, JobListing.JobDescription, Organization.Image, " +
                "Organization.ExternalLink, JobListing.Location, JobListing.Deadline, JobListing.NumOfApplicants, Organization.OrganizationDescription, " +
                "JobListing.JobListingID FROM " +
                "SchoolApproval INNER JOIN OpportunityEntity ON SchoolApproval.OpportunityEntityID = OpportunityEntity.OpportunityEntityID INNER JOIN JobListing ON " +
                "OpportunityEntity.OpportunityEntityID = JobListing.JobListingID INNER JOIN Organization ON JobListing.OrganizationID = Organization.OrganizationEntityID INNER JOIN " +
                " OpportunityInterestGroups ON OpportunityEntity.OpportunityEntityID = OpportunityInterestGroups.OpportunityEntityID WHERE(SchoolApproval.ApprovedFlag = 'Y') AND OpportunityEntity.OpportunityType = 'JOB' and " +
                "(SchoolApproval.SchoolEntityID = 12) and (" + s + ")";

        }



        pullJobInfo.Connection = sc;



        reader = pullJobInfo.ExecuteReader();

        {

            //Make the list
            List<JobListing> jobs = new List<JobListing>();


            int jobListingID;
            String orgName;
            String jobTitle;
            String jobDescription;
            String image;
            String link;
            String jobLocation;
            int numOfApplicants;
            String organizationDescription;
            DateTime deadline;


            int x = 0;
            while (reader.Read())
            {

                orgName = reader.GetString(0);
                jobTitle = reader.GetString(1);
                jobDescription = reader.GetString(2);
                image = reader.GetString(3);
                link = reader.GetString(4);
                jobLocation = reader.GetString(5);
                deadline = reader.GetDateTime(6);
                numOfApplicants = reader.GetInt32(7);
                organizationDescription = reader.GetString(8);
                jobListingID = reader.GetInt32(9);
                x++;

                JobListing job = new JobListing(jobTitle, jobDescription, jobLocation, deadline, numOfApplicants, orgName, organizationDescription,
                    image, link);
                //Set this to be used later
                job.setID(jobListingID);
                //Make the object
                //Add to list
                jobs.Add(job);

            }
            sc.Close();
            double doubleRows = countTotalJobs / 3.0;
            int numrows = (int)(Math.Ceiling(doubleRows));
            int numcells = 3;
            int count = 0;
            for (int j = 0; j < numrows; j++)
            {
                TableRow r = new TableRow();


                for (int i = 0; i < numcells; i++)
                {
                    if (count == countTotalJobs)
                    {
                        break;
                    }
                    TableCell c = new TableCell();

                    LinkButton referralLink = new LinkButton();
                    referralLink.ID = "referralLink" + count;

                    referralLink.CssClass = "far fa-paper-plane";

                    referralLink.CommandArgument += jobs[count].getID();
                    referralLink.Command += new CommandEventHandler(this.referralButton_Click);

                    c.Controls.Add(new LiteralControl("<div class='image-flip' ontouchstart='this.classList.toggle('hover');'>"));
                    c.Controls.Add(new LiteralControl("<div class='mainflip'>"));
                    c.Controls.Add(new LiteralControl("<div class='frontside'>"));
                    c.Controls.Add(new LiteralControl("<div class='card'>"));
                    c.Controls.Add(new LiteralControl("<div class='card-body text-center'>"));
                    c.Controls.Add(new LiteralControl("<p><img class='img-fluid' src='" + jobs[count].getOrgImage() + "' alt='card image'></p>"));
                    c.Controls.Add(new LiteralControl("<h4 class='card-title'>" + jobs[count].getOrgName() + "</h4>"));
                    c.Controls.Add(new LiteralControl("<p class='card-text'>" + jobs[count].getJobTitle() + "</p>"));
                    c.Controls.Add(new LiteralControl("<a href='#' class='btn btn-primary btn-sm'><i class='fa fa-plus'></i></a>"));
                    c.Controls.Add(new LiteralControl("</div>"));
                    c.Controls.Add(new LiteralControl("</div>"));
                    c.Controls.Add(new LiteralControl("</div>"));

                    c.Controls.Add(new LiteralControl("<div class='backside'>"));
                    c.Controls.Add(new LiteralControl("<div class='card'>"));
                    c.Controls.Add(new LiteralControl("<div class='card-body text-center'>"));
                    c.Controls.Add(new LiteralControl("<h4 class='card-title'>" + jobs[count].getOrgName() + "</h4>"));
                    c.Controls.Add(new LiteralControl("<p class='card-text'>" + jobs[count].getJobTitle() + "</p>"));
                    c.Controls.Add(new LiteralControl("<p class='card-text'> Location: " + jobs[count].getJobLocation() + "</p>"));
                    c.Controls.Add(new LiteralControl("<p class='card-text'>  Deadline: " + jobs[count].getJobDeadline().ToString() + "</p>"));
                    c.Controls.Add(new LiteralControl("<p class='card-text'>  Number of Applicants: " + jobs[count].getNumOfApplicants() + "</p>"));
                    c.Controls.Add(new LiteralControl("<ul class='list-inline'>"));
                    c.Controls.Add(new LiteralControl("<li class='list-inline-item'>"));
                    c.Controls.Add(new LiteralControl("<a class='social-icon text-xs-center' target='_blank' href='" + jobs[count].getOrgWebsite() + "'>"));
                    c.Controls.Add(new LiteralControl("<i class='fas fa-external-link-alt'></i>&nbsp;&nbsp;&nbsp;"));
                    //c.Controls.Add(referralLink);
                    c.Controls.Add(new LiteralControl("</a>"));
                    c.Controls.Add(new LiteralControl("</li>"));
                    c.Controls.Add(new LiteralControl("</ul>"));
                    c.Controls.Add(new LiteralControl("</div>"));
                    c.Controls.Add(new LiteralControl("</div>"));
                    c.Controls.Add(new LiteralControl("</div>"));
                    c.Controls.Add(new LiteralControl("</div>"));
                    c.Controls.Add(new LiteralControl("</div>"));

                    c.Style.Add("width", "33%");
                    r.Cells.Add(c);
                    count++;

                }
                jobPostingTable.Rows.Add(r);
            }


        }
    }
Example #55
0
 public void Push(string output, MockOutputMessageType type, ConsoleColor?color)
 {
     _outputs.Add(new MockOutputMessage(output, type, color));
 }
        public override void SetUpSteps()
        {
            base.SetUpSteps();

            AddStep("set local user", () => ((DummyAPIAccess)API).LocalUser.Value = UserLookupCache.GetUserAsync(1).GetResultSafely());

            AddStep("create leaderboard", () =>
            {
                leaderboard?.Expire();

                OsuScoreProcessor scoreProcessor;
                Beatmap.Value = CreateWorkingBeatmap(Ruleset.Value);

                var playableBeatmap  = Beatmap.Value.GetPlayableBeatmap(Ruleset.Value);
                var multiplayerUsers = new List <MultiplayerRoomUser>();

                foreach (int user in users)
                {
                    SpectatorClient.SendStartPlay(user, Beatmap.Value.BeatmapInfo.OnlineID);
                    var roomUser = OnlinePlayDependencies.MultiplayerClient.AddUser(new APIUser {
                        Id = user
                    }, true);

                    roomUser.MatchState = new TeamVersusUserState
                    {
                        TeamID = RNG.Next(0, 2)
                    };

                    multiplayerUsers.Add(roomUser);
                }

                Children = new Drawable[]
                {
                    scoreProcessor = new OsuScoreProcessor(),
                };

                scoreProcessor.ApplyBeatmap(playableBeatmap);

                LoadComponentAsync(leaderboard = new MultiplayerGameplayLeaderboard(scoreProcessor, multiplayerUsers.ToArray())
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }, gameplayLeaderboard =>
                {
                    LoadComponentAsync(new MatchScoreDisplay
                    {
                        Team1Score = { BindTarget = leaderboard.TeamScores[0] },
                        Team2Score = { BindTarget = leaderboard.TeamScores[1] }
                    }, Add);

                    LoadComponentAsync(gameplayScoreDisplay = new GameplayMatchScoreDisplay
                    {
                        Anchor     = Anchor.BottomCentre,
                        Origin     = Anchor.BottomCentre,
                        Team1Score = { BindTarget = leaderboard.TeamScores[0] },
                        Team2Score = { BindTarget = leaderboard.TeamScores[1] }
                    }, Add);

                    Add(gameplayLeaderboard);
                });
            });

            AddUntilStep("wait for load", () => leaderboard.IsLoaded);
            AddUntilStep("wait for user population", () => MultiplayerClient.CurrentMatchPlayingUserIds.Count > 0);
        }
        public string GetCss(HttpContext context, 
            string getp, 
            ref string pageId)
        {
            string output = null;
            
                    #region Search/Save path
                    //Get the list of files specified in the FileSet
                    List<string> fileNames = new List<string>();

                    // Get CssPaths in web.config
                    DataPageSection config =
                        (DataPageSection)System.Configuration.ConfigurationManager.GetSection(
                                              "DataPageHolderGroup/DataPageHolder");

                    // Load CssPaths in web.config
                    if (config.enable) {
                        CssElementCollection cssElements = null;
                        CssElementCollection masterCssElements = null;
                        // Find page css paths
                        foreach (PageElement cssPage in config.Pages) {
                            if (cssPage.pagePath.ToLower() == getp.ToLower())
                            {
                                cssElements = cssPage.Csss;
                            }

                            if (cssPage.pagePath.ToLower() == "~/MasterPage.master".ToLower()) {
                                masterCssElements = cssPage.Csss;
                            }

                        }

                        // Load master css paths
                        if (masterCssElements != null) {
                            foreach (CssElement css in masterCssElements) {
                                if (css.Name != "CssIe6") {
                                    fileNames.Add(css.Path);
                                } else {
                                    // IE6 Fix
                                    if (context.Request.Browser.Type.Equals("IE6")) {
                                        fileNames.Add(css.Path);
                                        // Change pageid (create new cache for IE6)
                                        pageId += "-IE6";
                                    }
                                }
                            }
                        }

                        // Load css paths
                        if (cssElements != null) {
                            foreach (CssElement css in cssElements) {
                                fileNames.Add(css.Path);
                            }
                        }
                    }
                    #endregion

                    // loop all files
                    if (fileNames.Count > 0)
                    {

                        //Write each files
                        foreach (string file in fileNames)
                        {


                            // Create a request using a URL
                            StreamReader getStream = File.OpenText(context.Request.MapPath(file));

                            output += getStream.ReadToEnd();

                            getStream.Dispose();
                            getStream.Close();


                        }

                        fileNames.Clear();

                        return output;
                    }

                    return null;
        }
Example #58
0
        private void Update()
        {
            List <Quest> pendingCompletedQuests = new List <Quest>();

            foreach (var quest in activeQuests)
            {
                if (quest.GoalsAchieved())
                {
                    pendingCompletedQuests.Add(quest);
                }
            }

            foreach (var quest in pendingCompletedQuests)
            {
                activeQuests.Remove(quest);
                completedQuests.Add(quest);

                foreach (var item in quest.itemsToCollect)
                {
                    RemoveFromInventory(item);
                }

                GiveExpToPlayer(quest.givesExp);
                notificationsPanel.AddMessage("Quest completed!");
                FMODUnity.RuntimeManager.PlayOneShot(questCompleteSound);
            }

            switch (state)
            {
            case State.MainMenu:
            case State.PlayerDead:
            case State.DialogChoice:
                break;

            case State.InGameMenu:
                if (Input.GetButtonDown("Cancel"))
                {
                    state = State.Gameplay;
                }
                break;

            case State.QuestsPanel:
                if (Input.GetButtonDown("Quests") || Input.GetButtonDown("Cancel"))
                {
                    state = State.Gameplay;
                }
                break;

            case State.Gameplay:
                if (playerState.health <= 0.0f)
                {
                    state = State.PlayerDead;
                }
                if (Input.GetButtonDown("Quests"))
                {
                    state = State.QuestsPanel;
                }
                if (Input.GetButtonDown("Cancel"))
                {
                    state = State.InGameMenu;
                }
                break;

            case State.DialogMessage:
                if (Input.GetButtonDown("Submit") || Input.GetButtonDown("Cancel") || Input.GetButtonDown("Fire1"))
                {
                    state = State.Gameplay;
                    if (mNextQuestElement)
                    {
                        mNextQuestElement.Run();
                    }
                }
                break;
            }

            particleManager.Update();
        }
Example #59
0
    void OnGUI()
    {
        if (Time.time % 2 < 1)
        {
            success = callBack.getResult();
        }
        // For Setting Up ResponseBox.
        GUI.TextArea(new Rect(10, 5, 1300, 175), success);

        //======================================{{{{************}}}}================================
        if (GUI.Button(new Rect(50, 200, 200, 30), "SaveUserScore"))
        {
            App42Log.SetDebug(true);
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.SaveUserScore(cons.gameName, cons.userName, userScore, callBack);
        }

        //======================================{{{{************}}}}=================================
        if (GUI.Button(new Rect(260, 200, 200, 30), "GetScoresByUser"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetScoresByUser(cons.gameName, cons.userName, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(470, 200, 200, 30), "GetHighestScoreByUser"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetHighestScoreByUser(cons.gameName, cons.userName, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(680, 200, 200, 30), "GetLowestScoreByUser"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetLowestScoreByUser(cons.gameName, cons.userName, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(890, 200, 200, 30), "GetTopRankings"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetTopRankings(cons.gameName, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(50, 250, 200, 30), "GetAverageScoreByUser"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetAverageScoreByUser(cons.gameName, cons.userName, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(260, 250, 200, 30), "GetLastScoreByUser"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetLastScoreByUser(cons.gameName, cons.userName, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(470, 250, 200, 30), "GetTopRankings"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetTopRankings(cons.gameName, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(680, 250, 200, 30), "GetTopNRankings"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetTopNRankings(cons.gameName, max, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(890, 250, 200, 30), "GetTopNRankers"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            scoreBoardService.GetTopNRankers(cons.gameName, max, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(50, 300, 200, 30), "GetTopRankingsByGroup"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            IList <string> userList = new List <string> ();
            userList.Add(cons.userName);
            userList.Add(cons.userName1);
            scoreBoardService.GetTopRankingsByGroup(cons.gameName, userList, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(260, 300, 200, 30), "GetTopNRankersByGroup"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            IList <string> userList = new List <string> ();
            userList.Add(cons.userName);
            userList.Add(cons.userName1);
            scoreBoardService.GetTopNRankersByGroup(cons.gameName, userList, callBack);
        }

        //======================================{{{{************}}}}==========================================
        if (GUI.Button(new Rect(470, 300, 200, 30), "EditScoreValueById"))
        {
            scoreBoardService = sp.BuildScoreBoardService();              // Initializing ScoreBoard Service.
            IList <string> userList = new List <string> ();
            userList.Add(cons.userName);
            userList.Add(cons.userName1);
            scoreBoardService.EditScoreValueById(cons.scoreId, userScore, callBack);
        }
    }
Example #60
0
        public ActionResult List()
        {
            OperationResult resul   = new OperationResult(OperationResultType.Error);
            GridRequest     request = new GridRequest(Request);
            string          storeId = Request["StoreId"];
            Expression <Func <StoreProductCollocation, bool> > predicate = FilterHelper.GetExpression <StoreProductCollocation>(request.FilterGroup);
            var spd        = _storeProductCollocationContract.StoreProductCollocations.Where(predicate).Where(x => x.CollocationName != "").Include(x => x.Operator).ToList();
            var filterList = new List <StoreProductCollocation>();

            if (!string.IsNullOrEmpty(storeId) && storeId != "0")
            {
                foreach (var item in spd)
                {
                    var arry = GetStoreNameArry(item.StoreId);
                    if (arry.Contains(storeId))
                    {
                        filterList.Add(item);
                    }
                }
            }
            else
            {
                filterList = spd.ToList();
            }
            int count  = filterList.ToList().Count();
            var source = filterList.OrderByDescending(c => c.CreatedTime)
                         .Skip(request.PageCondition.PageIndex)
                         .Take(request.PageCondition.PageSize);
            List <object> lis = new List <object>();

            foreach (var item in source)
            {
                if (item.Guid != null)
                {
                    var id         = _storeProductCollocationContract.StoreProductCollocations.Where(o => o.Guid == item.Guid).Select(x => x.Id).FirstOrDefault();
                    var querySouce = from Chitem in _storeCollocationInfoContract.StoreCollocationInfos
                                     join product in _productContract.Products on Chitem.ProductOrigNumberId equals product.Id into Joinitem
                                     from product in Joinitem.DefaultIfEmpty()
                                     where Chitem.IsDeleted == item.IsDeleted && Chitem.IsEnabled == item.IsEnabled &&
                                     Chitem.StoreCollocationId == id
                                     select new
                    {
                        Chitem.Id,
                        product.ThumbnailPath,
                        product.ProductNumber,
                        product.ProductOriginNumber,
                        product.Size,
                        product.Color,
                        product.CreatedTime,
                        product.IsDeleted,
                        product.IsEnabled,
                        Chitem.Operator
                    };



                    var da = querySouce.OrderByDescending(c => c.Id)
                             .Select(c => new
                    {
                        Id       = "childStore" + c.Id,
                        ParentId = "par" + id,
                        Guid     = "",
                        c.ThumbnailPath,
                        CollocationName = c.ProductNumber,
                        c.ProductOriginNumber.TagPrice,
                        StoreId     = "",
                        CreatedTime = c.CreatedTime,
                        c.IsDeleted,
                        c.IsEnabled,
                        c.Operator.Member.MemberName
                    }).ToList();
                    int childCount = da.ToList().Count();
                    count += childCount;
                    var par = new
                    {
                        Id              = "par" + item.Id,
                        Guid            = item.Guid,
                        ParentId        = "",
                        ThumbnailPath   = item.ThumbnailPath,
                        CollocationName = item.CollocationName,
                        count           = childCount,
                        TagPrice        = "",
                        StoreId         = GetCount(item.StoreId),
                        CreatedTime     = item.CreatedTime,
                        item.IsDeleted,
                        item.IsEnabled,
                        MemberName = item.Operator == null ? "" : item.Operator.Member.MemberName
                    };
                    lis.Add(par);
                    lis.AddRange(da);
                }
                else
                {
                    var par = new
                    {
                        Id              = "par" + item.Id,
                        Guid            = item.Guid,
                        ParentId        = "",
                        ThumbnailPath   = item.ThumbnailPath,
                        CollocationName = item.CollocationName,
                        count           = 0,
                        TagPrice        = "",
                        StoreId         = GetCount(item.StoreId),
                        CreatedTime     = item.CreatedTime,
                        item.Operator.Member.MemberName
                    };
                    lis.Add(par);
                }
            }
            GridData <object> data = new GridData <object>(lis, count, request.RequestInfo);

            return(Json(data, JsonRequestBehavior.AllowGet));
        }