public ExperienceAnalyticsTableControlResponse Get(DateTime dateFrom, DateTime dateTo, string siteName, Guid id)
        {
            var reportData = new ExperienceAnalyticsTableControlData <dynamic>();

            var random = new Random();

            var count = 10;

            for (var i = 0; i < count; i++)
            {
                var item = new
                {
                    index     = i,
                    id        = Guid.NewGuid().ToString(),
                    datefrom  = dateFrom.ToShortDateString(),
                    dateto    = dateTo.ToShortDateString(),
                    sitename  = siteName,
                    random    = random.Next(0, 1000),
                    parameter = id.ToString()
                };

                reportData.AddItem(item);
            }
            var content = new ExperienceAnalyticsTableControlResponse()
            {
                Data             = reportData,
                TotalRecordCount = count
            };

            return(content);
        }
        public ExperienceAnalyticsTableControlResponse Get(DateTime dateFrom, DateTime dateTo, string siteName)
        {
            Stopwatch sw = new Stopwatch();

            var    reportData = new ExperienceAnalyticsTableControlData <dynamic>();
            var    count      = 0;
            string cacheKey   = "contactListCache";

            //var reportCache = new Sitecore.Caching.Cache("ReportCache", 1024);
            //reportCache.Add("test", 12)

            try
            {
                sw.Start();
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : STOPWATCH - starts.", this);
                string   connectionString = ConfigurationManager.ConnectionStrings["analytics"].ConnectionString;
                MongoUrl mongoUrl         = new MongoUrl(connectionString);

                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : CONNECTION ESTABLISHED.", this);
                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : SiteName - {siteName}, DateFrom - {dateFrom.ToString("dd-MM-yy")}, DateTo - {dateTo.ToString("dd-MM-yy")}", this);

                var client = new MongoClient(connectionString);

                var database = client.GetServer().GetDatabase(mongoUrl.DatabaseName);

                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - database fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                IMongoQuery interactionQuery = null;

                BsonRegularExpression urlFilter1 = "[^/.]/industries/electricity/discover-the-active-grid";
                BsonRegularExpression urlFilter2 = "[^/.]/industries/electricity/discover-the-active-grid/";

                if (string.Equals(siteName, "All", StringComparison.OrdinalIgnoreCase))
                {
                    interactionQuery = Query.And(
                        Query.Or(
                            Query.Matches("Pages.Url.Path", urlFilter1),
                            Query.Matches("Pages.Url.Path", urlFilter2)
                            ),
                        Query.GTE("StartDateTime", new BsonDateTime(dateFrom)),
                        Query.LTE("StartDateTime", new BsonDateTime(dateTo))
                        );
                }
                else
                {
                    interactionQuery = Query.And(
                        Query.Or(
                            Query.Matches("Pages.Url.Path", urlFilter1),
                            Query.Matches("Pages.Url.Path", urlFilter2)
                            ),
                        Query.GTE("StartDateTime", new BsonDateTime(dateFrom)),
                        Query.LTE("StartDateTime", new BsonDateTime(dateTo)),
                        Query.EQ("SiteName", siteName)
                        );
                }

                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - search query built in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : BSON Dates = DateFrom - {new BsonDateTime(dateFrom).ToString()}, DateTo - {new BsonDateTime(dateTo).ToString()}", this);

                var interactions = database.GetCollection <Interaction>("Interactions").Find(interactionQuery);
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Interactions Query Executed.", this);

                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Interactions fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                var customReportCache = Sitecore.Caching.CacheManager.FindCacheByName("CustomReportCache");
                if (customReportCache == null)
                {
                    customReportCache = new Sitecore.Caching.Cache("CustomReportCache", 1000000);
                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Pushing CustomReportCache into Cache.", this);
                }
                else
                {
                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Reading CustomReportCache from Cache.", this);
                }
                Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - CustomReportCache fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                sw.Restart();

                if (interactions != null && interactions.Any())
                {
                    //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are {interactions.Count().ToString()} filtered interactions ", this);
                    //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : Interaction String  - {interactions.ToJson()}", this);
                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Interactions found, working on getting contact ids.", this);

                    IMongoQuery contactQuery = null;

                    BsonArray contactidBsonArray = new BsonArray(interactions.Select(x => x.ContactId));
                    //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : Contact Id String  - {contactidBsonArray.ToJson()}", this);
                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Contacts Ids fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                    sw.Restart();

                    contactQuery = Query.In("_id", contactidBsonArray);
                    MongoCollection <User> contactsCollection = null;

                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Started working on Contacts.", this);

                    var cachedContacts = customReportCache.GetValue(cacheKey);


                    if (cachedContacts != null)
                    {
                        contactsCollection = (MongoCollection <User>)cachedContacts;
                        //Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : {test}", this);

                        //contactsCollection = (MongoCollection<User>)customReportCache.GetValue(cacheKey);
                        Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Reading Contacts from Cache.", this);
                    }
                    else
                    {
                        contactsCollection = database.GetCollection <User>("Contacts");
                        customReportCache.Add(cacheKey, contactsCollection, TypeUtil.SizeOfObject(), DateTime.Now.AddHours(12));
                        Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : Pushing Contacts into Cache. Size is {customReportCache.Size}", this);
                    }

                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Contacts fetched in {sw.Elapsed.TotalSeconds} seconds", this);
                    sw.Restart();

                    var contacts = contactsCollection.Find(contactQuery);
                    Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : Contacts Query Executed.", this);

                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : STOPWATCH - Contacts filtered in {sw.Elapsed.TotalSeconds} seconds", this);
                    sw.Stop();

                    if (contacts != null && contacts.Any())
                    {
                        Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are {contacts.Count().ToString()} filtered contacts ", this);
                        int iteration = 1;
                        foreach (var contact in contacts)
                        {
                            if (!string.IsNullOrEmpty(contact.Personal.FirstName) && !string.IsNullOrEmpty(contact.Personal.Surname) && !string.IsNullOrEmpty(contact.Identifiers.Identifier))
                            {
                                var matchedInteraction = interactions.FirstOrDefault(x => x.ContactId.Equals(contact.id));

                                var item = new
                                {
                                    index          = iteration - 1,
                                    srn            = iteration,
                                    id             = contact.id,
                                    emailid        = contact.Identifiers.Identifier,
                                    fullname       = $"{contact.Personal.FirstName} {contact.Personal.Surname}",
                                    sitename       = matchedInteraction.SiteName,
                                    name           = $"{contact.Personal.FirstName} {contact.Personal.Surname}",
                                    activitydate   = matchedInteraction.EndDateTime.ToString("MM/dd/yyyy HH:mm:ss"),
                                    visitvalue     = matchedInteraction.Value,
                                    filtersitename = siteName
                                };

                                reportData.AddItem(item);
                                iteration++;
                            }
                        }
                    }
                    else
                    {
                        Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are NO filtered contacts ", this);
                    }
                }
                else
                {
                    Sitecore.Diagnostics.Log.Info($" Custom Visitor Report : There are NO filtered interactions ", this);
                }
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : ACTIVITY COMPLETED", this);
            }
            catch (Exception e)
            {
                Sitecore.Diagnostics.Log.Error($" Custom Visitor Report : {e.Message}", this);
                Sitecore.Diagnostics.Log.Info(" Custom Visitor Report : ACTIVITY ENDE DUE TO ERROR", this);
            }

            var content = new ExperienceAnalyticsTableControlResponse()
            {
                Data             = reportData,
                TotalRecordCount = count
            };

            return(content);
        }
        public ExperienceAnalyticsTableControlResponse Get(DateTime dateFrom, DateTime dateTo, string siteName, Guid id)
        {
            //Sitecore.Analytics.Reports.ReportFactory.
            Sitecore.Analytics.Reporting.ReportDataQuery test = new Sitecore.Analytics.Reporting.ReportDataQuery();

            var reportData = new ExperienceAnalyticsTableControlData <dynamic>();

            //-------------------
            //Connecting to the Analytics DB
            //var driver = Sitecore.Analytics.Data.DataAccess.MongoDb.MongoDbDriver.FromConnectionString("analytics");

            ////Building our query
            //var builder = new QueryBuilder();
            //var filter = builder.And(builder.GTE(_ => _.StartDateTime, DateTime.Now.AddDays(-30)), builder.EQ(_ => _.SiteName, siteName.ToLower()));

            ////Retrieving data from the "Interactions" collection
            //var interactions = driver.Interactions.FindAs(filter)
            //-------------------

            //Sitecore.Analytics.Reporting.MongoDbReportDataSource mongoDBSource = new Sitecore.Analytics.Reporting.MongoDbReportDataSource("analytics");
            //string query = "{collection: \"Interactions\",query: {_t: \"VisitData\"},fields: [\"_id\",\"ContactId\",\"StartDateTime\",\"EndDateTime\",\"Value\",\"VisitPageCount\"]}";
            //ReportDataQuery reportQuery = new Sitecore.Analytics.Reporting.ReportDataQuery(query);
            //DataTable interactions = mongoDBSource.GetData(reportQuery);
            ////------------------------------------------

            //string connectionString = ConfigurationManager.ConnectionStrings["analytics"].ConnectionString;

            //var client = new MongoDB.Driver.MongoClient(connectionString);

            //var database = client.GetServer().GetDatabase("your_database_name");

            //var contacts = database.GetCollection("Contacts");
            //var results =
            //    contacts.Aggregate(
            //        new BsonDocument
            //        {
            //{
            //    "$lookup",
            //    new BsonDocument
            //    {
            //        {"from", "Interactions"},
            //        {"localField", "_id"},
            //        {"foreignField", "ContactId"},
            //        {"as", "Interactions"}
            //    }
            //}
            //        });

            //// This may be a very large string, depending on the amount of data you have
            //string json = results.ResultDocuments.ToJson();
            //-------------------------------------------------------------
            var random = new Random();

            var count = 10;

            for (var i = 0; i < count; i++)
            {
                var item = new
                {
                    index     = i,
                    id        = Guid.NewGuid().ToString(),
                    datefrom  = dateFrom.ToShortDateString(),
                    dateto    = dateTo.ToShortDateString(),
                    sitename  = siteName,
                    random    = random.Next(0, 1000),
                    parameter = id.ToString()
                };

                reportData.AddItem(item);
            }
            var content = new ExperienceAnalyticsTableControlResponse()
            {
                Data             = reportData,
                TotalRecordCount = count
            };

            return(content);
        }