I would like to ask for an idea how will I saved the data I retrieved from webservice. Here is what I have so far.
Everything is working. I was able to retrieve the data I needed from webservice but I don't have idea on how will I saved the data on my database.
cust.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp.Authenticators;
using System.IO;
using RestSharp;
using System.Text.Json;
using System.Data;
namespace SAP1
{
class cust
{
public class custOutput
{
public string NAME;
public string AGE;
public string ADD;
public DateTime DATE1;
public DateTime DATE2;
}
RestClient client;
RestRequest request;
public cust()
{
client = new RestClient(#"http://testwebservice/");
client.Authenticator = new HttpBasicAuthenticator("test1", "cust#Test1");
}
public List<custOutput>
GetcustOutputs(DateTime start, DateTime end)
{
request = new RestRequest("sap/bc/zcust", Method.Get);
request.AddParameter("sap-client", "200");
request.AddParameter("start","");
request.AddParameter("end", end.ToString("yyyyMMdd"));
var output = client.ExecuteAsync<List<custOutput>>(request);
var o = output.Result.Data;
return o;
}
public void ProcessOutput(DateTime start, DateTime end)
{
var output = GetcustOutputs(start, end);
Console.WriteLine(output.ToString());
// IEnumerable<DataRow> v = output.Select(x => new DataRow(x.NAME,));
}
}
}
This how I call my function.
form.cs
void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
_backgroundWorkerThread = Thread.CurrentThread;
SIAP svc = new SIAP();
cust cust = new cust();
cust.ProcessOutput(dte_from.Value, dte_to.Value);
}
catch (ThreadAbortException)
{
e.Cancel = true;
m_oWorker.Dispose();
Thread.ResetAbort();
}
}
Related
I have a problem during the serialization with data modified during deserialization (i dont think its the problem )
some \u char are not correctly transformed...and i dont see how to fix that.. even with a global encoder....
See my comments about PROBLEM and NO PROBLEM
using System;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Text.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using libaurore;
namespace partoo
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("pe-id-environnement", "pe-id-environnement");
client.DefaultRequestHeaders.Add("pe-id-correlation", "pe-id-correlation");
client.DefaultRequestHeaders.Add("pe-id-utilisateur", "pe-id-utilisateur");
client.DefaultRequestHeaders.Add("pe-nom-application", "pe-nom-application");
var CodesAurore = await client.GetFromJsonAsync<List<RefAURORE>>("http://xx010-.pole-emploi.intra/v1/agences?horaire=true");
Console.WriteLine(CodesAurore[500].NomAgence);
//display: Pôle emploi - L'hay-Les-Roses NO PROBLEM
var encoderSettings = new TextEncoderSettings();
//encoderSettings.AllowCharacters('\u0027'); dont fix....
encoderSettings.AllowRange(UnicodeRanges.All);
var options = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.Create(encoderSettings),
WriteIndented = false
};
var ff = JsonSerializer.Serialize(CodesAurore[500], options);
Console.WriteLine(ff);
//diplay:..,"libelle":"Pôle emploi - L\u0027hay-Les-Roses" PROBLEM!!!
}
}
}
the class RefAURORE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text.Json.Serialization;
namespace libaurore
{
public static class Datas
{
public static TextInfo myTI = new CultureInfo("fr-FR", false).TextInfo;
public static Dictionary<int, string> HJdico = new Dictionary<int, string> {
{0, "sunday"},{1, "monday"},{2, "tuesday"},{3, "wednesday"},{4, "thursday"},{5, "friday"},{6, "saturday"}};
}
public class RefAURORE
{
[DefaultValue("")]
[JsonPropertyName(name: "code")]
public string CodeAurore { get; set; }
[DefaultValue("")]
[JsonPropertyName(name: "type")]
public string TypeAgence {
get; set; }
private string _NomAgence;
[DefaultValue("")]
[JsonPropertyName(name: "libelle")]
public string NomAgence
{
get => _NomAgence;
set
{
_NomAgence = $"Pôle emploi - {Datas.myTI.ToTitleCase(value.ToLower())}";
if( CodeAurore == "IDF0291")
{
//display Pôle emploi - L'hay-Les-Roses.....NO PROBLEM
Console.WriteLine("***********");
Console.WriteLine(NomAgence);
Console.WriteLine("***********");
}
}
}
:
:
Can you handle it with the below code?
var response = "Željko Cvijetić";
var jsonSerializerSettings = new JsonSerializerSettings {
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
var json = JsonConvert.SerializeObject(response, jsonSerializerSettings);
And using System.Text.Json
JsonSerializerOptions JsonSetting = new JsonSerializerOptions();
jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
var s = JsonSerializer.Serialize(response, JsonSetting);
I want to put a data from simple csv file into the records containing custom made class.
Here is my code:
using System;
using CsvHelper;
using System.IO; // for accessing the files
using System.Globalization;
using System.Linq; // to call a list enumerable
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
namespace Reading_CSV_Files
{
class Program
{
static void Main(string[] args)
{
ReadCSVFile(#"C:\path_to_my_file\file.csv");
}
public static void ReadCSVFile(String filePath)
{
if (filePath == null)
{
return;
}
using (var streamReader = new StreamReader(filePath) )
{
using (var foodFileCSVReader = new CsvReader(streamReader,
CultureInfo.InvariantCulture))
{
//var records = foodFileCSVReader.GetRecords<dynamic>().ToList();
var records = foodFileCSVReader.GetRecords<Pizza>().ToList();
// replace dynamic type argument on our records
}
}
}
}
public class Pizza
{
// attributes
[Name("Name")]
public String Name { get; set; }
[Name("PLN_Cost")]
public double Price { get; set; }
}
}
The csv file looks like this:
Screenshot from csv file
The file was saved as comma separated. I found some advices with manual setting it up, but currently it says, this field is read-only.
CsvHelper.HeaderValidationException: Header with name 'Name'[0] was not found.
Header with name 'PLN_Cost'[0] was not found.
If the program is going to be using CSV files which might have a comma or semi-colon as the separator, you could read the first line and set the separator to either of those, like this:
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Program
{
public class Pizza
{
// attributes
[Name("Name")]
public String Name { get; set; }
[Name("PLN_Cost")]
public decimal Price { get; set; }
public override string ToString()
{
return $"{Name} - {Price}";
}
}
public static List<Pizza> ReadCSVFile(String filePath)
{
if (!File.Exists(filePath))
{
return new List<Pizza>();
}
var sep = ";";
/* Check the header for the separator character to use. */
string headerLine = File.ReadLines(filePath).First();
if (headerLine?.IndexOf(',') >= 0) { sep = ","; }
using (var sr = new StreamReader(filePath))
{
var config = new CsvConfiguration(CultureInfo.CurrentCulture)
{
Delimiter = sep,
Encoding = Encoding.UTF8
};
using (var foodFileCSVReader = new CsvReader(sr, config))
{
return foodFileCSVReader.GetRecords<Pizza>().ToList();
}
}
}
static void Main(string[] args)
{
var pp = ReadCSVFile(#"C:\temp\PizzaPrices.csv");
Console.WriteLine(string.Join("\r\n", pp));
Console.ReadLine();
}
}
}
Note that it is better to use the decimal type for money instead of the double type.
You might need additional code to set the decimal separator to be used.
So I'm trying to retrieve data from a database to display it in a table.
(This is a WebApi project). The idea is to go through all the prodactivity from the table whose status is 1. Put them in some list and return it.
To do this, I need to convert a TBL object to DAL. but here I am stuck. It is unable to perform a conversion and is therefore unwilling to return an object of a different type.
I tried to convert in all sorts of ways but it'S out of sync with the type in the controller.
This is my code: (do'nt look at the other functions. Look at the function getProductivityRequest at the end)
UserController.cs
using BL;
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebApiSystem.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]//SupportsCredentials = true
[RoutePrefix("api/User")]
public class UserController : ApiController
{
[HttpGet]
[Route("login/{email}/{pass}")]
public IHttpActionResult LogIn(string email, string pass)
{
UserDTO user = BL.UserService.LogIn(email, pass);
if (user != null)
return Ok(user);
return NotFound();
}
[Route("register")]
public IHttpActionResult Register(UserDTO user)
{
return NotFound();
}
[HttpPost]
[Route("productivity")]
public IHttpActionResult InsertProductivity([FromBody] ProductivityDTO p)
{
bool b = BL.UserService.InsertProductivity(p);
if (b)
return Ok(b);
return BadRequest();
}
[HttpGet]
[Route("getProductivityRequest")]
public IHttpActionResult GetProductivityRequest()
{
return Json(BL.UserService.GetProductivityRequest());
}
}
}
UserService.cs
using DAL;
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BL
{
public class UserService
{
public static UserDTO LogIn(string email, string pass)
{
using (Model2 db = new Model2())
{
UserTbl user = db.UserTbl.FirstOrDefault(u => u.UserEmail == email && u.UserPassLogin == pass);
if (user == null)
return null;
return CONVERTERS.UserConverter.ConvertUsertoDTO(user);
}
}
public static bool InsertProductivity(ProductivityDTO p)
{
using (Model2 db = new Model2())
{
//conver dal to dto
ProductivityTbl prod = BL.CONVERTERS.ProductivityConverter.ProductivityDal(p);
prod.ProductivityStatus = 1;
db.ProductivityTbl.Add(prod);
db.SaveChanges();
return true;
}
return false;
}
public static ProductivityDTO GetProductivityRequest()//Here I can not convert
{
using (Model2 db = new Model2())
{
List<ProductivityDTO> PList = new List<ProductivityDTO>();
foreach (var item in db.ProductivityTbl.ToList())
{
if(item.ProductivityStatus==1)
{
ProductivityDTO prod = BL.CONVERTERS.ProductivityConverter.ConvertProductivitytoDTO(item);
PList.Add(prod);
}
}
return (PList);//He's unable to return the object
}
}
}
}
ProductivityConverter.cs(if it's relevant...)
using DTO;
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BL.CONVERTERS
{
class ProductivityConverter
{
public static ProductivityDTO ConvertProductivitytoDTO(ProductivityTbl productivity) {
return new ProductivityDTO
{
ProductivyCode = productivity.ProductivyCode,
ProductivityNum = productivity.ProductivityNum,
ProductivityStatus = productivity.ProductivityStatus,
UserCode = productivity.UserCode,
Cmment = productivity.Cmment,
Date = productivity.Date
};
}
public static ProductivityTbl ProductivityDal(ProductivityDTO productivity)
{
return new ProductivityTbl
{
ProductivyCode = productivity.ProductivyCode,
ProductivityNum = productivity.ProductivityNum,
ProductivityStatus = productivity.ProductivityStatus,
UserCode = productivity.UserCode,
Cmment = productivity.Cmment,
Date = productivity.Date
};
}
}
}
If anyone knows of another way to transfer the data I would love ideas.
Thanks!
Your method returns a ProductivityDTO:
public static ProductivityDTO GetProductivityRequest()
...but you are trying to return PList which is a List<ProductivityDTO>.
Your method signature should be:
public static List<ProductivityDTO> GetProductivityRequest()
Although your comment suggests you can't change the method signature. In which case you need to return just one DTO. How you determine which one is up to you. But if it were just one with a ProductivityStatus of 1 then you could do:
public static ProductivityDTO GetProductivityRequest()//Here I can not convert
{
using (Model2 db = new Model2())
{
return BL.CONVERTERS.ProductivityConverter.ConvertProductivitytoDTO(db.ProductivityTbl.FirstOrDefault(p => p.ProductivityStatus == 1)));
}
}
Your function is defined to return a single ProductivityDTO.
But your function is building a List<ProductivityDTO> and returning that.
Change your function return type to a collection type, such as:
public static List<ProductivityDTO> GetProductivityRequest()
or
public static IEnumerable<ProductivityDTO> GetProductivityRequest()
I have had a static version of this type of code working in a static version. However the API calls were just incredibly slow. I am trying to move to asynchronous now that C# 7 supports console async tasks (where I add code to connect to my DB and store data. I want to see this code output on the console to ensure it's working so I can assign variables for loading. I can't seem to figure out how to access the list from main. Here is the code I have so far:
Wrapper (or C# library):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AlphaVantageApiWrapper
{
public static class AlphaVantageApiWrapper
{
public static async Task<AlphaVantageRootObject> GetTechnical(List<ApiParam> parameters, string apiKey)
{
var stringRequest = parameters.Aggregate(#"https://www.alphavantage.co/query?", (current, param) => current + param.ToApiString());
stringRequest += "&apikey=" + apiKey;
var apiData = await CallAlphaVantageApi(stringRequest);
var technicalsObject = new AlphaVantageRootObject
{
MetaData = new MetaData
{
Function = parameters.FirstOrDefault(x => x.ParamName.Equals("function"))?.ParamValue ?? "NA?",
Interval = parameters.FirstOrDefault(x => x.ParamName.Equals("interval"))?.ParamValue ?? "NA?",
SeriesType = parameters.FirstOrDefault(x => x.ParamName.Equals("series_type"))?.ParamValue ?? "NA?",
Symbol = parameters.FirstOrDefault(x => x.ParamName.Equals("symbol"))?.ParamValue ?? "NA?"
},
TechnicalsByDate = apiData.Last.Values().OfType<JProperty>().Select(x => new TechnicalDataDate
{
Date = Convert.ToDateTime(x.Name),
Data = x.Value.OfType<JProperty>().Select(r => new TechnicalDataObject
{
TechnicalKey = r.Name,
TechnicalValue = Convert.ToDouble(r.Value.ToString())
}).ToList()
})
.ToList()
};
return technicalsObject;
}
public class ApiParam
{
public string ParamName;
public string ParamValue;
public ApiParam(string paramNameIn, string paramValueIn)
{
ParamName = paramNameIn;
ParamValue = paramValueIn;
}
public string ToApiString()
{
return $"&{ParamName}={ParamValue}";
}
}
public static string ToDescription(this Enum enumeration)
{
var type = enumeration.GetType();
var memInfo = type.GetMember(enumeration.ToString());
if (memInfo.Length <= 0) return enumeration.ToString();
var attrs = memInfo[0].GetCustomAttributes(typeof(EnumDescription), false);
return attrs.Length > 0 ? ((EnumDescription)attrs[0]).Text : enumeration.ToString();
}
public static async Task<JObject> CallAlphaVantageApi(string stringRequest)
{
try
{
using (var client = new HttpClient())
{
var res = await client.GetStringAsync(stringRequest);
return JsonConvert.DeserializeObject<JObject>(res);
}
}
catch (Exception e)
{
//fatal error
return null;
}
}
public class AlphaVantageRootObject
{
public MetaData MetaData;
public List<TechnicalDataDate> TechnicalsByDate;
}
public class MetaData
{
public string Function;
public string Interval;
public string SeriesType;
public string Symbol;
}
public class TechnicalDataDate
{
public DateTime Date;
public List<TechnicalDataObject> Data;
}
public class TechnicalDataObject
{
public string TechnicalKey { get; set; }
public double TechnicalValue { get; set; }
}
public class EnumDescription : Attribute
{
public string Text { get; }
public EnumDescription(string text)
{
Text = text;
}
}
public enum AvFuncationEnum
{
[EnumDescription("SMA")] Sma,
[EnumDescription("EMA")] Ema,
[EnumDescription("MACD")] Macd,
[EnumDescription("STOCH")] Stoch,
[EnumDescription("RSI")] Rsi,
}
public enum AvIntervalEnum
{
[EnumDescription("1min")] OneMinute,
[EnumDescription("5min")] FiveMinutes,
[EnumDescription("15min")] FifteenMinutes,
[EnumDescription("30min")] ThirtyMinutes,
[EnumDescription("60min")] SixtyMinutes,
[EnumDescription("daily")] Daily,
[EnumDescription("weekly")] Weekly,
[EnumDescription("monthly")] Monthly
}
public enum AvSeriesType
{
[EnumDescription("close")] Close,
[EnumDescription("open")] Open,
[EnumDescription("high")] High,
[EnumDescription("low")] Low,
}
}
}
`
The c# async main task (which obviously isn't working)...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlphaVantageApiWrapper.Test
{
public static class AlphaVantageApiDbLoader
{
public static async Task Main(string[] args)
{
var API_KEY = "EnterAPIHERE";
var StockTickers = new List<string> { "AAPL" }; //eventualy becomes a list pulled in from the DB for processing
foreach (var ticker in StockTickers)
{
var parameters = new List<AlphaVantageApiWrapper.ApiParam>
{
new AlphaVantageApiWrapper.ApiParam("function", AlphaVantageApiWrapper.AvFuncationEnum.Sma.ToDescription()),
new AlphaVantageApiWrapper.ApiParam("symbol", ticker),
new AlphaVantageApiWrapper.ApiParam("interval", AlphaVantageApiWrapper.AvIntervalEnum.Daily.ToDescription()),
new AlphaVantageApiWrapper.ApiParam("time_period", "5"),
new AlphaVantageApiWrapper.ApiParam("series_type", AlphaVantageApiWrapper.AvSeriesType.Open.ToDescription()),
};
//Start Collecting SMA values
var SMA_5 = await AlphaVantageApiWrapper.GetTechnical(parameters, API_KEY);
///var SMA_5Result = AlphaVantageApiWrapper.TechnicalDataObject() // can't all method error just want values fron list
parameters.FirstOrDefault(x => x.ParamName == "time_period").ParamValue = "20";
var SMA_20 = await AlphaVantageApiWrapper.GetTechnical(parameters, API_KEY);
parameters.FirstOrDefault(x => x.ParamName == "time_period").ParamValue = "50";
var SMA_50 = await AlphaVantageApiWrapper.GetTechnical(parameters, API_KEY);
parameters.FirstOrDefault(x => x.ParamName == "time_period").ParamValue = "200";
var SMA_200 = await AlphaVantageApiWrapper.GetTechnical(parameters, API_KEY);
//Change function to EMA
//Change function to RSI
//Change function to MACD
}
}
}
}
Any help would be greatly appreciated! I know the code runs in the background, I just can't seem to get it to a point to view it on the console screen. Eventually I would assign the symbol, date, value returned variable and read these to a DB. I'm used to using DataTables, but the async and .ToList is new to me. Thanks!!
I'm making an internal user inactivity monitor for work, and I'm using a windows form in conjunction with a topshelf service to do this, the code will write to a RabbitMQ Server and the service will consume the messages and forward them to a database, my code as it stands is throwing an exception with the following error;
Missing type map configuration or unsupported mapping.
Mapping types:
LogData -> DbLogData
AccessEye.LogData -> AccessEye.DbLogData
this is the code for my service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using NLog;
using IWshRuntimeLibrary;
using Topshelf;
using System.Data.Odbc;
using EasyNetQ;
using RabbitMQ;
using EasyNetQ.Topology;
using System.Threading.Tasks;
using System.Windows.Forms;
using AccessEye;
using System.ComponentModel;
namespace LogService
{
public class WindowsServiceHost : ServiceControl, ServiceShutdown
{
public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public static void WriteLogDataToDb(LogData data)
{
using (var db = new LogService.UserActivityDataContext())
{
DbLogData logData = AutoMapper.Mapper.Map<LogData, DbLogData>(data);
int t = (int)data.EventType;
EventType eventType = db.EventTypes.FirstOrDefault(r => r.Id == t);
if (eventType == null)
{
eventType = db.EventTypes.Add(new EventType
{
Event = GetEnumDescriptionAttributeValue(data.EventType),
Id = (int)data.EventType
});
db.SaveChanges();
}
logData.EventTypeId = eventType.Id;
db.LogEvents.Add(logData);
db.SaveChanges();
}
}
public static string GetEnumDescriptionAttributeValue(Enum value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
public bool Start(HostControl hostControl)
{
Program.bus = RabbitHutch.CreateBus("host=*****;virtualHost=*****;username=***;password=***").Advanced;
//var bus = RabbitHutch.CreateBus("host=*******;virtualHost=******;username=****;password=******").Advanced;
var queue = Queue.Declare(true, false, true, null);
var exchange = Exchange.DeclareFanout("UserActivityFanout", true, false, null);
var exchangeTopic = Exchange.DeclareTopic("UserActivity", true, false, null);
queue.BindTo(exchange, "#");
exchange.BindTo(exchangeTopic, "#");
Program.bus.Subscribe<AccessEye.LogData>(queue, (msg, messageRecInfo) => Task.Factory.StartNew(() =>
{
var data2 = LogDataFactory.CollectData();
data2.EventType = AccessEye.UserStateEvents.Logon;
WriteLogDataToDb(data2);
//AppForm.WriteLogDataToDb(data);
//Console.WriteLine(msg.Body.UserName + " -- " + msg.Body.ComputerName + " -- " + msg.Body.EventType + " -- " + msg.Body.TeamviewerId);
}));
return true;
}
public bool Stop(HostControl hostControl)
{
Logger.Trace("STOP");
Program.bus.Dispose();
return true;
}
public void Shutdown(HostControl hostControl)
{
Logger.Trace("SHUTDOWN");
Program.bus.Dispose();
}
}
}
and for the form
using System;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using AccessEye;
using System.Linq;
using EasyNetQ;
using EasyNetQ.Topology;
using Microsoft.Win32;
using MySql.Data.MySqlClient;
using NLog;
using ProtoBuf;
using System.Threading;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Reflection;
namespace LogProgram
{
public partial class AppForm : Form
{
public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private Screensaver watcher;
public Inactivity inactivity;
IAdvancedBus bus;
IExchange exchange;
public AppForm()
{
InitializeComponent();
ConfigureForm();
// todo: should be in setting
int pollingInterval = 5000;
inactivity = new Inactivity(pollingInterval);
inactivity.Inactive += inactivity_Inactive;
inactivity.Active += inactivity_Active;
inactivity.InactivityThresholdMs = 5 * 1000; // todo: should be in setting
inactivity.Start();
watcher = new Screensaver(pollingInterval);
watcher.ScreensaverOff += watcher_ScreensaverOff;
watcher.ScreensaverOn += watcher_ScreensaverOn;
watcher.Start();
SystemEvents.SessionEnding += SystemEvents_SessionEnding;
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
LogManager.ThrowExceptions = true;
// todo: connection string should be in setting
bus = RabbitHutch.CreateBus("host=as01.access.local;virtualHost=DEV-Reece;username=reece;password=reece").Advanced;
exchange = Exchange.DeclareTopic("UserActivity", true, false, null);
var fanout = Exchange.DeclareFanout("FanoutExchange", true, false, null);
fanout.BindTo(exchange, new[] { "#" });
}
public void ConfigureForm()
{
this.Hide();
TrayDisplayer.Visible = false;
}
public static void WriteLogDataToDb(LogData data)
{
using (var db = new LogService.UserActivityDataContext())
{
DbLogData logData = AutoMapper.Mapper.Map<LogData, DbLogData>(data);
int t = (int)data.EventType;
EventType eventType = db.EventTypes.FirstOrDefault(r => r.Id == t);
if (eventType == null)
{
eventType = db.EventTypes.Add(new EventType
{
Event = GetEnumDescriptionAttributeValue(data.EventType),
Id = (int)data.EventType
});
db.SaveChanges();
}
logData.EventTypeId = eventType.Id;
db.LogEvents.Add(logData);
db.SaveChanges();
}
}
public static string GetEnumDescriptionAttributeValue(Enum value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
private void AppForm_Load(object sender, EventArgs e)
{
}
void watcher_ScreensaverOn(object sender, EventArgs e)
{
var data = LogDataFactory.CollectData();
data.EventType = AccessEye.UserStateEvents.ScreensaverOn;
PublishLogData(data);
}
void watcher_ScreensaverOff(object sender, EventArgs e)
{
var data = LogDataFactory.CollectData();
data.EventType = AccessEye.UserStateEvents.ScreensaverOff;
PublishLogData(data);
}
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
var data = LogDataFactory.CollectData();
switch (e.Reason)
{
case SessionSwitchReason.SessionLock:
data.EventType = UserStateEvents.Lock;
break;
case SessionSwitchReason.SessionUnlock:
data.EventType = UserStateEvents.Unlock;
break;
}
PublishLogData(data);
}
public void PublishLogData(AccessEye.LogData LogData)
{
WriteLogDataToDb(LogData);
if (!bus.IsConnected) return;
try
{
using (var publishChannel = bus.OpenPublishChannel())
{
publishChannel.Publish(exchange, LogData.EventType.ToString(), new Message<LogData>(LogData));
}
}
catch (EasyNetQException)
{
//todo: handle
}
}
public static byte[] Serialize<T>(T instance)
{
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, instance);
return stream.ToArray();
}
}
private static T DeSerialize<T>(byte[] data)
{
using (var stream = new MemoryStream(data))
{
return Serializer.Deserialize<T>(stream);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
bus.Dispose();
}
public void inactivity_Active(object sender, EventArgs e)
{
inactivity.Stop();
var data = LogDataFactory.CollectData();
data.EventType = UserStateEvents.Active;
PublishLogData(data);
inactivity.Start();
}
public void inactivity_Inactive(object sender, EventArgs e)
{
inactivity.Stop();
var data = LogDataFactory.CollectData();
data.EventType = UserStateEvents.Inactive;
PublishLogData(data);
inactivity.Start();
}
public void SystemEvents_SessionEnding(object sender, EventArgs e)
{
var data = LogDataFactory.CollectData();
data.EventType = UserStateEvents.Logoff;
PublishLogData(data);
Logger.Trace("Logged off");
}
}
}
LogData Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProtoBuf;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AccessEye
{
public class DbLogData : LogData
{
[Key]
public int Id { get; set; }
public int? EventTypeId { get; set; }
[ForeignKey("EventTypeId")]
public virtual EventType EventTypeTest { get; set; }
}
}
Don't you need to create a map before you can use one;
AutoMapper.Mapper.CreateMap<LogData, DbLogData>();