/// <summary>
        /// Sends the specified request URI string.
        /// </summary>
        /// <param name="requestUriString">The request URI string.</param>
        /// <param name="method">The method.</param>
        /// <param name="queryStringData">The query string data.</param>
        /// <param name="formData">The form data.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static RockWebResponse Send( string requestUriString, string method, Dictionary<string, string> queryStringData, Dictionary<string, string> formData )
        {
            string uri = requestUriString;

            if ( queryStringData != null )
            {
                string parms = queryStringData.Join( "&" );
                if ( parms.Trim() != string.Empty )
                    uri += ( uri.Contains( "?" ) ? "&" : "?" ) + parms;
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( uri );

            request.Method = method;

            if ( formData != null && formData.Count > 0 )
            {
                byte[] postData = ASCIIEncoding.ASCII.GetBytes( formData.Join( "&" ) );

                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write( postData, 0, postData.Length );
                requestStream.Close();
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                return new RockWebResponse( response.StatusCode, GetResponseString( response.GetResponseStream() ) );
            }
            catch ( WebException webException )
            {
                string message = GetResponseString( webException.Response.GetResponseStream() );
                throw new Exception( webException.Message + " - " + message );
            }
        }
Example #2
0
        /// <summary>
        /// Binds the registrations grid.
        /// </summary>
        private void BindRegistrationsGrid()
        {
            int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull();
            if ( instanceId.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) );

                    var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value );
                    _instanceHasCost = instance != null && instance.RegistrationTemplate.Cost > 0.0m;

                    var qry = new RegistrationService( rockContext )
                        .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" )
                        .AsNoTracking()
                        .Where( r => r.RegistrationInstanceId == instanceId.Value );

                    if ( drpRegistrationDateRange.LowerValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value );
                    }
                    if ( drpRegistrationDateRange.UpperValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) )
                    {
                        string pfname = tbRegistrationRegisteredByFirstName.Text;
                        qry = qry.Where( r =>
                            r.FirstName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.NickName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.FirstName.StartsWith( pfname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) )
                    {
                        string plname = tbRegistrationRegisteredByLastName.Text;
                        qry = qry.Where( r =>
                            r.LastName.StartsWith( plname ) ||
                            r.PersonAlias.Person.LastName.StartsWith( plname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) )
                    {
                        string rfname = tbRegistrationRegistrantFirstName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.NickName.StartsWith( rfname ) ||
                                p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) )
                    {
                        string rlname = tbRegistrationRegistrantLastName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.LastName.StartsWith( rlname ) ) );
                    }

                    // If filtering on payment status, need to do some sub-querying...
                    if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null )
                    {
                        // Get all the registrant costs
                        var rCosts = new Dictionary<int, decimal>();
                        qry
                            .Select( r => new
                            {
                                RegistrationId = r.Id,
                                Costs = r.Registrants.Sum( p => p.Cost ),
                                Fees = r.Registrants.SelectMany( p => p.Fees ).Sum( f => f.Cost )
                            } ).ToList()
                            .ForEach( c =>
                                rCosts.AddOrReplace( c.RegistrationId, c.Costs + c.Fees ) );

                        var rPayments = new Dictionary<int, decimal>();
                        new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                rCosts.Keys.Contains( d.EntityId.Value ) )
                            .Select( d => new
                            {
                                RegistrationId = d.EntityId.Value,
                                Payment = d.Amount
                            } )
                            .ToList()
                            .GroupBy( d => d.RegistrationId )
                            .Select( d => new
                            {
                                RegistrationId = d.Key,
                                Payments = d.Sum( p => p.Payment )
                            } )
                            .ToList()
                            .ForEach( p =>
                                rPayments.AddOrReplace( p.RegistrationId, p.Payments ) );

                        var rPmtSummary = rCosts
                            .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new
                            {
                                RegistrationId = c.Key,
                                Costs = c.Value,
                                Payments = p.Value
                            } )
                            .ToList();

                        var ids = new List<int>();

                        if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" )
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs <= r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }
                        else
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs > r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }

                        qry = qry.Where( r => ids.Contains( r.Id ) );
                    }

                    IOrderedQueryable<Registration> orderedQry = null;
                    SortProperty sortProperty = gRegistrations.SortProperty;
                    if ( sortProperty != null )
                    {
                        orderedQry = qry.Sort( sortProperty );
                    }
                    else
                    {
                        orderedQry = qry.OrderByDescending( r => r.CreatedDateTime );
                    }

                    gRegistrations.SetLinqDataSource( orderedQry );

                    // Get all the payments for any registrations being displayed on the current page.
                    // This is used in the RowDataBound event but queried now so that each row does
                    // not have to query for the data.
                    var currentPageRegistrations = gRegistrations.DataSource as List<Registration>;
                    if ( currentPageRegistrations != null && registrationEntityType != null )
                    {
                        var registrationIds = currentPageRegistrations
                            .Select( r => r.Id )
                            .ToList();

                        RegistrationPayments = new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                registrationIds.Contains( d.EntityId.Value ) )
                            .ToList();
                    }

                    gRegistrations.DataBind();
                }
            }
        }
        /// <summary>
        /// Binds the registrations grid.
        /// </summary>
        private void BindRegistrationsGrid()
        {
            int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull();
            if ( instanceId.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) );

                    var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value );
                    decimal cost = instance.RegistrationTemplate.Cost;
                    if ( instance.RegistrationTemplate.SetCostOnInstance ?? false )
                    {
                        cost = instance.Cost ?? 0.0m;
                    }
                    _instanceHasCost = cost > 0.0m;

                    var qry = new RegistrationService( rockContext )
                        .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" )
                        .AsNoTracking()
                        .Where( r =>
                            r.RegistrationInstanceId == instanceId.Value &&
                            !r.IsTemporary );

                    if ( drpRegistrationDateRange.LowerValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value );
                    }
                    if ( drpRegistrationDateRange.UpperValue.HasValue )
                    {
                        qry = qry.Where( r =>
                            r.CreatedDateTime.HasValue &&
                            r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) )
                    {
                        string pfname = tbRegistrationRegisteredByFirstName.Text;
                        qry = qry.Where( r =>
                            r.FirstName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.NickName.StartsWith( pfname ) ||
                            r.PersonAlias.Person.FirstName.StartsWith( pfname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) )
                    {
                        string plname = tbRegistrationRegisteredByLastName.Text;
                        qry = qry.Where( r =>
                            r.LastName.StartsWith( plname ) ||
                            r.PersonAlias.Person.LastName.StartsWith( plname ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) )
                    {
                        string rfname = tbRegistrationRegistrantFirstName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.NickName.StartsWith( rfname ) ||
                                p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) );
                    }

                    if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) )
                    {
                        string rlname = tbRegistrationRegistrantLastName.Text;
                        qry = qry.Where( r =>
                            r.Registrants.Any( p =>
                                p.PersonAlias.Person.LastName.StartsWith( rlname ) ) );
                    }

                    // If filtering on payment status, need to do some sub-querying...
                    if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null )
                    {
                        // Get all the registrant costs
                        var rCosts = new Dictionary<int, decimal>();
                        qry.ToList()
                            .Select( r => new
                            {
                                RegistrationId = r.Id,
                                DiscountCosts = r.Registrants.Sum( p => (decimal?)( p.DiscountedCost( r.DiscountPercentage, r.DiscountAmount) ) ) ?? 0.0m,
                            } ).ToList()
                            .ForEach( c =>
                                rCosts.AddOrReplace( c.RegistrationId, c.DiscountCosts ) );

                        var rPayments = new Dictionary<int, decimal>();
                        new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                rCosts.Keys.Contains( d.EntityId.Value ) )
                            .Select( d => new
                            {
                                RegistrationId = d.EntityId.Value,
                                Payment = d.Amount
                            } )
                            .ToList()
                            .GroupBy( d => d.RegistrationId )
                            .Select( d => new
                            {
                                RegistrationId = d.Key,
                                Payments = d.Sum( p => p.Payment )
                            } )
                            .ToList()
                            .ForEach( p =>
                                rPayments.AddOrReplace( p.RegistrationId, p.Payments ) );

                        var rPmtSummary = rCosts
                            .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new
                            {
                                RegistrationId = c.Key,
                                Costs = c.Value,
                                Payments = p.Value
                            } )
                            .ToList();

                        var ids = new List<int>();

                        if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" )
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs <= r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }
                        else
                        {
                            ids = rPmtSummary
                                .Where( r => r.Costs > r.Payments )
                                .Select( r => r.RegistrationId )
                                .ToList();
                        }

                        qry = qry.Where( r => ids.Contains( r.Id ) );
                    }

                    SortProperty sortProperty = gRegistrations.SortProperty;
                    if ( sortProperty != null )
                    {
                        // If sorting by Total Cost or Balance Due, the database query needs to be run first without ordering,
                        // and then ordering needs to be done in memory since TotalCost and BalanceDue are not databae fields.
                        if ( sortProperty.Property == "TotalCost" )
                        {
                            if ( sortProperty.Direction == SortDirection.Ascending )
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.TotalCost ).AsQueryable() );
                            }
                            else
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.TotalCost ).AsQueryable() );
                            }
                        }
                        else if ( sortProperty.Property == "BalanceDue" )
                        {
                            if ( sortProperty.Direction == SortDirection.Ascending )
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.BalanceDue ).AsQueryable() );
                            }
                            else
                            {
                                gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.BalanceDue ).AsQueryable() );
                            }
                        }
                        else
                        {
                            gRegistrations.SetLinqDataSource( qry.Sort( sortProperty ) );
                        }
                    }
                    else
                    {
                        gRegistrations.SetLinqDataSource( qry.OrderByDescending( r => r.CreatedDateTime ) );
                    }

                    // Get all the payments for any registrations being displayed on the current page.
                    // This is used in the RowDataBound event but queried now so that each row does
                    // not have to query for the data.
                    var currentPageRegistrations = gRegistrations.DataSource as List<Registration>;
                    if ( currentPageRegistrations != null && registrationEntityType != null )
                    {
                        var registrationIds = currentPageRegistrations
                            .Select( r => r.Id )
                            .ToList();

                        RegistrationPayments = new FinancialTransactionDetailService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( d =>
                                d.EntityTypeId.HasValue &&
                                d.EntityId.HasValue &&
                                d.EntityTypeId.Value == registrationEntityType.Id &&
                                registrationIds.Contains( d.EntityId.Value ) )
                            .ToList();
                    }

                    var discountCodeHeader = gRegistrations.Columns.GetColumnByHeaderText( "Discount Code" );
                    if ( discountCodeHeader != null )
                    {
                        discountCodeHeader.Visible = GetAttributeValue( "DisplayDiscountCodes" ).AsBoolean();
                    }

                    gRegistrations.DataBind();
                }
            }
        }
Example #4
0
        public void RunLinqs()
        {
            IEnumerable<int> tablica = new int[] {2, 4, 3, 5, 2, 3};

            var lista = tablica.ToList(); // gen lista
            // List<int>

            int[] tabOfInts = {1, 2, 3, 1, 5, 4, 3};

            int sum = tabOfInts.Sum(); // 19

            var result = lista.Where(item => item == 3);// 2

            lista.Add(3);
            lista.Add(3);
            lista.Add(3);
            lista.Add(3);
            lista.Add(3);

            var icoteraz = result.ToArray();

            var ile = icoteraz.Length; // 7 !!!!

            lista.Add(3);

            var final = result.ToArray();

            Dictionary<string, string> klienci = new Dictionary<string, string>
            {
                { "30102061274627621478132", "Jas wedrowniczek"},
                { "30105061274627621478132", "Jas fasola"},
                { "30103061274627621478132", "johnny english"},
                { "30107061274627621478132", "jan kowalski"},
            };

            Dictionary<string, string> banki = new Dictionary<string, string>
            {
                { "1020", "Ing"},
                { "1030", "Pko"},
                { "1040", "nordea"},
                { "1050", "mbank"},
            };

            var chosenbank = banki.Where(item => item.Value == "mbank").Select(item => new MyExampleOfHomework());//string.Format("{0} to kod banku {1}", item.Key, item.Value));

            //banki.Add("1020", "dsfsdfasd");
            banki.Add("1060", "bzwbk");

            //IEqualityComparer<string> dsa;

            //dsa.

            var jazda = chosenbank.ToArray();
            //  nr konta , nazwa banku, klient
            var wynik = klienci.Join(
                banki,
                klienciSelector => klienciSelector.Key.Substring(2, 4),
                bankiSelector => bankiSelector.Key,
                (klient, bank) => new BankTransfer {Konto = klient.Key, NazwaBanku = bank.Value, Klient = klient.Value});

            var testhaha = wynik.Count();

            klienci.Add("121111", "szyfrant");
        }
        public static IDictionary<string, int> StringValuesAndEnumInts( this Enum value )
        {
            IDictionary<string, int> ret = new Dictionary<string, int>();

            Type type = value.GetType();
            IDictionary<string, string> valuesText = new Dictionary<string, string>();
            //Look for our string value associated with fields in this enum
            foreach ( FieldInfo fi in type.GetFields() ) {
                //Check for our custom attribute
                StringValueAttribute[] attrs = fi.GetCustomAttributes( typeof( StringValueAttribute ), false ) as StringValueAttribute[];
                if ( attrs.Length > 0 ) {
                    valuesText.Add( attrs[0].StringValue, fi.Name );
                }

            }

            IDictionary<string, int> valuesInt = new Dictionary<string, int>();
            foreach ( var ttt in Enum.GetValues( type ) ) {
                valuesInt.Add( ttt.ToString(), ( (int)ttt ) );

            }

            var items = valuesText.Join( valuesInt,
                                    ( x ) => { return x.Value; },
                                    ( x ) => { return x.Key; },
                                    (outer, inner) =>{ return new KeyValuePair<string,int>(outer.Key,inner.Value);}

                );
            foreach(var item in items){
                ret.Add(item);
            }

            return ret;
        }
Example #6
0
        private void WriteCluster(string path, int numClusters, int numRatings, Func<ItemRating, string> fieldSelector,
            bool writeRatingHistogram, string centerPath = "")
        {
            Console.WriteLine("Prepating data for clustering...");

            var items = _dataset.AllSamples.GroupBy(ir => fieldSelector(ir))
                .Select(g => new
                {
                    ItemId = g.Key,
                    RatingVector = g.GroupBy(ir => ir.Rating)
                        .Select(gg => new { Rate = Convert.ToInt32(gg.Key), Count = gg.Count() }).OrderBy(v => v.Rate)
                }).OrderBy(u => u.ItemId).ToList();

            int numItems = items.Count();

            double[,] features = new double[numItems, numRatings];
            Dictionary<string, string> histograms = new Dictionary<string,string>();

            int ix = 0;
            items.ForEach(i =>
            {
                string histLine = "";

                for (int j = 0; j < numRatings; j++)
                {
                    features[ix, j] = i.RatingVector.Where(rv => rv.Rate == (j + 1)).Select(rv => rv.Count).SingleOrDefault();
                    histLine += features[ix, j] + (j != (numRatings - 1) ? "," : "");
                }
                ix++;
                histograms.Add(i.ItemId, histLine);
            });

            var clusters = Cluster(items.Select(u => u.ItemId), features, numClusters, centerPath);
            var output = clusters.Select(c => string.Format("{0},{1}", c.Key, c.Value));
            File.WriteAllLines(path, output);

            if (writeRatingHistogram)
            {
                Console.WriteLine("Writing item histograms...");

                var hist = histograms.Join(clusters, h => h.Key, c => c.Key, (h, c) => new { Hist = h, Cluster = c })
                    .OrderBy(i => i.Cluster.Value);

                var histOutput = hist.Select(h => string.Format("{0},{1},{2}",
                    h.Cluster.Value,
                    h.Hist.Key,
                    h.Hist.Value
                ));

                var header = new string[] { "ClusterId,ItemId,R1,R2,R3,R4,R5" };

                File.WriteAllLines(path + ".hist", header.Concat(histOutput));
            }
        }
        private void ReinitializeSearchContainers(Dictionary<string, List<string>> Containers)
        {
            if (Containers == null)
            {
                // No search restrictions (search entire domain)
                foreach (var domain in this.Domains)
                    domain.UpdateSearchEntireDomain();
            }
            else
            {
                // Restrict search containers
                var searchContainerDomains = Containers.Join(this.Domains, ok => ok.Key, ik => ik.Name, (o, i) => Tuple.Create(o, i), StringComparer.OrdinalIgnoreCase);
                foreach (var domainContainers in searchContainerDomains)
                    domainContainers.Item2.UpdateSearchContainers(domainContainers.Item1.Value);

                // Ignore domains without configured containers
                var unconfiguredContainers = this.Domains.Except(searchContainerDomains.Select(sc => sc.Item2));
                foreach (var domain in unconfiguredContainers)
                    domain.UpdateSearchContainers(new List<string>());
            }
        }