Advertisement
Guest User

Untitled

a guest
Jun 30th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.81 KB | None | 0 0
  1. using System;
  2. using System.Configuration;
  3. using System.IO;
  4. using System.Reflection;
  5. using code.runner.intranet.Events;
  6. using code.runner.intranet.JSON;
  7. using NLog;
  8.  
  9. namespace code.runner
  10. {
  11. class Program
  12. {
  13. // create our NLOG references
  14. private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
  15.  
  16. // create our NLOG type
  17. private enum LogType
  18. {
  19. Debug,
  20. Info,
  21. Error
  22. };
  23.  
  24. static void Main(string[] args)
  25. {
  26. CLog(LogType.Info, "Code Runner started with version " + Assembly.GetAssembly(typeof(Program)).GetName().Version);
  27.  
  28. ProcessVolunteerOpportunities( ConfigurationManager.AppSettings["VCECurrentOpportunitiesOutputFile"],
  29. ConfigurationManager.AppSettings["VCECurrentOpportunitiesSPSite"],
  30. ConfigurationManager.AppSettings["VCECurrentOpportunitiesSPList"]);
  31. }
  32.  
  33. private static void ProcessVolunteerOpportunities(string outputFile, string sharePointSite,
  34. string sharepointList)
  35. {
  36. try
  37. {
  38. var r = new VCECurrentOpportunities();
  39.  
  40. // Attach VCE event handler
  41. r.OnEventHandler += SharePointEventHandler;
  42.  
  43. try
  44. {
  45. // retrieve list and write to a new JSON file
  46. using (var jsonFile = new StreamWriter(outputFile))
  47. {
  48. jsonFile.Write(r.RetreiveOpportunities(sharePointSite, sharepointList));
  49.  
  50. CLog(LogType.Info, "Successfully wrote local opportunities to: " + outputFile);
  51. }
  52. }
  53. catch (Exception ex)
  54. {
  55. CLog(LogType.Error, "Failed to write available opportunities to local JSON file: " + outputFile, ex);
  56. }
  57. }
  58. catch (Exception ex)
  59. {
  60. CLog(LogType.Error, "General error when processing volunteer opportunities", ex);
  61. }
  62. }
  63.  
  64. /// <summary>
  65. /// Log messages to file and the console
  66. /// </summary>
  67. /// <param name="type">The type of log event to write (Debug, Info, Error)</param>
  68. /// <param name="message">Optional verbose message to be included in the logs</param>
  69. /// <param name="e">Optional, pass an exception to the stack</param>
  70. private static void CLog(LogType type, string message = "", Exception e = null)
  71. {
  72. while (true)
  73. {
  74. switch (type)
  75. {
  76. case LogType.Debug:
  77. Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), message);
  78. Logger.Debug(String.Format("[{0}] {1}", DateTime.Now.ToShortTimeString(), message));
  79. break;
  80.  
  81. case LogType.Info:
  82. Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), message);
  83. Logger.Info(String.Format("[{0}] {1}", DateTime.Now.ToShortTimeString(), message));
  84. break;
  85.  
  86. case LogType.Error:
  87. Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), message);
  88. Console.WriteLine("[{0}] Exception details: {1}", DateTime.Now.ToShortTimeString(), e);
  89. Logger.Error(String.Format("[{0}] {1}n", DateTime.Now.ToShortTimeString(), message));
  90. Logger.Error(String.Format("[{0}] Exception details: {1}", DateTime.Now.ToShortTimeString(), e));
  91. break;
  92.  
  93. default:
  94. type = LogType.Error;
  95. e = new Exception("Unknown logging type.");
  96. continue;
  97. }
  98. break;
  99. }
  100. }
  101.  
  102. /// <summary>
  103. /// Method to handle events from our class and post them to NLOG and the Console
  104. /// </summary>
  105. /// <param name="sender"></param>
  106. /// <param name="e">SharePoint event object</param>
  107. static void SharePointEventHandler(object sender, SharePointEventArgs e)
  108. {
  109. switch (e.ExceptionType)
  110. {
  111. case SharePointEventArgs.ExceptionLevel.Debug:
  112. CLog(LogType.Debug, e.Message);
  113. break;
  114.  
  115. case SharePointEventArgs.ExceptionLevel.Info:
  116. CLog(LogType.Info, e.Message);
  117. break;
  118.  
  119. case SharePointEventArgs.ExceptionLevel.Error:
  120. CLog(LogType.Error, e.Message, e.Exception);
  121. break;
  122. }
  123. }
  124.  
  125. }
  126. }
  127.  
  128. using System;
  129. using System.Collections.Generic;
  130. using System.Linq;
  131. using System.Text;
  132. using code.runner.intranet.Dal;
  133. using code.runner.intranet.Entity;
  134. using code.runner.intranet.Events;
  135. using Microsoft.SharePoint;
  136. using Newtonsoft.Json.Linq;
  137.  
  138. namespace code.runner.intranet.JSON
  139. {
  140. public class VCECurrentOpportunities
  141. {
  142. /// <summary>
  143. /// Retreive List of current volunteer opportunities
  144. /// </summary>
  145. public string RetreiveOpportunities(string siteName, string listUrl)
  146. {
  147. try
  148. {
  149. PostEvent("Loaded VCE Current Opportunities Module", SharePointEventArgs.ExceptionLevel.Info);
  150.  
  151. using (var site = new SPSite(siteName))
  152. {
  153. using (var web = site.OpenWeb())
  154. {
  155. PostEvent("Successfully opened: " + web.Url, SharePointEventArgs.ExceptionLevel.Info);
  156. PostEvent("Loading list: " + listUrl, SharePointEventArgs.ExceptionLevel.Info);
  157.  
  158. var coDal = new VCECurrentOpportunitiesDAL();
  159.  
  160. SPList list = web.GetList(listUrl);
  161. List<VCECurrentOpportunitiesEntity> currentOpportunities = coDal.FetchItems(list);
  162.  
  163. PostEvent("Preparing JSON output for " + listUrl, SharePointEventArgs.ExceptionLevel.Info);
  164.  
  165. // initalize and specify that our return value (in JSON) contains an array
  166. var json = "[";
  167.  
  168. foreach (var item in currentOpportunities)
  169. {
  170. // create a new JSON object for use within our array
  171. var o = new JObject();
  172.  
  173. o["positionTitle"] = item.PositionTitle;
  174. o["region"] = item.Region;
  175.  
  176. // split locations choice field from SharePoint format into a processable array
  177. string[] locationsArray = null;
  178. if (item.Location != null)
  179. locationsArray = item.Location.Split(new[] {";#"}, StringSplitOptions.RemoveEmptyEntries);
  180. var location = new JArray {locationsArray};
  181. o["location"] = location;
  182.  
  183. o["jobDescription"] = item.JobDescription;
  184. o["fileName"] = item.FileName;
  185. o["fileLocation"] = item.FileLocation;
  186. o["department"] = item.Department;
  187.  
  188. json += o.ToString();
  189.  
  190. // only add a comma on our object if it isn't the last one in the array
  191. if (!item.Equals(currentOpportunities.Last())) json += ",";
  192. }
  193.  
  194. // close our JSON array
  195. json += "]";
  196.  
  197. return json;
  198. }
  199. }
  200. }
  201. catch (UnauthorizedAccessException ex)
  202. {
  203. PostEvent("Unable to access SharePoint list for Current Opportunities", SharePointEventArgs.ExceptionLevel.Error, ex);
  204.  
  205. return ex.ToString();
  206. }
  207. catch (Exception ex)
  208. {
  209. PostEvent("General error when retreiving opportunities", SharePointEventArgs.ExceptionLevel.Error, ex);
  210.  
  211. return ex.ToString();
  212. }
  213. }
  214.  
  215. /// <summary>
  216. /// Internal event handler allowing for logging of events within the class
  217. /// </summary>
  218. private EventHandler<SharePointEventArgs> _onEvent;
  219.  
  220. /// <summary>
  221. /// Public event handler allowing for accessibility outside of the class
  222. /// </summary>
  223. public event EventHandler<SharePointEventArgs> OnEventHandler
  224. {
  225. add { _onEvent += value; }
  226. remove { _onEvent += value; }
  227. }
  228.  
  229. public void PostEvent(string message, SharePointEventArgs.ExceptionLevel exceptionLevel, Exception exception = null)
  230. {
  231. if (_onEvent == null) return;
  232.  
  233. if (exception == null)
  234. {
  235. var e = new SharePointEventArgs(message, exceptionLevel);
  236. _onEvent(this, e);
  237. }
  238. else
  239. {
  240. var e = new SharePointEventArgs(message, exceptionLevel, exception);
  241. _onEvent(this, e);
  242. }
  243. }
  244.  
  245. }
  246. }
  247.  
  248. using System;
  249. using System.Collections.Generic;
  250. using System.Linq;
  251. using System.Text;
  252.  
  253. namespace code.runner.intranet.Events
  254. {
  255. public class SharePointEventArgs : EventArgs
  256. {
  257. public SharePointEventArgs(string message, ExceptionLevel exceptionType, Exception exception = null)
  258. {
  259. Message = message;
  260. ExceptionType = exceptionType;
  261.  
  262. if (exception != null) Exception = exception;
  263. }
  264.  
  265. /// <summary>
  266. /// Property to allow the storage of a more verbose and explainable error message
  267. /// </summary>
  268. public string Message { get; private set; }
  269.  
  270. /// <summary>
  271. /// Object to store full exception information
  272. /// </summary>
  273. public Exception Exception { get; private set; }
  274.  
  275. /// <summary>
  276. /// Stores the type of exception being sent
  277. /// </summary>
  278. public ExceptionLevel ExceptionType { get; private set; }
  279.  
  280. /// <summary>
  281. /// Enum to store the types of exceptions that can be sent to the event
  282. /// </summary>
  283. public enum ExceptionLevel
  284. {
  285. Debug,
  286. Info,
  287. Error
  288. }
  289. }
  290. }
  291.  
  292. using System;
  293. using System.Collections.Generic;
  294. using System.Linq;
  295. using System.Text;
  296. using Microsoft.SharePoint;
  297.  
  298. namespace code.runner.intranet.Entity
  299. {
  300. /// <summary>
  301. /// Entity for tracking current opportunitiy data
  302. /// </summary>
  303. public class VCECurrentOpportunitiesEntity : ItemEntity
  304. {
  305. public string PositionTitle { get; set; }
  306. public string Department { get; set; }
  307. public string Region { get; set; }
  308. public string Location { get; set; }
  309. public string JobDescription { get; set; }
  310. public string FileName { get; set; }
  311. public string FileLocation { get; set; }
  312.  
  313. }
  314. }
  315.  
  316. using System;
  317. using System.Collections.Generic;
  318. using System.Linq;
  319. using System.Net.Sockets;
  320. using System.Text;
  321. using code.runner.intranet.Entity;
  322. using Microsoft.SharePoint;
  323.  
  324. namespace code.runner.intranet.Dal
  325. {
  326. public class VCECurrentOpportunitiesDAL : ItemDal
  327. {
  328. /// <summary>
  329. /// Fetch items from SharePoint and populate them into our entity
  330. /// </summary>
  331. /// <param name="list"></param>
  332. /// <returns></returns>
  333. public List<VCECurrentOpportunitiesEntity> FetchItems(SPList list)
  334. {
  335. try
  336. {
  337. return (from SPListItem item in list.Items
  338. select LoadItems(
  339. item["Position Title"].ToString(),
  340. item["Department"].ToString(),
  341. item["Region"].ToString(),
  342. item["Location"].ToString(),
  343. item["Job Description"].ToString() ,
  344. item["File Name (Job Description)"].ToString() ,
  345. item["File Location (Job Description)"].ToString() ,
  346. item.ID.ToString(), // item id
  347. item.ContentType.Name, // content type
  348. item.DisplayName, // display name
  349. item.Name, // name
  350. "", // title
  351. item.Url, // url
  352. item["Created By"].ToString(), // author
  353. item["Modified By"].ToString(), // editor
  354. Convert.ToDateTime(item["Created"]), // date time modified
  355. item["Created By"].ToString(), // modified by
  356. Convert.ToDateTime(item["Created"]), // date time created
  357. item["Created By"].ToString() // created by
  358. )).ToList();
  359. }
  360. catch (Exception ex)
  361. {
  362. Console.WriteLine("Error fetching list items: {0}", ex);
  363.  
  364. throw;
  365. }
  366. }
  367.  
  368. public VCECurrentOpportunitiesEntity LoadItems(
  369. string positionTitle, string department, string region, string location,
  370. string jobDescription, string fileName, string fileLocation, string itemId, string contentType,
  371. string displayName, string name, string title,
  372. string url, string author, string editor, DateTime modified, string modifiedBy,
  373. DateTime created, string createdBy)
  374. {
  375.  
  376. var vceCurrentOpportunitiesEntity = new VCECurrentOpportunitiesEntity
  377. {
  378. // Current opportunities specific data
  379. PositionTitle = positionTitle,
  380. Department = department,
  381. Region = region,
  382. Location = location,
  383. JobDescription = jobDescription,
  384. FileName = fileName,
  385. FileLocation = fileLocation,
  386.  
  387. // Common SharePoint List data
  388. ItemId = itemId,
  389. ContentType = contentType,
  390. DisplayName = displayName,
  391. Name = name,
  392. Title = title,
  393. Url = url,
  394. Author = author,
  395. Editor = editor,
  396. Modified = modified,
  397. ModifiedBy = modifiedBy,
  398. Created = created,
  399. CreatedBy = createdBy
  400. };
  401.  
  402. return vceCurrentOpportunitiesEntity;
  403. }
  404. }
  405. }
  406.  
  407. public enum ExceptionLevel
  408. {
  409. Debug,
  410. Info,
  411. Error
  412. }
  413.  
  414. private enum LogType
  415. {
  416. Debug,
  417. Info,
  418. Error
  419. };
  420.  
  421. while (true)
  422. {
  423. switch (type)
  424. {
  425. case LogType.Debug:
  426. Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), message);
  427. Logger.Debug(String.Format("[{0}] {1}", DateTime.Now.ToShortTimeString(), message));
  428. break;
  429.  
  430. case LogType.Info:
  431. Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), message);
  432. Logger.Info(String.Format("[{0}] {1}", DateTime.Now.ToShortTimeString(), message));
  433. break;
  434.  
  435. case LogType.Error:
  436. Console.WriteLine("[{0}] {1}", DateTime.Now.ToShortTimeString(), message);
  437. Console.WriteLine("[{0}] Exception details: {1}", DateTime.Now.ToShortTimeString(), e);
  438. Logger.Error(String.Format("[{0}] {1}n", DateTime.Now.ToShortTimeString(), message));
  439. Logger.Error(String.Format("[{0}] Exception details: {1}", DateTime.Now.ToShortTimeString(), e));
  440. break;
  441.  
  442. default:
  443. type = LogType.Error;
  444. e = new Exception("Unknown logging type.");
  445. continue;
  446. }
  447. break;
  448. }
  449.  
  450. var currentTime = DateTime.Now.ToShortTimeString();
  451.  
  452. if (type != LogType.Debug &&
  453. type != LogType.Info &&
  454. type != LogType.Error)
  455. {
  456. type = LogType.Error;
  457. e = new Exception("Unknown logging type.");
  458. }
  459.  
  460. switch (type)
  461. {
  462. case LogType.Debug:
  463. Console.WriteLine("[{0}] {1}", currentTime, message);
  464. Logger.Debug(String.Format("[{0}] {1}", currentTime, message));
  465. break;
  466.  
  467. case LogType.Info:
  468. Console.WriteLine("[{0}] {1}", currentTime, message);
  469. Logger.Info(String.Format("[{0}] {1}", currentTime, message));
  470. break;
  471.  
  472. case LogType.Error:
  473. Console.WriteLine("[{0}] {1}", currentTime, message);
  474. Console.WriteLine("[{0}] Exception details: {1}", currentTime, e);
  475. Logger.Error(String.Format("[{0}] {1}n", currentTime, message));
  476. Logger.Error(String.Format("[{0}] Exception details: {1}", currentTime, e));
  477. break;
  478. }
  479.  
  480. if (_onEvent == null) return;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement