Advertisement
Guest User

Untitled

a guest
Apr 28th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 69.08 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.Odbc;
  5. using System.Diagnostics;
  6. using System.IO.MemoryMappedFiles;
  7. using System.Linq;
  8. using EventCyborgEvent.Business;
  9. using EventCyborgEvent.Entities;
  10. using EventCyborgEvent.Infrastructure;
  11. using System.Device.Location;
  12. using EventCyborgEvent.Infrastructure.Common;
  13. using EventCyborgEvent.Infrastructure.Enums;
  14. using EventCyborgEvent.Utils;
  15.  
  16. namespace EventCyborgEvent.Services
  17. {
  18.     public class AmazonRedshift
  19.     {
  20.         #region Variables
  21.  
  22.         private readonly TopicService _topicService;
  23.         private readonly EventInfoService _eventInfoService;
  24.         private readonly UserService _userService;
  25.         private readonly UserFollowService _userFollowService;
  26.         private readonly MediaService _mediaService;
  27.         private readonly GlobalSettingsService _globalSettingsService = new GlobalSettingsService();
  28.         public TopicService TopicService
  29.         {
  30.             get { return _topicService ?? new TopicService(); }
  31.         }
  32.         public EventInfoService EventInfoService
  33.         {
  34.             get { return _eventInfoService ?? new EventInfoService(); }
  35.         }
  36.         public UserService UserService
  37.         {
  38.             get { return _userService ?? new UserService(); }
  39.         }
  40.         public UserFollowService UserFollowService
  41.         {
  42.             get { return _userFollowService ?? new UserFollowService(); }
  43.         }
  44.         public MediaService MediaService
  45.         {
  46.             get { return _mediaService ?? new MediaService(); }
  47.         }
  48.  
  49.         public string GeoHelperDatabaseFile
  50.         {
  51.             get
  52.             {
  53.                 var allSettigns = _globalSettingsService.GetAll();
  54.                 string url;
  55.                 url = allSettigns.Find(GlobalSettingsColumn.ItemKey, "GeoHelperDatabaseFile").ItemValue;
  56.                 return url;
  57.             }
  58.         }
  59.         public string AmazonRedshiftDatabaseName
  60.         {
  61.             get
  62.             {
  63.                 var allSettigns = _globalSettingsService.GetAll();
  64.                 string dbName;
  65.                 dbName = allSettigns.Find(GlobalSettingsColumn.ItemKey, "AmazonRedshiftDatabaseName").ItemValue;
  66.                 return dbName;
  67.             }
  68.         }
  69.  
  70.         public int tagsCount = 0;
  71.         // Server, e.g. "examplecluster.xyz.us-west-2.redshift.amazonaws.com"
  72.         string server = "aigendars.crqnzxnrzu09.eu-west-1.redshift.amazonaws.com";
  73.  
  74.         // Port, e.g. "5439"
  75.         string port = "5439";
  76.  
  77.         // MasterUserName, e.g. "masteruser".
  78.         string masterUsername = "redshift";
  79.  
  80.         // MasterUserPassword, e.g. "mypassword".
  81.         string masterUserPassword = "!Term2015#$";
  82.  
  83.         // DBName, e.g. "dev"
  84.         //string DBName = "aigendaredshiftdb";
  85.  
  86.         private List<string> tags;
  87.  
  88.         #endregion
  89.  
  90.         #region Log methods
  91.         /// <summary> Used for inserting new record in activityLog table (AmazonRedshiftDB) </summary>
  92.         public void InsertLog(Activity activityLog)
  93.         {
  94.  
  95.             string query = "";
  96.  
  97.             if (activityLog.ActivityValue.Count > 1)
  98.             {
  99.                 foreach (var row in activityLog.ActivityValue)
  100.                 {
  101.                     query +=
  102.                         string.Format(
  103.                             "insert into tagging.activityLog(userid,externalentityid,activityvalue,clicktype,actiondate,latitude,longitude,related_topics)" +
  104.                             " values('{0}','{1}','{2}',{3},'{4}','{5}','{6}','{7}'); ",
  105.                             activityLog.UserId, activityLog.ExternalEntityId, row, (int)activityLog.ActivityType,
  106.                             activityLog.TimeOfActivity, activityLog.Latitude, activityLog.Longitude, activityLog.RelatedTopics);
  107.                 }
  108.             }
  109.             else
  110.             {
  111.                 if (activityLog.ActivityValue.Count == 1)
  112.                 {
  113.                     query =
  114.                         string.Format(
  115.                             "insert into tagging.activityLog(userid,externalentityid,activityvalue,clicktype,actiondate,latitude,longitude,related_topics)" +
  116.                             " values('{0}','{1}','{2}',{3},'{4}','{5}','{6}','{7}')",
  117.                             activityLog.UserId, activityLog.ExternalEntityId, activityLog.ActivityValue[0],
  118.                             (int)activityLog.ActivityType, activityLog.TimeOfActivity, activityLog.Latitude,
  119.                             activityLog.Longitude, activityLog.RelatedTopics);
  120.                 }
  121.                 else
  122.                 {
  123.                     query =
  124.                         string.Format(
  125.                             "insert into tagging.activityLog(userid,externalentityid,activityvalue,clicktype,actiondate,latitude,longitude,related_topics)" +
  126.                                          " values('{0}','{1}','{2}',{3},'{4}','{5}','{6}','{7}')",
  127.                             activityLog.UserId, activityLog.ExternalEntityId, string.Empty,
  128.                             (int)activityLog.ActivityType, activityLog.TimeOfActivity, activityLog.Latitude,
  129.                             activityLog.Longitude, activityLog.RelatedTopics);
  130.                 }
  131.             }
  132.  
  133.  
  134.  
  135.             string connString = "Driver={Amazon Redshift (x86)};" +
  136.                     String.Format("Server={0};Database={1};" +
  137.                     "UID={2};PWD={3};Port={4}",
  138.                     server, AmazonRedshiftDatabaseName, masterUsername,
  139.                     masterUserPassword, port);
  140.             var conn = new OdbcConnection(connString);
  141.  
  142.             try
  143.             {
  144.                 // Make a connection using the psqlODBC provider.
  145.  
  146.                 conn.Open();
  147.  
  148.                 // Try a simple query.
  149.                 string sql = query;
  150.  
  151.                 var da = new OdbcDataAdapter();
  152.                 da.InsertCommand = new OdbcCommand();
  153.                 da.InsertCommand.CommandText = query;
  154.                 da.InsertCommand.Connection = conn;
  155.  
  156.                 var nesto = da.InsertCommand.ExecuteReader();
  157.             }
  158.             catch (Exception ex)
  159.             {
  160.             }
  161.             finally
  162.             {
  163.                 conn.Close();
  164.             }
  165.         }
  166.  
  167.  
  168.         /// <summary>Returns latitude and longitude using GeoCoordinateWatcher. </summary>
  169.         public double[] GetUserLatitudeAndLongitutde()
  170.         {
  171.             GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
  172.             watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
  173.  
  174.             double latitude;
  175.             double longitutde;
  176.  
  177.             if (watcher.Position.Location.IsUnknown != true)
  178.             {
  179.                 GeoCoordinate coord = watcher.Position.Location;
  180.  
  181.                 latitude = coord.Latitude;
  182.                 longitutde = coord.Longitude;
  183.  
  184.             }
  185.             else
  186.             {
  187.                 GeoHelper geoHelper = new GeoHelper(GeoHelperDatabaseFile);
  188.                 double[] res = geoHelper.GetlatLong();
  189.                 if (res != null)
  190.                 {
  191.                     latitude = res[0];
  192.                     longitutde = res[1];
  193.                 }
  194.                 else
  195.                 {
  196.                     string publicIp = geoHelper.GetIp();
  197.                     res = geoHelper.GetlatLongByIpApi(publicIp);
  198.                     latitude = res[0];
  199.                     longitutde = res[1];
  200.                 }
  201.  
  202.             }
  203.  
  204.             return new[]
  205.             {
  206.                 latitude,
  207.                 longitutde
  208.             };
  209.  
  210.         }
  211.  
  212.  
  213.         public void InsertListLog(List<Activity> activityLogs)
  214.         {
  215.  
  216.  
  217.             string query =
  218.                 "insert into tagging.activityLog(userid,externalentityid,activityvalue,clicktype,actiondate,latitude,longitude)values";
  219.  
  220.             foreach (var activityLog in activityLogs)
  221.             {
  222.                 query += string.Format("('{0}','{1}','{2}',{3},'{4}','{5}','{6}')",
  223.                                          activityLog.UserId, activityLog.ExternalEntityId, activityLog.ActivityValue, (int)activityLog.ActivityType, activityLog.TimeOfActivity, activityLog.Latitude, activityLog.Longitude) + ",";
  224.             }
  225.  
  226.             query = query.Remove(query.Length - 1);
  227.             string connString = "Driver={Amazon Redshift (x86)};" +
  228.                     String.Format("Server={0};Database={1};" +
  229.                     "UID={2};PWD={3};Port={4}",
  230.                     server, AmazonRedshiftDatabaseName, masterUsername,
  231.                     masterUserPassword, port);
  232.             var conn = new OdbcConnection(connString);
  233.             try
  234.             {
  235.                 // Make a connection using the psqlODBC provider.
  236.                 conn.Open();
  237.  
  238.                 // Try a simple query.
  239.                 string sql = query;
  240.  
  241.                 OdbcDataAdapter da = new OdbcDataAdapter();
  242.                 da.InsertCommand = new OdbcCommand();
  243.                 da.InsertCommand.CommandText = query;
  244.                 da.InsertCommand.Connection = conn;
  245.  
  246.                 var nesto = da.InsertCommand.ExecuteReader();
  247.  
  248.             }
  249.             catch (Exception ex)
  250.             {
  251.             }
  252.             finally
  253.             {
  254.                 conn.Close();
  255.             }
  256.         }
  257.         #endregion
  258.  
  259.         #region Construct Tag Clusters
  260.  
  261.         public MemoryMappedFile JoinTagsOnUsers(MemoryMappedFile matrix, List<string> tags)
  262.         {
  263.             string query = string.Format(@"SELECT firstlog.activityvalue Tag1, firstLog.userid UserId, secondLog.activityvalue
  264.                                        Tag2 FROM tagging.activityLog firstLog
  265.                                        JOIN tagging.activityLog secondLog ON firstLog.userid = secondLog.userid
  266.                                        WHERE firstLog.activityid < secondLog.activityid AND activityvalue<>''");
  267.  
  268.             string connString = "Driver={Amazon Redshift (x86)};" +
  269.                     String.Format("Server={0};Database={1};" +
  270.                     "UID={2};PWD={3};Port={4}",
  271.                     server, AmazonRedshiftDatabaseName, masterUsername,
  272.                     masterUserPassword, port);
  273.             var conn = new OdbcConnection(connString);
  274.             try
  275.             {
  276.                 // Make a connection using the psqlODBC provider.
  277.                 conn.Open();
  278.  
  279.                 OdbcDataAdapter da = new OdbcDataAdapter();
  280.                 da.SelectCommand = new OdbcCommand();
  281.                 da.SelectCommand.CommandText = query;
  282.                 da.SelectCommand.Connection = conn;
  283.  
  284.                 var reader = da.SelectCommand.ExecuteReader();
  285.  
  286.                 while (reader.Read())
  287.                 {
  288.                     var tag1 = reader["Tag1"].ToString();
  289.                     var tag2 = reader["Tag2"].ToString();
  290.                     if (tag1 == tag2) continue;
  291.                     var index1 = tags.IndexOf(tag1);
  292.                     var index2 = tags.IndexOf(tag2);
  293.  
  294.                     //matrix[index1][index2] = matrix[index2][index1] += 1;
  295.                     var view = matrix.CreateViewAccessor();
  296.                     var plusOne = (double)(view.ReadDouble(index1 * tags.Count + index2) + 1);
  297.                     view.Write<double>(index1 * tags.Count + index2, ref plusOne);
  298.                 }
  299.             }
  300.             catch (Exception ex)
  301.             {
  302.             }
  303.             finally
  304.             {
  305.                 conn.Close();
  306.             }
  307.  
  308.             return matrix;
  309.         }
  310.  
  311.  
  312.         /// <summary>
  313.         /// Construct matrix according to the connection of tags by events.
  314.         /// </summary>
  315.         /// <param name="matrix"></param>
  316.         /// <returns>Updated matrix with connected tags.</returns>
  317.         public MemoryMappedFile JoinTagsOnEvents(MemoryMappedFile matrix, List<string> tags)
  318.         {
  319.             var eventTags = TopicService.Topic_JoinTagsOnEvents();
  320.             foreach (DataRow row in eventTags.Tables[0].Rows)
  321.             {
  322.                 if (row["Topic1"].ToString() == row["Topic2"].ToString()) continue;
  323.                 var index1 = tags.IndexOf(row["Topic1"].ToString());
  324.                 var index2 = tags.IndexOf(row["Topic2"].ToString());
  325.  
  326.  
  327.                 var view = matrix.CreateViewAccessor();
  328.                 var plusFive = (double)(view.ReadDouble(index1 * tags.Count + index2) + 5);
  329.                 view.Write<double>(index1 * tags.Count + index2, ref plusFive);
  330.  
  331.  
  332.                 var test = view.ReadDouble(104 * tags.Count + 80); // index1 = 104 , index2 = 80
  333.  
  334.             }
  335.             var view1 = matrix.CreateViewAccessor();
  336.             var test1 = view1.ReadDouble(104 * tags.Count + 80);
  337.             return matrix;
  338.         }
  339.  
  340.  
  341.         /// <summary>
  342.         /// Constructs the input matrix for the MCL algorithm.
  343.         /// </summary>
  344.         /// <returns>The resulting matrix ready for clustering.</returns>
  345.         public MemoryMappedFile ConstructTagMatrix()
  346.         {
  347.             var allTopics = TopicService.Topic_GetAllDistinctTopics();
  348.             tags = new List<string>();
  349.             foreach (DataRow topic in allTopics.Tables[0].Rows)
  350.             {
  351.                 tags.Add(topic["TopicValue"].ToString());
  352.             }
  353.  
  354.             var matrix = MemoryMappedFile.CreateNew("tes132345tData", tags.Count * tags.Count);
  355.             var view = matrix.CreateViewAccessor();
  356.             //var matrix = new double[tags.Count][];
  357.             for (int i = 0; i < tags.Count; i++)
  358.             {
  359.                 //matrix[i] = new double[tags.Count];
  360.                 //matrix[i][i] = 1;
  361.                 var one = 1.0;
  362.                 view.Write<double>(i * tags.Count + i, ref one);
  363.  
  364.             }
  365.  
  366.             matrix = JoinTagsOnUsers(matrix, tags);
  367.             //matrix = JoinTagsOnEvents(matrix, tags);
  368.             return matrix;
  369.         }
  370.  
  371.         public void GenerateTagClusters()
  372.         {
  373.             try
  374.             {
  375.                 var allTopics = TopicService.Topic_GetAllDistinctTopics();
  376.                 var size = allTopics.Tables[0].Rows.Count;
  377.                 MCLAlgorithm mclAlgorithm = new MCLAlgorithm();
  378.  
  379.                 var matrixConstruction = ConstructTagMatrix();
  380.  
  381.                 var matrixNormalisation = mclAlgorithm.MatrixNormalisation(matrixConstruction, size);
  382.  
  383.                 //var matrixExponential = mclAlgorithm.MatrixProductExponential(matrixNormalisation,
  384.                 //    mclAlgorithm.matrixPower, size);
  385.  
  386.                 //var matrixInflation = mclAlgorithm.MatrixInflate(matrixExponential, mclAlgorithm.matrixPower, size);
  387.  
  388.                 //matrixInflation = mclAlgorithm.Repeat(matrixInflation, size);
  389.  
  390.                 //var matrixInterpretated = mclAlgorithm.InterpretResulting(matrixInflation, size);
  391.  
  392.                 //List<List<int>> groups = mclAlgorithm.groups;
  393.  
  394.                 //CleanTagClusters();
  395.                 //for (var i = 0; i < groups.Count; i++)
  396.                 //{
  397.                 //    for (var j = 0; j < groups[i].Count; j++)
  398.                 //    {
  399.                 //        InsertTagClustersRecord(i + 1, tags[groups[i][j] - 1]);
  400.                 //    }
  401.                 //}
  402.             }
  403.             catch { }
  404.         }
  405.  
  406.         public void InsertTagClustersRecord(int tagClusterId, string tag)
  407.         {
  408.             var query = string.Format("INSERT INTO tagging.TagClusters(tagclusterid,tagvalue)" +
  409.                                          " VALUES('{0}','{1}')", tagClusterId, tag);
  410.  
  411.             var connString = "Driver={Amazon Redshift (x86)};" +
  412.                     String.Format("Server={0};Database={1};" +
  413.                     "UID={2};PWD={3};Port={4}",
  414.                     server, AmazonRedshiftDatabaseName, masterUsername,
  415.                     masterUserPassword, port);
  416.             var conn = new OdbcConnection(connString);
  417.             try
  418.             {
  419.                 // Make a connection using the psqlODBC provider.
  420.                 conn.Open();
  421.  
  422.                 var da = new OdbcDataAdapter { InsertCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  423.                 da.InsertCommand.ExecuteNonQuery();
  424.             }
  425.             catch (Exception ex)
  426.             {
  427.             }
  428.             finally
  429.             {
  430.                 conn.Close();
  431.             }
  432.         }
  433.  
  434.         public void CleanTagClusters()
  435.         {
  436.             var query = string.Format("DELETE FROM tagging.TagClusters");
  437.  
  438.             var connString = "Driver={Amazon Redshift (x86)};" +
  439.                     String.Format("Server={0};Database={1};" +
  440.                     "UID={2};PWD={3};Port={4}",
  441.                     server, AmazonRedshiftDatabaseName, masterUsername,
  442.                     masterUserPassword, port);
  443.             var conn = new OdbcConnection(connString);
  444.             try
  445.             {
  446.                 // Make a connection using the psqlODBC provider.
  447.  
  448.                 conn.Open();
  449.  
  450.                 var da = new OdbcDataAdapter { DeleteCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  451.                 da.DeleteCommand.ExecuteNonQuery();
  452.             }
  453.             catch (Exception ex)
  454.             {
  455.             }
  456.             finally
  457.             {
  458.                 conn.Close();
  459.             }
  460.         }
  461.  
  462.         #endregion
  463.  
  464.         #region Construct Event Clusters
  465.         //try-catch proverki za da ne otide matricata vo nepovrat
  466.  
  467.         /// <summary>
  468.         /// Construct matrix according to the connection of topics by events.
  469.         /// </summary>
  470.         /// <param name="matrix"></param>
  471.         /// <returns>Updated matrix with connected tags.</returns>
  472.         public MemoryMappedFile JoinEventsOnTopics(MemoryMappedFile matrix, List<string> tags)
  473.         {
  474.             try
  475.             {
  476.                 var eventTopics = EventInfoService.Event_JoinEventsOnTopics();
  477.                 var view = matrix.CreateViewAccessor();
  478.                 foreach (DataRow row in eventTopics.Tables[0].Rows)
  479.                 {
  480.  
  481.                     if (!tags.Contains(row["EventId1"].ToString()) || !tags.Contains(row["EventId2"].ToString())) continue;
  482.                     if (row["EventId1"].ToString() == row["EventId2"].ToString()) continue;
  483.  
  484.                     var index1 = tags.IndexOf(row["EventId1"].ToString());
  485.                     var index2 = tags.IndexOf(row["EventId2"].ToString());
  486.                     var plusFive = (double)(view.ReadDouble(index1 * tags.Count + index2) + 5);
  487.                     view.Write<double>(index1 * tags.Count + index2, ref plusFive);
  488.                 }
  489.                 return matrix;
  490.             }
  491.  
  492.             catch (Exception ex)
  493.             {
  494.                 throw new Exception(ex.ToString());
  495.             }
  496.         }
  497.  
  498.  
  499.         /// <summary>
  500.         /// Construct matrix according to the connection of topics by events.
  501.         /// </summary>
  502.         /// <param name="matrix"></param>
  503.         /// <returns>Updated matrix with connected tags.</returns>
  504.         public MemoryMappedFile JoinEventsOnUsers(MemoryMappedFile matrix, List<string> tags)
  505.         {
  506.             int i = 1;
  507.             try
  508.             {
  509.  
  510.                 var eventUsers = EventInfoService.Event_JoinEventsOnUsers();
  511.  
  512.                 var mmf = MemoryMappedFile.OpenExisting("EventsMemoryMaped3");
  513.                 var view = mmf.CreateViewAccessor();
  514.                 foreach (DataRow row in eventUsers.Tables[0].Rows)
  515.                 {
  516.                     var dar = eventUsers.Tables[0].Rows.Count;
  517.                     i++;
  518.                     var c = i;
  519.                     if (!tags.Contains(row["EventId1"].ToString()) || !tags.Contains(row["EventId2"].ToString())) continue;
  520.                     if (row["EventId1"].ToString() == row["EventId2"].ToString()) continue;
  521.  
  522.                     var index1 = tags.IndexOf(row["EventId1"].ToString());
  523.                     var index2 = tags.IndexOf(row["EventId2"].ToString());
  524.  
  525.                     //var plusThree = 3.0;
  526.  
  527.                     var plusThree = (view.ReadDouble(index1 * tags.Count + index2) + 3);
  528.                     view.Write(index1 * tags.Count + index2, ref plusThree);
  529.  
  530.                     var test = view.ReadDouble(49 * tags.Count + 54); // index1 = 49 , index2 = 54
  531.  
  532.                     //if (index1 == 49 && index2 == 54)
  533.                     //{
  534.                     //    var sdas = "";
  535.                     //}
  536.  
  537.  
  538.                 }
  539.  
  540.                 return matrix;
  541.             }
  542.  
  543.             catch (Exception ex)
  544.             {
  545.                 throw new Exception(ex.ToString());
  546.             }
  547.         }
  548.  
  549.  
  550.         /// <summary>
  551.         /// Constructs the input matrix for the MCL algorithm.
  552.         /// </summary>
  553.         /// <returns>The resulting matrix ready for clustering.</returns>
  554.         public MemoryMappedFile ConstructEventsMatrix()
  555.         {
  556.             try
  557.             {
  558.                 var allEvents = TopicService.Topic_GetAllDistinctEvents();
  559.  
  560.                 tags = new List<string>();
  561.                 foreach (DataRow singleEvent in allEvents.Tables[0].Rows)
  562.                 {
  563.                     tags.Add(singleEvent["EventID"].ToString());
  564.                 }
  565.  
  566.                 var matrix = MemoryMappedFile.CreateNew("EventsMemoryMaped3", (long)tags.Count * tags.Count);
  567.                 var view = matrix.CreateViewAccessor();
  568.                 //var matrix = new double[tags.Count][];
  569.  
  570.                 for (int i = 0; i < (long)tags.Count; ++i)
  571.                 {
  572.                     //matrix[i] = new double[tags.Count];
  573.                     //matrix[i][i] = 1;
  574.                     var one = 1.0;
  575.  
  576.                     view.Write<double>(i * (long)tags.Count + i, ref one);
  577.                 }
  578.  
  579.                 matrix = JoinEventsOnUsers(matrix, tags);
  580.                 //matrix = JoinEventsOnTopics(matrix, tags);
  581.                 return matrix;
  582.             }
  583.             catch (Exception ex)
  584.             {
  585.                 throw new Exception(ex.ToString());
  586.             }
  587.         }
  588.  
  589.         public void GenerateEventClusters()
  590.         {
  591.             MCLAlgorithm mclAlgorithm = new MCLAlgorithm();
  592.  
  593.             var allEvents = TopicService.Topic_GetAllDistinctEvents();
  594.  
  595.             var size = allEvents.Tables[0].Rows.Count;
  596.  
  597.             var matrixConstruction = ConstructEventsMatrix();
  598.  
  599.             var matrixNormalisation = mclAlgorithm.MatrixNormalisation(matrixConstruction, size);
  600.  
  601.             //var matrixExponential = mclAlgorithm.MatrixProductExponential(matrixNormalisation,
  602.             //    mclAlgorithm.matrixPower, size);
  603.  
  604.             //var matrixInflation = mclAlgorithm.MatrixInflate(matrixExponential, mclAlgorithm.matrixPower, size);
  605.  
  606.             //matrixInflation = mclAlgorithm.Repeat(matrixInflation, size);
  607.  
  608.             //var matrixInterpretated = mclAlgorithm.InterpretResulting(matrixInflation, size);
  609.  
  610.             //List<List<int>> groups = mclAlgorithm.groups;
  611.  
  612.             //CleanEventClusters();
  613.  
  614.             //for (var i = 0; i < groups.Count; i++)
  615.             //{
  616.             //    for (var j = 0; j < groups[i].Count; j++)
  617.             //    {
  618.             //        InsertEventClustersRecord(i + 1, Convert.ToInt64(tags[groups[i][j] - 1]));
  619.             //    }
  620.             //}
  621.         }
  622.  
  623.         public void InsertEventClustersRecord(int tagEventClusterId, long eventId)
  624.         {
  625.             var query = string.Format("INSERT INTO tagging.EventClusters(eventclusterid,eventid)" +
  626.                                          " VALUES('{0}','{1}')", tagEventClusterId, eventId);
  627.  
  628.  
  629.             var connString = "Driver={Amazon Redshift (x86)};" +
  630.                     String.Format("Server={0};Database={1};" +
  631.                     "UID={2};PWD={3};Port={4}",
  632.                     server, AmazonRedshiftDatabaseName, masterUsername,
  633.                     masterUserPassword, port);
  634.             var conn = new OdbcConnection(connString);
  635.             try
  636.             {
  637.                 conn.Open();
  638.  
  639.                 var da = new OdbcDataAdapter { InsertCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  640.                 da.InsertCommand.ExecuteNonQuery();
  641.             }
  642.             catch (Exception ex)
  643.             {
  644.             }
  645.             finally
  646.             {
  647.                 conn.Close();
  648.             }
  649.         }
  650.  
  651.         public void CleanEventClusters()
  652.         {
  653.             var query = string.Format("DELETE FROM tagging.EventClusters");
  654.  
  655.             var connString = "Driver={Amazon Redshift (x86)};" +
  656.                     String.Format("Server={0};Database={1};" +
  657.                     "UID={2};PWD={3};Port={4}",
  658.                     server, AmazonRedshiftDatabaseName, masterUsername,
  659.                     masterUserPassword, port);
  660.             var conn = new OdbcConnection(connString);
  661.  
  662.             try
  663.             {
  664.                 // Make a connection using the psqlODBC provider.
  665.                 conn.Open();
  666.  
  667.                 var da = new OdbcDataAdapter { DeleteCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  668.                 da.DeleteCommand.ExecuteNonQuery();
  669.             }
  670.             catch (Exception ex)
  671.             {
  672.             }
  673.             finally
  674.             {
  675.                 conn.Close();
  676.             }
  677.         }
  678.  
  679.         #endregion
  680.  
  681.         #region Get recommended topics for users
  682.  
  683.         public DataTable GetTagsList(List<string> tags, int numberOfTags)
  684.         {
  685.             var retList = new List<string>();
  686.  
  687.             var tagClusterIds = GetTopicClusterIds(tags);
  688.  
  689.             var query = string.Format("SELECT * FROM tagging.TagClusters WHERE tagclusterid={0}", tagClusterIds.FirstOrDefault());
  690.             for (var i = 0; i < tagClusterIds.Count; i++)
  691.                 query += string.Format(" OR tagclusterid={0}", tagClusterIds[i]);
  692.             query += string.Format(" ORDER BY RANDOM() LIMIT " + numberOfTags);
  693.  
  694.             var connString = "Driver={Amazon Redshift (x86)};" +
  695.                     String.Format("Server={0};Database={1};" +
  696.                     "UID={2};PWD={3};Port={4}",
  697.                     server, AmazonRedshiftDatabaseName, masterUsername,
  698.                     masterUserPassword, port);
  699.             var conn = new OdbcConnection(connString);
  700.  
  701.             var dt = new DataTable();
  702.             dt.Columns.Add(new DataColumn("tagvalue"));
  703.  
  704.             try
  705.             {
  706.                 conn.Open();
  707.  
  708.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  709.                 da.Fill(dt);
  710.             }
  711.             catch (Exception ex)
  712.             {
  713.             }
  714.             finally
  715.             {
  716.                 conn.Close();
  717.             }
  718.             return dt;
  719.         }
  720.  
  721.         public List<int> GetTopicClusterIds(List<string> tags)
  722.         {
  723.             if (!tags.Any())
  724.                 return new List<int>();
  725.             var retList = new List<int>();
  726.             var query = string.Format("SELECT * FROM tagging.TagClusters WHERE tagvalue='{0}'", tags.FirstOrDefault());
  727.             for (var i = 1; i < tags.Count; i++)
  728.                 query += string.Format(" OR tagvalue='{0}'", tags[i]);
  729.  
  730.             var connString = "Driver={Amazon Redshift (x86)};" +
  731.                     String.Format("Server={0};Database={1};" +
  732.                     "UID={2};PWD={3};Port={4}",
  733.                     server, AmazonRedshiftDatabaseName, masterUsername,
  734.                     masterUserPassword, port);
  735.  
  736.             var conn = new OdbcConnection(connString);
  737.             try
  738.             {
  739.                 conn.Open();
  740.  
  741.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  742.  
  743.                 var reader = da.SelectCommand.ExecuteReader();
  744.  
  745.  
  746.                 while (reader.Read())
  747.                 {
  748.                     retList.Add(int.Parse(reader["tagclusterid"].ToString()));
  749.                 }
  750.             }
  751.             catch (Exception ex)
  752.             {
  753.             }
  754.             finally
  755.             {
  756.                 conn.Close();
  757.             }
  758.             return retList;
  759.         }
  760.  
  761.         public Dictionary<string, int> GetRecommendedTagsWithCount(List<string> tags, int numberOfTags)
  762.         {
  763.             var retDict = new Dictionary<string, int>();
  764.             var topTags = GetTagsList(tags, numberOfTags);
  765.  
  766.             foreach (DataRow tag in topTags.Rows)
  767.             {
  768.                 try
  769.                 {
  770.                     int count;
  771.                     retDict[tag["tagvalue"].ToString()] = TopicService.GetTotalItems(string.Format("TopicValue = '{0}'", tag), out count);
  772.                 }
  773.                 catch (Exception exc) { }
  774.             }
  775.  
  776.             return retDict;
  777.         }
  778.  
  779.         public Dictionary<string, int> GetRecommendedTopicsForUser(string userId, int numberOfTags)
  780.         {
  781.             Dictionary<string, int> retDict = null;
  782.             var topicsList = new List<string>();
  783.             var queryEvents = string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1}) AND userid='{2}' GROUP BY externalentityid ORDER BY num DESC LIMIT {3}", (int)ActivityTypeEnumerator.EventClick, (int)ActivityTypeEnumerator.EventFollowClick, userId, numberOfTags);
  784.             var queryTopics = string.Format("SELECT actlog.activityvalue AS TopicValue, COUNT(actlog.activityvalue) AS num FROM tagging.activityLog actlog WHERE actlog.ClickType={0} AND userid='{1}' GROUP BY actlog.activityvalue ORDER BY num DESC LIMIT {2}", (int)ActivityTypeEnumerator.TagClick, userId, numberOfTags);
  785.             var queryRandomTopics = string.Format("SELECT tagvalue AS TopicValue FROM tagging.tagclusters ORDER BY RANDOM() LIMIT {0}", numberOfTags);
  786.  
  787.             var connString = "Driver={Amazon Redshift (x86)};" +
  788.                     String.Format("Server={0};Database={1};" +
  789.                     "UID={2};PWD={3};Port={4}",
  790.                     server, AmazonRedshiftDatabaseName, masterUsername,
  791.                     masterUserPassword, port);
  792.  
  793.             var conn = new OdbcConnection(connString);
  794.             try
  795.             {
  796.                 conn.Open();
  797.  
  798.                 var da = new OdbcDataAdapter
  799.                 {
  800.                     SelectCommand = new OdbcCommand { CommandText = queryTopics, Connection = conn }
  801.                 };
  802.  
  803.                 var dt1 = new DataTable();
  804.                 var topicValueColumn = new DataColumn("TopicValue", Type.GetType("System.String"));
  805.                 dt1.Columns.Add(topicValueColumn);
  806.                 dt1.PrimaryKey = new[] { topicValueColumn };
  807.                 da.Fill(dt1);
  808.                 topicsList.AddRange((from DataRow dataRow in dt1.Rows select dataRow["TopicValue"].ToString()));
  809.  
  810.                 if (topicsList.Count < numberOfTags)
  811.                 {
  812.                     da = new OdbcDataAdapter
  813.                     {
  814.                         SelectCommand = new OdbcCommand { CommandText = queryEvents, Connection = conn }
  815.                     };
  816.  
  817.                     var dt2 = new DataTable();
  818.                     var externalEntityIdColumn = new DataColumn("externalentityid", Type.GetType("System.String"));
  819.                     dt2.Columns.Add(externalEntityIdColumn);
  820.                     da.Fill(dt2);
  821.  
  822.                     var tListTopics = (from DataRow dataRow in dt2.Rows
  823.                                        select TopicService.Find(string.Format("RelatedEntityId = {0}", dataRow["externalentityid"]))).Aggregate(new TList<Topic>(),
  824.                                            (res, list) =>
  825.                                            {
  826.                                                res.AddRange(list);
  827.                                                return res;
  828.                                            });
  829.                     topicsList.AddRange(tListTopics.Where(x => !topicsList.Contains(x.TopicValue)).TakeWhile((member, index) => topicsList.Count <= numberOfTags).Select(x => x.TopicValue));
  830.  
  831.                     if (topicsList.Count < numberOfTags)
  832.                     {
  833.                         da = new OdbcDataAdapter
  834.                         {
  835.                             SelectCommand = new OdbcCommand { CommandText = queryRandomTopics, Connection = conn }
  836.                         };
  837.                         var dt3 = new DataTable();
  838.                         var topicValueColumnDt3 = new DataColumn("TopicValue", Type.GetType("System.String"));
  839.                         dt3.Columns.Add(topicValueColumnDt3);
  840.                         dt3.PrimaryKey = new[] { topicValueColumnDt3 };
  841.                         da.Fill(dt3);
  842.                         topicsList.AddRange((from DataRow dataRow in dt3.Rows where !topicsList.Contains(dataRow["TopicValue"].ToString()) select dataRow["TopicValue"].ToString())
  843.                                   .TakeWhile((member, index) => topicsList.Count <= numberOfTags));
  844.                     }
  845.                 }
  846.             }
  847.             catch (Exception ex) { }
  848.             finally
  849.             {
  850.                 conn.Close();
  851.             }
  852.  
  853.             retDict = new Dictionary<string, int>();
  854.             foreach (var tag in topicsList)
  855.             {
  856.                 int count;
  857.                 retDict[tag] = TopicService.GetTotalItems(string.Format("TopicValue = '{0}'", tag), out count);
  858.             }
  859.  
  860.             return retDict;
  861.         }
  862.  
  863.         public Dictionary<string, int> GetTrendingTopics(TopicsEnumerator type, int numberOfTags, int lastMonths)
  864.         {
  865.             var st1 = new Stopwatch();
  866.  
  867.             Dictionary<string, int> retDict = null;
  868.             var topicsList = new List<string>();
  869.             var queryContents =
  870.                 type == TopicsEnumerator.User ?
  871.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{2}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.SpeakerClick, (int)ActivityTypeEnumerator.UserFollowClick, lastMonths) :
  872.                 type == TopicsEnumerator.Event ?
  873.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{2}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.EventClick, (int)ActivityTypeEnumerator.EventFollowClick, lastMonths) :
  874.                 type == TopicsEnumerator.Video ?
  875.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{4}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.VideoView, (int)ActivityTypeEnumerator.VideoLike, (int)ActivityTypeEnumerator.VideoComment, (int)ActivityTypeEnumerator.VideoShare, lastMonths) :
  876.                 type == TopicsEnumerator.Image ?
  877.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{4}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.ImageView, (int)ActivityTypeEnumerator.ImageLike, (int)ActivityTypeEnumerator.ImageComment, (int)ActivityTypeEnumerator.ImageShare, lastMonths) :
  878.                 type == TopicsEnumerator.Slide ?
  879.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{4}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.SlideView, (int)ActivityTypeEnumerator.SlideLike, (int)ActivityTypeEnumerator.SlideComment, (int)ActivityTypeEnumerator.SlideShare, lastMonths) :
  880.                 string.Format(@"SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog
  881.                                WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}
  882.                                OR ClickType={4} OR ClickType={5} OR ClickType={6} OR ClickType={7}
  883.                                OR ClickType={8} OR ClickType={9} OR ClickType={10} OR ClickType={11}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{12}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50",
  884.                                 (int)ActivityTypeEnumerator.VideoView, (int)ActivityTypeEnumerator.VideoLike, (int)ActivityTypeEnumerator.VideoComment, (int)ActivityTypeEnumerator.VideoShare,
  885.                                 (int)ActivityTypeEnumerator.ImageView, (int)ActivityTypeEnumerator.ImageLike, (int)ActivityTypeEnumerator.ImageComment, (int)ActivityTypeEnumerator.ImageShare,
  886.                                 (int)ActivityTypeEnumerator.SlideView, (int)ActivityTypeEnumerator.SlideLike, (int)ActivityTypeEnumerator.SlideComment, (int)ActivityTypeEnumerator.SlideShare,
  887.                                 lastMonths);
  888.             var queryAllContents = type == TopicsEnumerator.Event ?
  889.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{2}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.EventClick, (int)ActivityTypeEnumerator.EventFollowClick, lastMonths) :
  890.                 type == TopicsEnumerator.Video ?
  891.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{4}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.VideoView, (int)ActivityTypeEnumerator.VideoLike, (int)ActivityTypeEnumerator.VideoComment, (int)ActivityTypeEnumerator.VideoShare, lastMonths) :
  892.                 type == TopicsEnumerator.Image ?
  893.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{4}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.ImageView, (int)ActivityTypeEnumerator.ImageLike, (int)ActivityTypeEnumerator.ImageComment, (int)ActivityTypeEnumerator.ImageShare, lastMonths) :
  894.                 type == TopicsEnumerator.Slide ?
  895.                 string.Format("SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{4}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50", (int)ActivityTypeEnumerator.SlideView, (int)ActivityTypeEnumerator.SlideLike, (int)ActivityTypeEnumerator.SlideComment, (int)ActivityTypeEnumerator.SlideShare, lastMonths) :
  896.                 string.Format(@"SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog
  897.                                WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}
  898.                                OR ClickType={4} OR ClickType={5} OR ClickType={6} OR ClickType={7}
  899.                                OR ClickType={8} OR ClickType={9} OR ClickType={10} OR ClickType={11}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{12}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50",
  900.                                 (int)ActivityTypeEnumerator.VideoView, (int)ActivityTypeEnumerator.VideoLike, (int)ActivityTypeEnumerator.VideoComment, (int)ActivityTypeEnumerator.VideoShare,
  901.                                 (int)ActivityTypeEnumerator.ImageView, (int)ActivityTypeEnumerator.ImageLike, (int)ActivityTypeEnumerator.ImageComment, (int)ActivityTypeEnumerator.ImageShare,
  902.                                 (int)ActivityTypeEnumerator.SlideView, (int)ActivityTypeEnumerator.SlideLike, (int)ActivityTypeEnumerator.SlideComment, (int)ActivityTypeEnumerator.SlideShare,
  903.                                 lastMonths);
  904.  
  905.             var connString = "Driver={Amazon Redshift (x86)};" +
  906.                     String.Format("Server={0};Database={1};" +
  907.                     "UID={2};PWD={3};Port={4}",
  908.                     server, AmazonRedshiftDatabaseName, masterUsername,
  909.                     masterUserPassword, port);
  910.             var conn = new OdbcConnection(connString);
  911.  
  912.             st1.Start();
  913.             try
  914.             {
  915.                 conn.Open();
  916.                 var da = new OdbcDataAdapter
  917.                 {
  918.                     SelectCommand = new OdbcCommand { CommandText = queryContents, Connection = conn }
  919.                 };
  920.  
  921.                 Debug.WriteLine("Open conn and execute query : " + st1.ElapsedMilliseconds);
  922.  
  923.                 st1.Reset();
  924.                 st1.Start();
  925.                 var dt2 = new DataTable();
  926.                 var externalColumn2 = new DataColumn("externalentityid", Type.GetType("System.String"));
  927.                 dt2.Columns.Add(externalColumn2);
  928.                 dt2.PrimaryKey = new[] { externalColumn2 };
  929.                 da.Fill(dt2);
  930.  
  931.                 foreach (DataRow row in dt2.Rows)
  932.                 {
  933.                     var contentId = row["externalentityid"].ToString();
  934.                     int count;
  935.                     var contentWithTopics =
  936.                         type != TopicsEnumerator.AllMedia
  937.                         ? TopicService.Find(string.Format("RelatedEntityId = {0} AND RelatedEntityType={1}", contentId,
  938.                             (int)type))
  939.                         : TopicService.GetPaged(
  940.                             string.Format(
  941.                                 "RelatedEntityId = {0} AND (RelatedEntityType={1} OR RelatedEntityType={2} OR RelatedEntityType={3})",
  942.                                 contentId, (int)TopicsEnumerator.Video, (int)TopicsEnumerator.Image,
  943.                                 (int)TopicsEnumerator.Slide), "", 0, numberOfTags, out count);
  944.                     if (contentWithTopics == null || !contentWithTopics.Any()) continue;
  945.                     foreach (var item in contentWithTopics.TakeWhile(item => topicsList.Count() != numberOfTags).Where(item => !topicsList.Contains(item.TopicValue)))
  946.                     {
  947.                         topicsList.Add(item.TopicValue);
  948.                     }
  949.                 }
  950.                
  951.                 Debug.WriteLine("Iterate through results from AR : " + st1.ElapsedMilliseconds);
  952.  
  953.                 if (topicsList.Count() < numberOfTags)
  954.                 {
  955.                     int remained;
  956.                     var topicsRemained = TopicService.GetPaged(string.Format("RelatedEntityType={0}", (int)type), "", 0,
  957.                         numberOfTags, out remained);
  958.                     foreach (
  959.                         var item in
  960.                             topicsRemained.Where(item => !topicsList.Contains(item.TopicValue))
  961.                                 .TakeWhile(item => topicsList.Count() < numberOfTags))
  962.                     {
  963.                         topicsList.Add(item.TopicValue);
  964.                     }
  965.                 }
  966.                 st1.Reset();
  967.                 st1.Start();
  968.                 retDict = new Dictionary<string, int>();
  969.                 if (type != TopicsEnumerator.AllMedia && type != TopicsEnumerator.User && type != TopicsEnumerator.Event)
  970.                     retDict = MediaService.GetTrendingTopicsForMedia((int)type).Tables[0].Rows.Cast<DataRow>().ToDictionary(row => row["TopicValue"].ToString(), row => int.Parse(row["CntTopics"].ToString()));
  971.  
  972.                 // todo: da se proveri koga type=event dali moze da se izvadat site rezultati so 1 povik do baza
  973.                 foreach (var tag in topicsList)
  974.                 {
  975.                     int count;
  976.                     switch (type)
  977.                     {
  978.                         case TopicsEnumerator.AllMedia:
  979.                             retDict[tag] = TopicService.GetTotalItems(
  980.                             string.Format(
  981.                                 "TopicValue = '{0}' AND (RelatedEntityType='{1}' OR RelatedEntityType='{2}' OR RelatedEntityType='{3}')",
  982.                                 tag, (int)TopicsEnumerator.Video, (int)TopicsEnumerator.Image,
  983.                                 (int)TopicsEnumerator.Slide), out count);
  984.                             break;
  985.                         case TopicsEnumerator.User:
  986.                         case TopicsEnumerator.Event:
  987.                             count = TopicService.GetEventCountByTopicValueAndRelatedEntityType(tag, (int)type, 0);
  988.                             retDict[tag] = count;
  989.                             break;
  990.                         //case TopicsEnumerator.Video:
  991.                         //    count = TopicService.GetEventCountByTopicValueAndRelatedEntityType(tag, (int)type, (int)MediaTypeEnum.Video);
  992.                         //    retDict[tag] = count;
  993.                         //    break;
  994.                         //case TopicsEnumerator.Slide:
  995.                         //    count = TopicService.GetEventCountByTopicValueAndRelatedEntityType(tag, (int)type, (int)MediaTypeEnum.Slide);
  996.                         //    retDict[tag] = count;
  997.                         //    break;
  998.                         //case TopicsEnumerator.Image:
  999.                         //    count = TopicService.GetEventCountByTopicValueAndRelatedEntityType(tag, (int)type, (int)MediaTypeEnum.Image);
  1000.                         //    retDict[tag] = count;
  1001.                         //    break;
  1002.                     }
  1003.                 }
  1004.                 st1.Stop();
  1005.                 Debug.WriteLine("Iterate through each topic and get the count : " + st1.ElapsedMilliseconds);
  1006.                
  1007.             }
  1008.             catch (Exception ex)
  1009.             {
  1010.                 LogUtility.LogException(ex);
  1011.             }
  1012.             finally
  1013.             {
  1014.                 conn.Close();
  1015.             }
  1016.  
  1017.             return retDict ?? GetRecommendedTagsWithCount(topicsList, numberOfTags);
  1018.         }
  1019.  
  1020.         public Dictionary<string, int> GetMostlyClickedTopicsForUser(string userId, int lastMonths, int numberOfTags, bool countTopicsNeeded = false, OdbcConnection openConnection = null)
  1021.         {
  1022.             Dictionary<string, int> retDict = null;
  1023.             var topicsList = new List<string>();
  1024.             var queryTopics = string.Format("SELECT actlog.activityvalue, COUNT(actlog.activityvalue) AS num FROM tagging.activityLog actlog WHERE actlog.ClickType={0} AND userid='{1}' AND actiondate > ADD_MONTHS(CURRENT_DATE,-{2}) GROUP BY actlog.activityvalue ORDER BY num DESC LIMIT {3}", (int)ActivityTypeEnumerator.TagClick, userId, lastMonths, numberOfTags);
  1025.             var connString = "Driver={Amazon Redshift (x86)};" +
  1026.                     String.Format("Server={0};Database={1};" +
  1027.                     "UID={2};PWD={3};Port={4}",
  1028.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1029.                     masterUserPassword, port);
  1030.             var conn = openConnection ?? new OdbcConnection(connString);
  1031.  
  1032.             try
  1033.             {
  1034.                 if (conn.State != ConnectionState.Open)
  1035.                     conn.Open();
  1036.  
  1037.                 var da = new OdbcDataAdapter
  1038.                 {
  1039.                     SelectCommand = new OdbcCommand { CommandText = queryTopics, Connection = conn }
  1040.                 };
  1041.  
  1042.                 var dt1 = new DataTable();
  1043.                 var activityValueColumn = new DataColumn("activityvalue", Type.GetType("System.String"));
  1044.                 dt1.Columns.Add(activityValueColumn);
  1045.                 dt1.PrimaryKey = new[] { activityValueColumn };
  1046.                 da.Fill(dt1);
  1047.  
  1048.                 retDict = new Dictionary<string, int>();
  1049.                 foreach (DataRow row in dt1.Rows)
  1050.                 {
  1051.                     int count;
  1052.                     var item = row["activityvalue"].ToString();
  1053.                     retDict[item] = countTopicsNeeded ? TopicService.GetTotalItems(string.Format("TopicValue = '{0}'", item), out count) : 0;
  1054.                 }
  1055.             }
  1056.             catch (Exception ex)
  1057.             {
  1058.                 LogUtility.LogException(ex);
  1059.             }
  1060.             finally
  1061.             {
  1062.                 conn.Close();
  1063.             }
  1064.             return retDict;
  1065.         }
  1066.  
  1067.         public List<string> GetMostPopularTopics(int lastMonths, int numberOfTags)
  1068.         {
  1069.             var topicsList = new List<string>();
  1070.             var queryAllContents =
  1071.                 string.Format(
  1072.                 @"SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}
  1073.                OR ClickType={4} OR ClickType={5} OR ClickType={6} OR ClickType={7}
  1074.                OR ClickType={8} OR ClickType={9} OR ClickType={10} OR ClickType={11}) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{12}) GROUP BY externalentityid ORDER BY num DESC LIMIT 50",
  1075.                 (int)ActivityTypeEnumerator.VideoView, (int)ActivityTypeEnumerator.VideoLike,
  1076.                 (int)ActivityTypeEnumerator.VideoComment, (int)ActivityTypeEnumerator.VideoShare,
  1077.                 (int)ActivityTypeEnumerator.ImageView, (int)ActivityTypeEnumerator.ImageLike,
  1078.                 (int)ActivityTypeEnumerator.ImageComment, (int)ActivityTypeEnumerator.ImageShare,
  1079.                 (int)ActivityTypeEnumerator.SlideView, (int)ActivityTypeEnumerator.SlideLike,
  1080.                 (int)ActivityTypeEnumerator.SlideComment, (int)ActivityTypeEnumerator.SlideShare,
  1081.                 lastMonths);
  1082.  
  1083.             var connString = "Driver={Amazon Redshift (x86)};" +
  1084.                     String.Format("Server={0};Database={1};" +
  1085.                     "UID={2};PWD={3};Port={4}",
  1086.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1087.                     masterUserPassword, port);
  1088.  
  1089.             var conn = new OdbcConnection(connString);
  1090.             try
  1091.             {
  1092.                 conn.Open();
  1093.  
  1094.                 var da = new OdbcDataAdapter
  1095.                 {
  1096.                     SelectCommand = new OdbcCommand { CommandText = queryAllContents, Connection = conn }
  1097.                 };
  1098.  
  1099.                 var dt1 = new DataTable();
  1100.                 var externalColumn = new DataColumn("externalentityid", Type.GetType("System.String"));
  1101.                 dt1.Columns.Add(externalColumn);
  1102.                 dt1.PrimaryKey = new[] { externalColumn };
  1103.                 da.Fill(dt1);
  1104.  
  1105.                 foreach (DataRow row in dt1.Rows)
  1106.                 {
  1107.                     var contentId = row["externalentityid"].ToString();
  1108.                     int count;
  1109.                     var contentsWithTopics = TopicService.GetPaged(
  1110.                         string.Format(
  1111.                             "RelatedEntityId = '{0}' AND (RelatedEntityType='{1}' OR RelatedEntityType='{2}' OR RelatedEntityType='{3}')",
  1112.                             contentId, (int)TopicsEnumerator.Video, (int)TopicsEnumerator.Image,
  1113.                             (int)TopicsEnumerator.Slide), "RelatedEntityId", 0, 50, out count);
  1114.                     if (contentsWithTopics == null || !contentsWithTopics.Any()) continue;
  1115.                     foreach (
  1116.                         var item in
  1117.                             contentsWithTopics.TakeWhile(item => topicsList.Count() != numberOfTags)
  1118.                                 .Where(item => !topicsList.Contains(item.TopicValue)))
  1119.                     {
  1120.                         topicsList.Add(item.TopicValue);
  1121.                     }
  1122.                 }
  1123.             }
  1124.             catch (Exception ex)
  1125.             {
  1126.             }
  1127.             finally
  1128.             {
  1129.                 conn.Close();
  1130.             }
  1131.  
  1132.             return topicsList;
  1133.         }
  1134.  
  1135.         #endregion
  1136.  
  1137.         #region Get recommended Events for users
  1138.  
  1139.         public DataTable GetEventsList(List<string> events, int numberOfEvents)
  1140.         {
  1141.             var retList = new List<string>();
  1142.  
  1143.             var eventClusterIds = GetEventClusterIds(events);
  1144.  
  1145.             var query = string.Format("SELECT * FROM tagging.EventClusters WHERE eventclusterid={0}", eventClusterIds.FirstOrDefault());
  1146.             for (var i = 0; i < eventClusterIds.Count; i++)
  1147.                 query += string.Format(" OR eventclusterid={0}", eventClusterIds[i]);
  1148.             query += string.Format(" ORDER BY RANDOM() LIMIT " + numberOfEvents);
  1149.  
  1150.             var connString = "Driver={Amazon Redshift (x86)};" +
  1151.                     String.Format("Server={0};Database={1};" +
  1152.                     "UID={2};PWD={3};Port={4}",
  1153.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1154.                     masterUserPassword, port);
  1155.             var conn = new OdbcConnection(connString);
  1156.  
  1157.             var dt1 = new DataTable();
  1158.             var eventIdColumn = new DataColumn("eventid", Type.GetType("System.String"));
  1159.             dt1.Columns.Add(eventIdColumn);
  1160.             dt1.PrimaryKey = new[] { eventIdColumn };
  1161.  
  1162.             try
  1163.             {
  1164.                 conn.Open();
  1165.  
  1166.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  1167.                 da.Fill(dt1);
  1168.             }
  1169.             catch (Exception ex)
  1170.             {
  1171.             }
  1172.             finally
  1173.             {
  1174.                 conn.Close();
  1175.             }
  1176.             return dt1;
  1177.         }
  1178.  
  1179.         public List<int> GetEventClusterIds(List<string> events)
  1180.         {
  1181.             if (!events.Any())
  1182.                 return new List<int>();
  1183.             var retList = new List<int>();
  1184.             var query = string.Format("SELECT * FROM tagging.EventClusters WHERE eventid='{0}'", events.FirstOrDefault());
  1185.             for (var i = 1; i < events.Count; i++)
  1186.                 query += string.Format(" OR eventid='{0}'", events[i]);
  1187.  
  1188.             var connString = "Driver={Amazon Redshift (x86)};" +
  1189.                     String.Format("Server={0};Database={1};" +
  1190.                     "UID={2};PWD={3};Port={4}",
  1191.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1192.                     masterUserPassword, port);
  1193.             var conn = new OdbcConnection(connString);
  1194.  
  1195.             var dt1 = new DataTable();
  1196.             var eventIdColumn = new DataColumn("eventid", Type.GetType("System.String"));
  1197.             dt1.Columns.Add(eventIdColumn);
  1198.             dt1.PrimaryKey = new[] { eventIdColumn };
  1199.  
  1200.             try
  1201.             {
  1202.                 conn.Open();
  1203.  
  1204.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  1205.                 da.Fill(dt1);
  1206.             }
  1207.             catch (Exception ex)
  1208.             {
  1209.             }
  1210.             finally
  1211.             {
  1212.                 conn.Close();
  1213.             }
  1214.             return (from DataRow row in dt1.Rows
  1215.                     select int.Parse(row[""].ToString())).ToList();
  1216.         }
  1217.  
  1218.         public DataTable GetRecommendedEventsTable(string topics, int numberOfEvents, DateTime dateTo, double minLat = 0.0, double maxLat = 0.0, double minLon = 0.0, double maxLon = 0.0)
  1219.         {
  1220.             if (topics == null) return new DataTable();
  1221.  
  1222.             var result =
  1223.                 TopicService.Event_GetEventsForConferenceWidget(
  1224.                     "\'" + topics + "\'", numberOfEvents, dateTo, minLat,
  1225.                     maxLat, minLon, maxLon);
  1226.             if (result != null && result.Tables.Count > 0)
  1227.                 return result.Tables[0];
  1228.             return new DataTable();
  1229.         }
  1230.  
  1231.         #endregion
  1232.  
  1233.         #region People
  1234.  
  1235.         /// <summary>
  1236.         /// Construct matrix according to the connection of users by events.
  1237.         /// </summary>
  1238.         /// <param name="matrix"></param>
  1239.         /// <returns>Updated matrix with connected tags.</returns>
  1240.         public double[][] JoinUsersOnEvents(double[][] matrix, List<string> tags)
  1241.         {
  1242.             try
  1243.             {
  1244.                 var userEvents = UserService.User_JoinUsersOnEvents();
  1245.  
  1246.                 foreach (DataRow row in userEvents.Tables[0].Rows)
  1247.                 {
  1248.                     if (!tags.Contains(row["UserId1"].ToString()) || !tags.Contains(row["UserId2"].ToString())) continue;
  1249.                     if (row["UserId1"].ToString() == row["UserId2"].ToString()) continue;
  1250.  
  1251.                     var index1 = tags.IndexOf(row["UserId1"].ToString());
  1252.                     var index2 = tags.IndexOf(row["UserId2"].ToString());
  1253.                     matrix[index1][index2] = matrix[index2][index1] += 3;
  1254.                 }
  1255.                 return matrix;
  1256.             }
  1257.             catch (Exception ex)
  1258.             {
  1259.                 throw new Exception(ex.ToString());
  1260.             }
  1261.         }
  1262.  
  1263.         public double[][] UsersFollowUsers(double[][] matrix, List<string> tags)
  1264.         {
  1265.             try
  1266.             {
  1267.                 var followUsers = UserFollowService.GetAll().ToList();
  1268.  
  1269.                 foreach (var row in followUsers)
  1270.                 {
  1271.                     if (!tags.Contains(row.UserId.ToString()) || !tags.Contains(row.FollowedUserId.ToString()))
  1272.                         continue;
  1273.                     if (row.UserId.ToString() == row.FollowedUserId.ToString()) continue;
  1274.  
  1275.                     var index1 = tags.IndexOf(row.UserId.ToString());
  1276.                     var index2 = tags.IndexOf(row.FollowedUserId.ToString());
  1277.                     matrix[index1][index2] = matrix[index2][index1] += 5;
  1278.                 }
  1279.                 return matrix;
  1280.             }
  1281.             catch (Exception ex)
  1282.             {
  1283.                 throw new Exception(ex.ToString());
  1284.             }
  1285.  
  1286.         }
  1287.  
  1288.         public double[][] ConstructUsersMatrix()
  1289.         {
  1290.             try
  1291.             {
  1292.                 var allUsers = UserService.GetAll().Distinct().ToList();
  1293.  
  1294.                 tags = new List<string>();
  1295.                 foreach (var singleUser in allUsers)
  1296.                 {
  1297.                     tags.Add(singleUser.UserId.ToString());
  1298.                 }
  1299.  
  1300.                 var matrix = new double[allUsers.Count()][];
  1301.                 for (int i = 0; i < allUsers.Count(); i++)
  1302.                 {
  1303.                     matrix[i] = new double[allUsers.Count];
  1304.                     matrix[i][i] = 1;
  1305.                 }
  1306.  
  1307.                 matrix = JoinUsersOnEvents(matrix, tags);
  1308.                 matrix = UsersFollowUsers(matrix, tags);
  1309.                 return matrix;
  1310.             }
  1311.             catch (Exception ex)
  1312.             {
  1313.                 throw new Exception(ex.ToString());
  1314.             }
  1315.         }
  1316.  
  1317.         public void GenerateUserClusters()
  1318.         {
  1319.             MCLAlgorithm mclAlgorithm = new MCLAlgorithm();
  1320.  
  1321.             var matrixConstruction = ConstructUsersMatrix();
  1322.  
  1323.             //var matrixNormalisation = mclAlgorithm.MatrixNormalisation(matrixConstruction);
  1324.  
  1325.             //var matrixExponential = mclAlgorithm.MatrixProductExponential(matrixNormalisation, mclAlgorithm.matrixPower);
  1326.  
  1327.             //var matrixInflation = mclAlgorithm.MatrixInflate(matrixExponential, mclAlgorithm.matrixPower);
  1328.  
  1329.             //matrixInflation = mclAlgorithm.Repeat(matrixInflation);
  1330.  
  1331.             //var matrixInterpretated = mclAlgorithm.InterpretResulting(matrixInflation);
  1332.  
  1333.             List<List<int>> groups = mclAlgorithm.groups;
  1334.  
  1335.             CleanUserClusters();
  1336.  
  1337.             for (var i = 0; i < groups.Count; i++)
  1338.             {
  1339.                 for (var j = 0; j < groups[i].Count; j++)
  1340.                 {
  1341.                     InsertEventClustersRecord(i + 1, Convert.ToInt64(tags[groups[i][j] - 1]));
  1342.                 }
  1343.             }
  1344.         }
  1345.  
  1346.         public void InsertUserClustersRecord(int tagUserClusterId, Guid userId)
  1347.         {
  1348.             var query = string.Format("INSERT INTO tagging.UserClusters(userClusterId,userId)" +
  1349.                                          " VALUES('{0}','{1}')", tagUserClusterId, userId);
  1350.  
  1351.  
  1352.             var connString = "Driver={Amazon Redshift (x86)};" +
  1353.                     String.Format("Server={0};Database={1};" +
  1354.                     "UID={2};PWD={3};Port={4}",
  1355.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1356.                     masterUserPassword, port);
  1357.             var conn = new OdbcConnection(connString);
  1358.  
  1359.             try
  1360.             {
  1361.                 conn.Open();
  1362.  
  1363.                 var da = new OdbcDataAdapter { InsertCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  1364.                 da.InsertCommand.ExecuteNonQuery();
  1365.             }
  1366.             catch (Exception ex)
  1367.             {
  1368.             }
  1369.             finally
  1370.             {
  1371.                 conn.Close();
  1372.             }
  1373.         }
  1374.  
  1375.         public void CleanUserClusters()
  1376.         {
  1377.             var query = string.Format("DELETE FROM tagging.UserClusters");
  1378.  
  1379.             var connString = "Driver={Amazon Redshift (x86)};" +
  1380.                     String.Format("Server={0};Database={1};" +
  1381.                     "UID={2};PWD={3};Port={4}",
  1382.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1383.                     masterUserPassword, port);
  1384.  
  1385.             var conn = new OdbcConnection(connString);
  1386.             try
  1387.             {
  1388.                 conn.Open();
  1389.  
  1390.                 var da = new OdbcDataAdapter { DeleteCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  1391.                 da.DeleteCommand.ExecuteNonQuery();
  1392.             }
  1393.             catch (Exception ex)
  1394.             {
  1395.             }
  1396.             finally
  1397.             {
  1398.                 conn.Close();
  1399.             }
  1400.         }
  1401.  
  1402.         public DataSet GetUserRecentActivitiesObjects(string userId)
  1403.         {
  1404.             Stopwatch st = new Stopwatch();
  1405.             var topicsList = new List<string>();
  1406.  
  1407.             var connString = "Driver={Amazon Redshift (x86)};" +
  1408.                     String.Format("Server={0};Database={1};" +
  1409.                     "UID={2};PWD={3};Port={4}",
  1410.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1411.                     masterUserPassword, port);
  1412.  
  1413.             var conn = new OdbcConnection(connString);
  1414.  
  1415.  
  1416.             DataSet ds = new DataSet();
  1417.             try
  1418.             {
  1419.                 st.Start();
  1420.                 conn.Open();
  1421.                 st.Stop();
  1422.                 Debug.WriteLine(" 1 1 " + st.ElapsedMilliseconds);
  1423.                 st.Reset();
  1424.  
  1425.                 st.Start();
  1426.                 #region events
  1427.  
  1428.  
  1429.  
  1430.  
  1431.                 Dictionary<string, int> clickedTopics = new Dictionary<string, int>();
  1432.  
  1433.                 DataTable clickedEventIds = new DataTable();
  1434.                 DataTable eventsFromTopics = new DataTable();
  1435.  
  1436.                 DataColumn eventIdColumn = new DataColumn("EventId");
  1437.                 eventIdColumn.DataType = System.Type.GetType("System.Int64");
  1438.  
  1439.                 clickedEventIds.Columns.Add(eventIdColumn);
  1440.  
  1441.                 DataColumn popularityColumn = new DataColumn("PopularityValue");
  1442.                 popularityColumn.DataType = System.Type.GetType("System.Double");
  1443.  
  1444.                 clickedEventIds.Columns.Add(popularityColumn);
  1445.  
  1446.                 clickedEventIds.PrimaryKey = new DataColumn[] { eventIdColumn };
  1447.  
  1448.  
  1449.  
  1450.                 var queryEvents = string.Format("select top 20 externalentityid as EventId, count(externalentityid) as PopularityValue from tagging.activityLog WHERE userid = '{0}' and clicktype in ({1},{2}) group by externalentityid order by PopularityValue desc;", userId, (int)ActivityTypeEnumerator.EventClick, (int)ActivityTypeEnumerator.EventFollowClick);
  1451.  
  1452.  
  1453.  
  1454.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = queryEvents, Connection = conn } };
  1455.                 //var reader = da.SelectCommand.ExecuteReader();
  1456.  
  1457.                 da.Fill(clickedEventIds);
  1458.                 st.Stop();
  1459.                 Debug.WriteLine(" 1 clickedEventIds " + st.ElapsedMilliseconds);
  1460.                 st.Reset();
  1461.  
  1462.                 st.Start();
  1463.  
  1464.                 //while (reader.Read())
  1465.                 //{
  1466.                 //  var clicked = reader["externalentityid"].ToString();
  1467.                 //  DataRow dr = clickedEventIds.NewRow();
  1468.  
  1469.                 //  dr["EventId"] = clicked;
  1470.                 //  clickedEventIds.Rows.Add(dr);
  1471.  
  1472.                 //}
  1473.  
  1474.  
  1475.  
  1476.                 clickedTopics = GetMostlyClickedTopicsForUser(userId, 1, 20, false, conn);
  1477.                 st.Stop();
  1478.                 Debug.WriteLine(" 1 get mostly clicked topics " + st.ElapsedMilliseconds);
  1479.                 st.Reset();
  1480.  
  1481.                 st.Start();
  1482.  
  1483.                 DataTable dt = GetRecommendedEventsTable(String.Join(",", clickedTopics.Select(x => x.Key)), 15, DateTime.Now.AddMonths(3));
  1484.  
  1485.                 st.Stop();
  1486.                 Debug.WriteLine(" 1 get recommended events " + st.ElapsedMilliseconds);
  1487.                 st.Reset();
  1488.  
  1489.                 st.Start();
  1490.  
  1491.                 eventsFromTopics = new DataView(dt).ToTable(false, "EventId");
  1492.                 clickedEventIds.Merge(eventsFromTopics);
  1493.  
  1494.  
  1495.                 #endregion
  1496.                 st.Stop();
  1497.                 Debug.WriteLine(" 1 2 " + st.ElapsedMilliseconds);
  1498.                 st.Reset();
  1499.  
  1500.                 st.Start();
  1501.                 #region users
  1502.                 DataTable finalUsersList = new DataTable();
  1503.  
  1504.                 DataColumn UserIdColumn = new DataColumn("UserId");
  1505.                 UserIdColumn.DataType = System.Type.GetType("System.Guid");
  1506.  
  1507.                 finalUsersList.Columns.Add(UserIdColumn);
  1508.                 finalUsersList.PrimaryKey = new DataColumn[] { UserIdColumn };
  1509.  
  1510.                 DataColumn UserpopularityColumn = new DataColumn("PopularityValue");
  1511.                 UserpopularityColumn.DataType = System.Type.GetType("System.Double");
  1512.  
  1513.                 finalUsersList.Columns.Add(UserpopularityColumn);
  1514.  
  1515.                 var queryUsers = string.Format("Select top 20 activityvalue as UserId, count(activityvalue) as PopularityValue FROM tagging.activityLog Where clicktype = {0} and userid = '{1}' group by activityvalue order by PopularityValue desc ", (int)ActivityTypeEnumerator.UserFollowClick, userId);
  1516.  
  1517.                 da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = queryUsers, Connection = conn } };
  1518.  
  1519.                 da.Fill(finalUsersList);
  1520.  
  1521.  
  1522.                 #endregion
  1523.                 st.Stop();
  1524.                 Debug.WriteLine(" 1 3 " + st.ElapsedMilliseconds);
  1525.                 st.Reset();
  1526.  
  1527.                 st.Start();
  1528.                 #region Media
  1529.                 DataTable finalMediaList = new DataTable();
  1530.  
  1531.                 DataColumn MediaIdColumn = new DataColumn("MediaId");
  1532.                 MediaIdColumn.DataType = System.Type.GetType("System.Int64");
  1533.  
  1534.                 finalMediaList.Columns.Add(MediaIdColumn);
  1535.                 finalMediaList.PrimaryKey = new DataColumn[] { MediaIdColumn };
  1536.  
  1537.                 DataColumn mediaPopularityColumn = new DataColumn("PopularityValue");
  1538.                 mediaPopularityColumn.DataType = System.Type.GetType("System.Double");
  1539.  
  1540.                 finalMediaList.Columns.Add(mediaPopularityColumn);
  1541.  
  1542.                 var queryMedia = string.Format("Select top 20 externalentityid as MediaId, count(externalentityid) as PopularityValue FROM tagging.activityLog Where clicktype in ({0},{1}) and userid = '{2}' group by externalentityid order by PopularityValue desc ", (int)ActivityTypeEnumerator.PresentationClick, (int)ActivityTypeEnumerator.VideoClick, userId);
  1543.  
  1544.                 da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = queryMedia, Connection = conn } };
  1545.                 //reader = da.SelectCommand.ExecuteReader();
  1546.                 da.Fill(finalMediaList);
  1547.  
  1548.  
  1549.  
  1550.                 #endregion
  1551.                 st.Stop();
  1552.                 Debug.WriteLine(" 1 4 " + st.ElapsedMilliseconds);
  1553.                 st.Reset();
  1554.  
  1555.                 st.Start();
  1556.                 ds.Tables.Add(clickedEventIds);
  1557.                 ds.Tables.Add(finalUsersList);
  1558.                 ds.Tables.Add(finalMediaList);
  1559.                 st.Stop();
  1560.                 Debug.WriteLine(" 1 1 " + st.ElapsedMilliseconds);
  1561.                 st.Reset();
  1562.                 //dodadi gi site listi vo datatable;
  1563.  
  1564.                 //ds = GetUserObjectsActivityWall(userId);
  1565.             }
  1566.             catch (Exception ex)
  1567.             {
  1568.             }
  1569.             finally
  1570.             {
  1571.                 conn.Close();
  1572.             }
  1573.  
  1574.             return ds;
  1575.         }
  1576.  
  1577.         public DataSet GetUserObjectsActivityWall(string userId, GeoHelper geoHelperInstanca)
  1578.         {
  1579.  
  1580.             SystemUserService systemUser = new SystemUserService();
  1581.             MediaService mediaService = new MediaService();
  1582.             //TODO:(dimkov) create logic to add popularity
  1583.             DataSet ds = new DataSet();
  1584.             Stopwatch st = new Stopwatch();
  1585.             st.Start();
  1586.             ds = GetUserRecentActivitiesObjects(userId);
  1587.             st.Stop();
  1588.             Debug.WriteLine(" 1 " + st.ElapsedMilliseconds);
  1589.             st.Reset();
  1590.  
  1591.             //GeoHelper geoHelper = new GeoHelper(GeoHelperDatabaseFile);
  1592.             GeoHelper geoHelper = geoHelperInstanca ?? new GeoHelper(GeoHelperDatabaseFile);
  1593.  
  1594.             double[] latLong = geoHelper.GetlatLong();
  1595.             double[] latLongExpanded = geoHelper.GetNearby(latLong[0], latLong[1], 300);
  1596.             double minLat = latLongExpanded[0];
  1597.             double maxLat = latLongExpanded[1];
  1598.             double minLong = latLongExpanded[2];
  1599.             double maxLong = latLongExpanded[3];
  1600.             st.Start();
  1601.             var rEvents = EventInfoService.GetRecommendedByLocationAndPopularity(DateTime.Now.AddMonths(-2),
  1602.                 DateTime.Now.AddMonths(3), minLat, maxLat, minLong, maxLong);
  1603.             var rUsers = systemUser.GetRecommendedByLocationAdnPopularity(minLat, maxLat, minLong, maxLong);
  1604.             var rMedia = mediaService.GetByPopularityAndLocation(DateTime.Now.AddMonths(-2), DateTime.Now, minLat,
  1605.                 maxLat, minLong, maxLong);
  1606.             st.Stop();
  1607.             Debug.WriteLine(" 2 " + st.ElapsedMilliseconds);
  1608.             st.Reset();
  1609.  
  1610.             st.Start();
  1611.             if (ds.Tables.Count > 0)
  1612.             {
  1613.                 ds.Tables[0].Merge(rEvents.Tables[0]);
  1614.             }
  1615.             else
  1616.             {
  1617.                 ds.Tables.Add("Table1");
  1618.                 ds.Tables[0].Merge(rEvents.Tables[0]);
  1619.             }
  1620.  
  1621.             if (ds.Tables.Count > 1)
  1622.             {
  1623.  
  1624.                 ds.Tables[1].Merge(rUsers.Tables[0]);
  1625.             }
  1626.             else
  1627.             {
  1628.                 ds.Tables.Add("Table2");
  1629.                 ds.Tables[1].Merge(rUsers.Tables[0]);
  1630.  
  1631.  
  1632.             }
  1633.             if (ds.Tables.Count > 2)
  1634.             {
  1635.                 ds.Tables[2].Merge(rMedia.Tables[0]);
  1636.             }
  1637.             else
  1638.             {
  1639.                 ds.Tables.Add("Table3");
  1640.                 ds.Tables[2].Merge(rMedia.Tables[0]);
  1641.  
  1642.  
  1643.             }
  1644.             st.Stop();
  1645.             Debug.WriteLine(" 3 " + st.ElapsedMilliseconds);
  1646.             st.Reset();
  1647.             return ds;
  1648.         }
  1649.  
  1650.  
  1651.         #endregion
  1652.  
  1653.         #region Get recommended media for user
  1654.  
  1655.         public List<long> GetMediaList(List<string> media, int numberOfMedia, MediaTypeEnum type)
  1656.         {
  1657.             var mediaClusterIds = GetMediaClusterIds(media, type);
  1658.  
  1659.             var query =
  1660.                 type == MediaTypeEnum.Video ?
  1661.                 string.Format("SELECT * FROM tagging.VideoClusters WHERE videoclusterid={0}", mediaClusterIds.FirstOrDefault()) :
  1662.                 type == MediaTypeEnum.Image ?
  1663.                 string.Format("SELECT * FROM tagging.ImageClusters WHERE imageclusterid={0}", mediaClusterIds.FirstOrDefault()) :
  1664.                 string.Format("SELECT * FROM tagging.SlideClusters WHERE slideclusterid={0}", mediaClusterIds.FirstOrDefault());
  1665.             for (var i = 0; i < mediaClusterIds.Count; i++)
  1666.                 query +=
  1667.                     type == MediaTypeEnum.Video ?
  1668.                     string.Format(" OR videoclusterid={0}", mediaClusterIds[i]) :
  1669.                     type == MediaTypeEnum.Image ?
  1670.                     string.Format(" OR imageclusterid={0}", mediaClusterIds[i]) :
  1671.                     string.Format(" OR slideclusterid={0}", mediaClusterIds[i]);
  1672.             query += string.Format(" ORDER BY RANDOM() LIMIT " + numberOfMedia);
  1673.  
  1674.             var connString = "Driver={Amazon Redshift (x86)};" +
  1675.                     String.Format("Server={0};Database={1};" +
  1676.                     "UID={2};PWD={3};Port={4}",
  1677.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1678.                     masterUserPassword, port);
  1679.             var conn = new OdbcConnection(connString);
  1680.  
  1681.             var index = type == MediaTypeEnum.Video
  1682.                     ? "videoid"
  1683.                     : type == MediaTypeEnum.Image ? "imageid" : "slideid";
  1684.  
  1685.             var dt1 = new DataTable();
  1686.             var mediaColumn = new DataColumn(index);
  1687.             dt1.Columns.Add(mediaColumn);
  1688.             dt1.PrimaryKey = new[] { mediaColumn };
  1689.  
  1690.             try
  1691.             {
  1692.                 conn.Open();
  1693.  
  1694.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  1695.                 da.Fill(dt1);
  1696.             }
  1697.             catch (Exception ex)
  1698.             {
  1699.             }
  1700.             finally
  1701.             {
  1702.                 conn.Close();
  1703.             }
  1704.             return (from DataRow row in dt1.Rows
  1705.                     select long.Parse(row[index].ToString())).ToList();
  1706.         }
  1707.  
  1708.         public List<int> GetMediaClusterIds(List<string> media, MediaTypeEnum type)
  1709.         {
  1710.             if (!media.Any())
  1711.                 return new List<int>();
  1712.             var query =
  1713.                 type == MediaTypeEnum.Video ?
  1714.                 string.Format("SELECT * FROM tagging.VideoClusters WHERE videoid='{0}'", media.FirstOrDefault()) :
  1715.                 type == MediaTypeEnum.Image ?
  1716.                 string.Format("SELECT * FROM tagging.ImageClusters WHERE imageid='{0}'", media.FirstOrDefault()) :
  1717.                 string.Format("SELECT * FROM tagging.SlideClusters WHERE slideid='{0}'", media.FirstOrDefault());
  1718.             for (var i = 1; i < media.Count; i++)
  1719.                 query +=
  1720.                     type == MediaTypeEnum.Video ?
  1721.                     string.Format(" OR videoid='{0}'", media[i]) :
  1722.                     type == MediaTypeEnum.Image ?
  1723.                     string.Format(" OR imageid='{0}'", media[i]) :
  1724.                     string.Format(" OR slideid='{0}'", media[i]);
  1725.  
  1726.             var connString = "Driver={Amazon Redshift (x86)};" +
  1727.                     String.Format("Server={0};Database={1};" +
  1728.                     "UID={2};PWD={3};Port={4}",
  1729.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1730.                     masterUserPassword, port);
  1731.             var conn = new OdbcConnection(connString);
  1732.  
  1733.             var index = type == MediaTypeEnum.Video
  1734.                     ? "videoclusterid"
  1735.                     : type == MediaTypeEnum.Image ? "imageclusterid" : "slideclusterid";
  1736.  
  1737.             var dt1 = new DataTable();
  1738.             var mediaColumn = new DataColumn(index);
  1739.             dt1.Columns.Add(mediaColumn);
  1740.             dt1.PrimaryKey = new[] { mediaColumn };
  1741.  
  1742.             try
  1743.             {
  1744.                 conn.Open();
  1745.  
  1746.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  1747.                 da.Fill(dt1);
  1748.             }
  1749.             catch (Exception ex)
  1750.             {
  1751.             }
  1752.             finally
  1753.             {
  1754.                 conn.Close();
  1755.             }
  1756.             return (from DataRow row in dt1.Rows
  1757.                     select int.Parse(row[index].ToString())).ToList();
  1758.         }
  1759.  
  1760.         public List<long> GetRecommendedMediaForUser(string userId, int numberOfMedia, MediaTypeEnum type, int lastMonths, string topics)
  1761.         {
  1762.             var mediaList = new List<string>();
  1763.             var recomMedia = new List<long>();
  1764.             const string queryString = "SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND userid='{4}' AND (','+related_topics+',' LIKE '%,{5},%' ) AND actiondate > ADD_MONTHS(CURRENT_DATE,-{6}) GROUP BY externalentityid ORDER BY num DESC LIMIT 30";
  1765.  
  1766.             var queryRandomMedia =
  1767.                 type == MediaTypeEnum.Video ?
  1768.                 string.Format("SELECT videoid FROM tagging.videoclusters ORDER BY RANDOM() LIMIT {0}", numberOfMedia) :
  1769.                 type == MediaTypeEnum.Image ?
  1770.                 string.Format("SELECT imageid FROM tagging.imageclusters ORDER BY RANDOM() LIMIT {0}", numberOfMedia) :
  1771.                 string.Format("SELECT slideid FROM tagging.slideclusters ORDER BY RANDOM() LIMIT {0}", numberOfMedia);
  1772.  
  1773.             var connString = "Driver={Amazon Redshift (x86)};" +
  1774.                     String.Format("Server={0};Database={1};" +
  1775.                     "UID={2};PWD={3};Port={4}",
  1776.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1777.                     masterUserPassword, port);
  1778.             var conn = new OdbcConnection(connString);
  1779.  
  1780.             var index = type == MediaTypeEnum.Video
  1781.                         ? "videoid"
  1782.                         : type == MediaTypeEnum.Image ? "imageid" : "slideid";
  1783.  
  1784.             try
  1785.             {
  1786.                 conn.Open();
  1787.  
  1788.                 foreach (var topic in topics.Split(new[] { ',' }))
  1789.                 {
  1790.                     var queryEvents =
  1791.                         type == MediaTypeEnum.Video
  1792.                             ? string.Format(queryString, (int)ActivityTypeEnumerator.VideoView,
  1793.                                 (int)ActivityTypeEnumerator.VideoLike, (int)ActivityTypeEnumerator.VideoComment,
  1794.                                 (int)ActivityTypeEnumerator.VideoShare, userId, topic, lastMonths)
  1795.                             : type == MediaTypeEnum.Image
  1796.                                 ? string.Format(queryString, (int)ActivityTypeEnumerator.ImageView,
  1797.                                     (int)ActivityTypeEnumerator.ImageLike, (int)ActivityTypeEnumerator.ImageComment,
  1798.                                     (int)ActivityTypeEnumerator.ImageShare, userId, topic, lastMonths)
  1799.                                 : string.Format(queryString, (int)ActivityTypeEnumerator.SlideView,
  1800.                                     (int)ActivityTypeEnumerator.SlideLike, (int)ActivityTypeEnumerator.SlideComment,
  1801.                                     (int)ActivityTypeEnumerator.SlideShare, userId, topic, lastMonths);
  1802.  
  1803.                     var da = new OdbcDataAdapter
  1804.                     {
  1805.                         SelectCommand = new OdbcCommand { CommandText = queryEvents, Connection = conn }
  1806.                     };
  1807.  
  1808.                     var dt1 = new DataTable();
  1809.                     var externalColumn = new DataColumn(index, Type.GetType("System.String"));
  1810.                     dt1.Columns.Add(externalColumn);
  1811.  
  1812.                     // ova pravi problem kaj auth user i paga celiot metod... ako misles deka treba da se promeni, slobodno
  1813.                     //dt1.PrimaryKey = new[] { externalColumn };
  1814.  
  1815.                     da.Fill(dt1);
  1816.  
  1817.                     mediaList.AddRange((from DataRow row in dt1.Rows
  1818.                                         select row[index].ToString()).Distinct());
  1819.                 }
  1820.  
  1821.                 recomMedia = GetMediaList(mediaList, numberOfMedia, type);
  1822.  
  1823.                 if (string.IsNullOrEmpty(topics) && mediaList.Count < numberOfMedia)
  1824.                 {
  1825.                     var da = new OdbcDataAdapter
  1826.                     {
  1827.                         SelectCommand = new OdbcCommand { CommandText = queryRandomMedia, Connection = conn }
  1828.                     };
  1829.  
  1830.                     var dt2 = new DataTable();
  1831.                     var externalColumn2 = new DataColumn(index, Type.GetType("System.String"));
  1832.                     dt2.Columns.Add(externalColumn2);
  1833.                     da.Fill(dt2);
  1834.  
  1835.                     recomMedia.AddRange(
  1836.                         (from DataRow row in dt2.Rows
  1837.                          select long.Parse(row[index].ToString())).Distinct().TakeWhile((member, ind) => recomMedia.Count <= numberOfMedia)
  1838.                         );
  1839.                 }
  1840.             }
  1841.             catch (Exception ex)
  1842.             {
  1843.             }
  1844.             finally
  1845.             {
  1846.                 conn.Close();
  1847.             }
  1848.  
  1849.             return recomMedia;
  1850.         }
  1851.  
  1852.         /// <summary>
  1853.         /// Get recommended data for user for Media page. It retrieves 3 tables (videos, pictures and slides) in a DataSet.
  1854.         /// </summary>
  1855.         /// <param name="userId"></param>
  1856.         /// <param name="numberOfMedia"></param>
  1857.         /// <param name="lastMonths"></param>
  1858.         /// <returns>DataSet</returns>
  1859.         public DataSet GetRecommendedMediaForUsersDataSet(string userId, int numberOfMedia, int lastMonths = 3)
  1860.         {
  1861.             var mediaLists = GetRecommendedMediaLists(userId, lastMonths);
  1862.             return MediaService.GetDataForRecommendedMedia(mediaLists[0], mediaLists[1], mediaLists[2], Guid.Parse(userId));
  1863.         }
  1864.  
  1865.         public List<string> GetRecommendedMediaLists(string userId, int lastMonths = 3)
  1866.         {
  1867.             const string queryString = "SELECT externalentityid, COUNT(externalentityid) AS num FROM tagging.activityLog WHERE (ClickType={0} OR ClickType={1} OR ClickType={2} OR ClickType={3}) AND userid='{4}' AND actiondate > ADD_MONTHS(CURRENT_DATE,-{5}) GROUP BY externalentityid ORDER BY num DESC LIMIT 30";
  1868.  
  1869.             var enumList = new[] { MediaTypeEnum.Video, MediaTypeEnum.Image, MediaTypeEnum.Slide };
  1870.             var mediaLists = new List<string>();
  1871.             var connString = "Driver={Amazon Redshift (x86)};" +
  1872.                     String.Format("Server={0};Database={1};" +
  1873.                     "UID={2};PWD={3};Port={4}",
  1874.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1875.                     masterUserPassword, port);
  1876.             var conn = new OdbcConnection(connString);
  1877.  
  1878.             try
  1879.             {
  1880.                 conn.Open();
  1881.  
  1882.                 foreach (var type in enumList)
  1883.                 {
  1884.                     var index = type == MediaTypeEnum.Video
  1885.                         ? "videoid"
  1886.                         : type == MediaTypeEnum.Image ? "imageid" : "slideid";
  1887.  
  1888.                     var queryEvents =
  1889.                         type == MediaTypeEnum.Video
  1890.                             ? string.Format(queryString, (int)ActivityTypeEnumerator.VideoView,
  1891.                                 (int)ActivityTypeEnumerator.VideoLike, (int)ActivityTypeEnumerator.VideoComment,
  1892.                                 (int)ActivityTypeEnumerator.VideoShare, userId, lastMonths)
  1893.                             : type == MediaTypeEnum.Image
  1894.                                 ? string.Format(queryString, (int)ActivityTypeEnumerator.ImageView,
  1895.                                     (int)ActivityTypeEnumerator.ImageLike, (int)ActivityTypeEnumerator.ImageComment,
  1896.                                     (int)ActivityTypeEnumerator.ImageShare, userId, lastMonths)
  1897.                                 : string.Format(queryString, (int)ActivityTypeEnumerator.SlideView,
  1898.                                     (int)ActivityTypeEnumerator.SlideLike, (int)ActivityTypeEnumerator.SlideComment,
  1899.                                     (int)ActivityTypeEnumerator.SlideShare, userId, lastMonths);
  1900.  
  1901.                     var da = new OdbcDataAdapter
  1902.                     {
  1903.                         SelectCommand = new OdbcCommand { CommandText = queryEvents, Connection = conn }
  1904.                     };
  1905.  
  1906.                     var dt1 = new DataTable();
  1907.                     var externalColumn = new DataColumn(index, Type.GetType("System.String"));
  1908.                     dt1.Columns.Add(externalColumn);
  1909.  
  1910.                     da.Fill(dt1);
  1911.  
  1912.                     mediaLists.Add(String.Join(",", (from DataRow row in dt1.Rows
  1913.                                                      select row[index].ToString()).Distinct()));
  1914.                 }
  1915.  
  1916.                 return mediaLists;
  1917.             }
  1918.             catch (Exception ex)
  1919.             {
  1920.             }
  1921.             finally
  1922.             {
  1923.                 conn.Close();
  1924.             }
  1925.  
  1926.             return new List<string> { "", "", "" };
  1927.  
  1928.         }
  1929.  
  1930.         #endregion
  1931.  
  1932.         #region Activity wall functions
  1933.  
  1934.         public List<string> GetUsersActiveList(int minutes = 15)
  1935.         {
  1936.             var retList = new List<string>();
  1937.  
  1938.             var query = string.Format("SELECT userid FROM tagging.ActivityLog WHERE actiondate > dateadd(m,-{0},'{1}') AND userid <> '' AND userid IS NOT NULL GROUP BY userid", minutes, DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss"));
  1939.  
  1940.             var connString = "Driver={Amazon Redshift (x86)};" +
  1941.                     String.Format("Server={0};Database={1};" +
  1942.                     "UID={2};PWD={3};Port={4}",
  1943.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1944.                     masterUserPassword, port);
  1945.             var conn = new OdbcConnection(connString);
  1946.  
  1947.             var dt1 = new DataTable();
  1948.             var mediaColumn = new DataColumn("userid");
  1949.             dt1.Columns.Add(mediaColumn);
  1950.             dt1.PrimaryKey = new[] { mediaColumn };
  1951.  
  1952.             try
  1953.             {
  1954.                 conn.Open();
  1955.  
  1956.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  1957.                 da.Fill(dt1);
  1958.  
  1959.                 retList.AddRange(from DataRow row in dt1.Rows select row["userid"].ToString());
  1960.             }
  1961.             catch (Exception ex)
  1962.             {
  1963.             }
  1964.             finally
  1965.             {
  1966.                 conn.Close();
  1967.             }
  1968.  
  1969.             return retList;
  1970.         }
  1971.  
  1972.  
  1973.         /// <summary>
  1974.         /// Check whether unregistered user has been inactive for the last month.
  1975.         /// </summary>
  1976.         /// <param name="userId"></param>
  1977.         /// <param name="months"></param>
  1978.         /// <returns>Boolean</returns>
  1979.         public bool HasUserBeenActive(string userId, int months = 1)
  1980.         {
  1981.             var query = string.Format(@"SELECT DISTINCT userid FROM tagging.ActivityLog
  1982.                                        WHERE userid='{0}' AND ActionDate < ADD_MONTHS(CURRENT_DATE,-{1})
  1983.                                        ORDER BY ActionDate DESC LIMIT 1", userId, months);
  1984.  
  1985.             var connString = "Driver={Amazon Redshift (x86)};" +
  1986.                     String.Format("Server={0};Database={1};" +
  1987.                     "UID={2};PWD={3};Port={4}",
  1988.                     server, AmazonRedshiftDatabaseName, masterUsername,
  1989.                     masterUserPassword, port);
  1990.  
  1991.             var dt1 = new DataTable();
  1992.             var mediaColumn = new DataColumn("userid");
  1993.             dt1.Columns.Add(mediaColumn);
  1994.             dt1.PrimaryKey = new[] { mediaColumn };
  1995.  
  1996.             var conn = new OdbcConnection(connString);
  1997.             try
  1998.             {
  1999.                 conn.Open();
  2000.                 var da = new OdbcDataAdapter { SelectCommand = new OdbcCommand { CommandText = query, Connection = conn } };
  2001.                 da.Fill(dt1);
  2002.  
  2003.                 if (dt1.Rows.Count > 0)
  2004.                     return true;
  2005.             }
  2006.             catch (Exception ex)
  2007.             {
  2008.             }
  2009.             finally
  2010.             {
  2011.                 conn.Close();
  2012.             }
  2013.             return false;
  2014.         }
  2015.  
  2016.         #endregion
  2017.     }
  2018. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement