Advertisement
Guest User

Untitled

a guest
Oct 17th, 2014
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.13 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8.  
  9. namespace IgaStats
  10. {
  11.     public class IgaEntry
  12.     {
  13.         public int mViewCount;
  14.         public int mClickCount;
  15.     }
  16.  
  17.     public class IgaAdKey : IEquatable<IgaAdKey>, IComparable<IgaAdKey>
  18.     {
  19.         public int ResourceId;
  20.         public int EditionId;
  21.         public int LocationId;
  22.  
  23.         public IgaAdKey(int resourceId, int editionId, int locationId)
  24.         {
  25.             ResourceId = resourceId;
  26.             EditionId = editionId;
  27.             LocationId = locationId;
  28.         }
  29.         public override bool Equals(object obj)
  30.         {
  31.             if (ReferenceEquals(this, obj))
  32.                 return true;
  33.             else if (ReferenceEquals(null, obj))
  34.                 return false;
  35.             if (obj.GetType() != GetType())
  36.                 return false;
  37.             var other = (IgaAdKey)obj;
  38.             return ResourceId == other.ResourceId && EditionId == other.EditionId && LocationId == other.LocationId;
  39.         }
  40.  
  41.         public override int GetHashCode()
  42.         {
  43.             return ResourceId.GetHashCode() ^ EditionId.GetHashCode() ^ LocationId.GetHashCode();
  44.         }
  45.  
  46.         public override string ToString()
  47.         {
  48.             return string.Format("ResourceId={0}, EditionId={1}, LocationId={2}", ResourceId, EditionId, LocationId);
  49.         }
  50.  
  51.         #region IEquatable<IgaAdKey> Members
  52.  
  53.         public bool Equals(IgaAdKey other)
  54.         {
  55.             return Equals((object)other);
  56.         }
  57.  
  58.         #endregion
  59.  
  60.         #region IComparable<IgaAdKey> Members
  61.  
  62.         public int CompareTo(IgaAdKey other)
  63.         {
  64.             if (other == null)
  65.                 return -1; // At end?
  66.             if (object.ReferenceEquals(this, other))
  67.                 return 0;
  68.             int diff;
  69.             if ((diff = ResourceId.CompareTo(other.ResourceId)) != 0)
  70.                 return diff;
  71.             if ((diff = EditionId.CompareTo(other.EditionId)) != 0)
  72.                 return diff;
  73.             if ((diff = LocationId.CompareTo(other.LocationId)) != 0)
  74.                 return diff;
  75.             return 0;
  76.         }
  77.  
  78.         #endregion
  79.     }
  80.  
  81.  
  82.  
  83.     public class IgaStats
  84.     {
  85.         private static void Main(string[] args)
  86.         {
  87.             string[] files;
  88.  
  89.             //if (args.Length < 2)
  90.             //{
  91.             //    Usage();
  92.             //    return;
  93.             //}
  94.  
  95.             string path = @"E:\\Ads";
  96.             string file = @"E:\\Ads\results.csv";
  97.             try
  98.             {
  99.                 files = Directory.GetFiles(path, "*.csv", SearchOption.TopDirectoryOnly);
  100.             }
  101.             catch (Exception e)
  102.             {
  103.                 Console.WriteLine("Exception " + e.Message);
  104.                 return;
  105.             }
  106.  
  107.  
  108.             HashSet<int> allResources = new HashSet<int>();
  109.  
  110.             Dictionary<DateTime, List<string>> dateFiles = GetAllCsvFilesByDate(files);
  111.             Dictionary<string, HashSet<int>> resourcesDate = new Dictionary<string, HashSet<int>>();
  112.  
  113.             // string path = args[1];
  114.  
  115.             if (String.IsNullOrEmpty(path))
  116.             {
  117.                 Console.Error.WriteLine("Please write output directory e.g E:\\Ads\\result.csv");
  118.             }
  119.  
  120.             try
  121.             {
  122.                 using (var stream = File.CreateText(file))
  123.                 {
  124.                     foreach (KeyValuePair<DateTime, List<string>> dateFile in dateFiles)
  125.                     {
  126.                         GetAllResourcesID(dateFile.Value, allResources);
  127.                         GetAllResourcesByDate(dateFile.Key, dateFile.Value, resourcesDate);
  128.                     }
  129.  
  130.                     // write columns
  131.                     foreach (int id in allResources)
  132.                     {
  133.                         stream.Write(id + ",");
  134.                         stream.Write("Locationd ID" + ",");
  135.                         stream.Write("Edition ID" + ",");
  136.                         stream.Write("Click Count" + ",");
  137.                         stream.Write("View Count" + ",");
  138.                     }
  139.                     stream.Write("\n");
  140.  
  141.                     // merge each file and write the rows
  142.                     foreach (KeyValuePair<DateTime, List<string>> dateFile in dateFiles)
  143.                     {
  144.                         MergeFilesForDay(dateFile.Key, dateFile.Value, stream, allResources, resourcesDate);
  145.                         stream.Write("\n");
  146.                     }
  147.                 }
  148.             }
  149.  
  150.             catch (IOException ex)
  151.             {
  152.                 Console.WriteLine("File is in use" + ex.Message);
  153.             }
  154.         }
  155.  
  156.         private static void GetAllResourcesByDate(DateTime date, List<string> files, Dictionary<string, HashSet<int>> resourcesDate)
  157.         {
  158.  
  159.             const char lineSep = ';';
  160.             foreach (string fn in files)
  161.             {
  162.                 foreach (string line in File.ReadAllLines(fn))
  163.                 {
  164.                     string[] igaItems = line.Split(lineSep);
  165.                     foreach (var item in igaItems)
  166.                     {
  167.                         string[] fields = item.Split(new string[] { "," }, StringSplitOptions.None);
  168.                         if (fields.Length < 3)
  169.                         {
  170.                             continue; // skip invalid data
  171.                         }
  172.  
  173.                         int resourceId;
  174.                         bool resourceIdValid = int.TryParse(fields[1].Trim(), out resourceId);
  175.  
  176.                         bool validDate = resourcesDate.ContainsKey(date.ToString("yyyyMMdd"));
  177.                         if (!validDate)
  178.                         {
  179.                             resourcesDate.Add(date.ToString("yyyyMMdd"), new HashSet<int>());
  180.                         }
  181.  
  182.                         resourcesDate[date.ToString("yyyyMMdd")].Add(resourceId);
  183.                     }
  184.                 }
  185.             }
  186.         }
  187.  
  188.         /// <summary>
  189.         /// Crawl over the files and get date to files
  190.         /// </summary>
  191.         /// <param name="files"></param>
  192.         /// <returns></returns>
  193.         public static Dictionary<DateTime, List<string>> GetAllCsvFilesByDate(string[] files)
  194.         {
  195.             var dataFiles = new Dictionary<DateTime, List<string>>();
  196.  
  197.             foreach (string file in files)
  198.             {
  199.                 string fn = Path.GetFileNameWithoutExtension(file);
  200.                 if (fn.Length < "yyyyMMdd_HHmmss".Length)
  201.                 {
  202.                     continue;
  203.                 }
  204.                 string datePart = fn.Remove("yyyyMMdd".Length); // we need only date
  205.                 DateTime date;
  206.                 if (DateTime.TryParseExact(datePart, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None,
  207.                                            out date))
  208.                 {
  209.                     bool containsDate = dataFiles.ContainsKey(date);
  210.                     if (!containsDate)
  211.                     {
  212.                         dataFiles.Add(date, new List<string>());
  213.                     }
  214.                     dataFiles[date].Add(file);
  215.                 }
  216.             }
  217.  
  218.             return dataFiles;
  219.         }
  220.  
  221.  
  222.         /// <summary>
  223.         /// gets all resource IDs to populate them in one row
  224.         /// </summary>
  225.         /// <param name="files"></param>
  226.         /// <param name="resourcesSet"></param>
  227.         private static void GetAllResourcesID(List<string> files, HashSet<int> resourcesSet)
  228.         {
  229.             const char lineSep = ';';
  230.             foreach (string fn in files)
  231.             {
  232.                 foreach (string line in File.ReadAllLines(fn))
  233.                 {
  234.                     string[] igaItems = line.Split(lineSep);
  235.                     foreach (var item in igaItems)
  236.                     {
  237.                         string[] fields = item.Split(new string[] { "," }, StringSplitOptions.None);
  238.                         if (fields.Length < 3)
  239.                         {
  240.                             continue; // skip invalid data
  241.                         }
  242.  
  243.                         int resourceId;
  244.                         bool resourceIdValid = int.TryParse(fields[1].Trim(), out resourceId);
  245.                         if (resourceIdValid)
  246.                         {
  247.                             resourcesSet.Add(resourceId);
  248.                         }
  249.                     }
  250.                 }
  251.             }
  252.         }
  253.  
  254.         /// <summary>
  255.         /// merges all the files for one specific date and create iga entry, merge their values, write them to the file
  256.         /// </summary>
  257.         /// <param name="date"></param>
  258.         /// <param name="files"></param>
  259.         /// <param name="streamWriter"></param>
  260.         private static void MergeFilesForDay(DateTime date, List<string> files, StreamWriter streamWriter,
  261.             HashSet<int> allResources, Dictionary<string, HashSet<int>> resourcesDate)
  262.         {
  263.             var enteries = new Dictionary<IgaAdKey, IgaEntry>();
  264.  
  265.  
  266.  
  267.             HashSet<int> currResources = new HashSet<int>();
  268.             List<int> resourcesList = allResources.ToList();
  269.  
  270.             const char lineSep = ';';
  271.  
  272.             foreach (string fn in files)
  273.             {
  274.                 foreach (string line in File.ReadAllLines(fn))
  275.                 {
  276.                     string[] igaItems = line.Split(lineSep);
  277.                     foreach (var item in igaItems)
  278.                     {
  279.                         string[] fields = item.Split(new string[] { "," }, StringSplitOptions.None);
  280.                         if (fields.Length < 5)
  281.                         {
  282.                             continue; // skip invalid data
  283.                         }
  284.  
  285.                         int viewCount, clickCount, editionId, locationId, resourceId;
  286.  
  287.                         bool locationIdValid = int.TryParse(fields[0].Trim(), out locationId);
  288.                         bool resourceIdValid = int.TryParse(fields[1].Trim(), out resourceId);
  289.                         bool editionValid = int.TryParse(fields[2].Trim(), out editionId);
  290.                         bool viewCountValid = int.TryParse(fields[3].Trim(), out viewCount);
  291.                         bool clickCountValid = int.TryParse(fields[4].Trim(), out clickCount);
  292.  
  293.                         if (locationIdValid && resourceIdValid && viewCountValid && clickCountValid && editionValid)
  294.                         {
  295.                             IgaAdKey key = new IgaAdKey(resourceId, editionId, locationId);
  296.                             bool knownId = enteries.ContainsKey(key);
  297.                             if (!knownId)
  298.                             {
  299.                                 enteries.Add(key, new IgaEntry());
  300.                             }
  301.  
  302.                             IgaEntry entry = enteries[key];
  303.                             entry.mClickCount += clickCount;
  304.                             entry.mViewCount += viewCount;
  305.                         }
  306.                     }
  307.                 }
  308.             }
  309.  
  310.             streamWriter.Write(date.ToString("yyyyMMdd") + ",");
  311.  
  312.             HashSet<int> resources;
  313.  
  314.              foreach (var pair in enteries.OrderBy(pair => pair.Key))
  315.             {
  316.                     streamWriter.Write(pair.Key.LocationId + ",");
  317.                     streamWriter.Write(pair.Key.EditionId + ",");
  318.                     streamWriter.Write(pair.Value.mClickCount + ",");
  319.                     streamWriter.Write(pair.Value.mViewCount + ",");
  320.                     streamWriter.Write(",");
  321.                  
  322.             }
  323.              
  324.             }
  325.            
  326.  
  327.  
  328.         private string GetCmdParameterValue(string[] args, string parameter)
  329.         {
  330.             foreach (string[] parts in args.Select(s => s.Split('=')).
  331.                 Where(p => p.Length == 2 && p[0].Equals(parameter)))
  332.             {
  333.                 return parts[1];
  334.             }
  335.             return null;
  336.         }
  337.  
  338.         private static void Usage()
  339.         {
  340.             Console.Error.WriteLine("Usage: IgaStats ads_path output_path \n eg. IgaStats E:\\Ads  E:\\Ads\\results.csv");
  341.         }
  342.     }
  343. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement