I am having the following criteria:-
1.Create gmail group using query execution in sql db. This query will filter contacts on the basis of region.
2.These contacts may or may not be different for each send request. It depends upon the users those who are active at the time of send.
3.I am able to send mail to group.
Main problem is related with how i can update group each time before sending mail to group members excluding inactive members.
Please let me know if you need more explanation.I will try my best.
UPDATE:
I had done the following code from a Console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
namespace IMAPCommands
{
class Program
{
static void Main(string[] args)
{ GoogleContactService.InitializeService("mailid", "password");
List<ContactDetail> test = GoogleContactService.GetContacts("System Group: My Contacts");
//Use break point here
Console.ReadLine();
}
public class GoogleContactService
{
#region Properties
public static ContactsService GContactService = null;
#endregion
#region Methods
public static void InitializeService(string username, string password)
{
GContactService = new ContactsService("Contact Infomation");
GContactService.setUserCredentials(username, password);
}
public static List<ContactDetail> GetContacts(string GroupName = null)
{
List<ContactDetail> contactDetails = new List<ContactDetail>();
ContactsQuery contactQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
contactQuery.NumberToRetrieve = 1000;
if (!String.IsNullOrEmpty(GroupName))
{
GroupEntry ge = GetGroup(GroupName);
if (ge != null)
contactQuery.Group = ge.Id.AbsoluteUri;
}
else
{
string groupName = "";
GroupEntry ge = GetGroup(groupName);
if (ge != null)
contactQuery.Group = ge.Id.AbsoluteUri;
}
ContactsFeed feed = GContactService.Query(contactQuery);
foreach (ContactEntry entry in feed.Entries)
{
if (entry.Title.Text == "TechnicalBulletinName")
{
int test = entry.Emails.Count;
ContactDetail contact = new ContactDetail
{
Name = entry.Title.Text,
EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : "",
EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : "",
Phone1 = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : "",
Phone2 = entry.Phonenumbers.Count >= 2 ? entry.Phonenumbers[1].Value : "",
Address = entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].FormattedAddress : "",
Details = entry.Content.Content
};
contact.UserDefinedFields = new List<UDT>();
foreach (var udt in entry.UserDefinedFields)
{
contact.UserDefinedFields.Add(new UDT { Key = udt.Key, Value = udt.Value });
}
contactDetails.Add(contact);
}
}
return contactDetails;
}
#endregion
#region Helpers
public static GroupEntry GetGroup(string GroupName)
{
GroupEntry groupEntry = null;
GroupsQuery groupQuery = new GroupsQuery(GroupsQuery.CreateGroupsUri("default"));
groupQuery.NumberToRetrieve = 100;
GroupsFeed groupFeed = GContactService.Query(groupQuery);
foreach (GroupEntry entry in groupFeed.Entries)
{
if (entry.Title.Text.Equals(GroupName, StringComparison.CurrentCultureIgnoreCase))
{
groupEntry = entry;
break;
}
}
return groupEntry;
}
#endregion
}
public class ContactDetail
{
public string Name { get; set; }
public string EmailAddress1 { get; set; }
public string EmailAddress2 { get; set; }
public string Phone1 { get; set; }
public string Phone2 { get; set; }
public string Address { get; set; }
public string Details { get; set; }
public string Pipe { get; set; }
public string Relationship { get; set; }
public string Status { get; set; }
public List<UDT> UserDefinedFields { get; set; }
}
public class UDT
{
public string Key { get; set; }
public string Value { get; set; }
}
}
Still not able to get list of contacts which are member of group TechnicalBulletinName. I am only able to get emailID of this group not members of the group.
Related
I have read out per WMI the installed programs on a remote PC. I have read the Program Name, Program Publisher, Program Install.date and Program install.path properties and stored each of them in a separate string array. (All arrays with same length: 99)
I want to list the program informations according to the alphabetical order of Program name.
Is it possible to do that without combining the 4 arrays in one multidimensional array?
Or should I first combine the arrays to one two dimensional array ?
If yes how?
As I am new in C# I would thank you if you would make a suggestion. I have read lots of entries but I got more confused.
public string[] Programs_WMI_name = new string[99];
public string[] Programs_WMI_publisher = new string[99];
public string[] Programs_WMI_installdate = new string[99];
public string[] Programs_WMI_installlocation = new string[99];
I have tried this but get error:
In my public Class
public class TagService{
public string Programs_WMI_Name { get; set; }
public string Programs_WMI_Publisher { get; set; }
public string Programs_WMI_Installdate { get; set; }
public string Programs_WMI_Installlocation { get; set; }
public List<string> programs = new List<string>(99);
}
then
for (int i = 0; i < TagService.Programs_WMI_name.Length; i++)
{
programs.Add(new TagService
{
Programs_WMI_Name = TagService.Programs_WMI_name[i],
Programs_WMI_Publisher = TagService.Programs_WMI_publisher[i],
Programs_WMI_Installdate = TagService.Programs_WMI_installdate[i],
Programs_WMI_Installlocation = TagService.Programs_WMI_installlocation[i],
});
}
programs = programs.OrderBy(p => p.Programs_WMI_Name).ToList();
Do yourself and others a favor and use classes
public class ProgramInfo
{
public string Name { get; set; }
public string Publisher { get; set; }
public string InstallDate { get; set; }
public string InstallLocation { get; set; }
}
from arrays
var programs = new List<ProgramInfo>(Programs_WMI_name.Length);
for (int i = 0; i < Programs_WMI_name.Length; i++)
{
programs.Add(new ProgramInfo
{
Name = Programs_WMI_name[i],
Publisher = Programs_WMI_publisher[i],
InstallDate = Programs_WMI_installdate[i],
InstallLocation = Programs_WMI_installlocation[i],
});
}
better yet fill from query directly
var programs = new List<ProgramInfo>();
foreach (var row in new ManagementObjectSearcher(somequery).Get())
{
programs.Add(new ProgramInfo
{
Name = row["name"],
Publisher = row["publisher"],
InstallDate = row["installdate"],
InstallLocation = row["installlocation"],
});
}
complete example could look like this
using System;
using System.Linq;
using System.Collections.Generic;
namespace Test
{
public class ProgramInfo
{
public string Name { get; set; }
public string Publisher { get; set; }
public string InstallDate { get; set; }
public string InstallLocation { get; set; }
}
public class TagService
{
public static List<ProgramInfo> Programs { get; } = new List<ProgramInfo>();
public static void RefreshPrograms()
{
Programs.Clear();
foreach (var row in new ManagementObjectSearcher(somequery).Get())
{
programs.Add(new ProgramInfo
{
Name = row["name"],
Publisher = row["publisher"],
InstallDate = row["installdate"],
InstallLocation = row["installlocation"],
});
}
Programs.Sort((l, r) => string.Compare(l.Name, r.Name));
}
}
public Program
{
public static void Main()
{
TagService.ReadPrograms();
var properties = typeof(ProgramInfo).GetProperties();
Console.WriteLine(string.Join("|", properties.Select(p => p.Name.PaddRight(10))));
foreach (var program in TagService.Programs)
{
Console.WriteLine(string.Join("|", properties.Select(p => ((string)p.GetValue(program)).PaddRight(10))));
}
}
}
}
I want to check each page values from the API and against the values to change the color of the map marker.
This is my API: http://194.141.118.43:3001/?id=0 where id is from 0 to 16
I want:
if from ?id=0 AL = 1 the marker should be green
if from ?id=0 AL = 2 the marker should be yellow
if from ?id=0 AL = 3 the marker should be orange
if from ?id=0 AL = 4 the marker should be red
So I want to check for all 17 stations (from ?id=0 to ?id=16)
I am currently checking the property Alertlevelwebsite in this method with this API: http://194.141.118.43:3001/stations, But now I have to check all the values from this address for each pin and I have to put a color for the largest value for each pin.
http://194.141.118.43:3001/?id=0 (from 0 to 16)
I use this example from xamarin.forms.maps - https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithmaps/ and in CustomMapRenderer class I try to change the colors in this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
//Get Value
c_annotation = annotation;
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
((CustomMKAnnotationView)annotationView).MapCode = customPin.MapCode;
//Here I add the RequestUri for stations
string GenerateRequestUriStations(string endpoint)
{
string requestUri = endpoint;
requestUri += $"stations";
return requestUri;
}
//Here I need the loop from 0 to 16 every page and change the pin icons like above if statement
string GenerateRequestUri(string endpoint)
{
string requestUri = endpoint;
requestUri += $"?id=0";
return requestUri;
}
//This is the value who I need to compare result.WaterData.Ardaforecast but does not allow me to write result.WaterData.Ardaforecast and does not allow me to foreach here .. I don't know why ?
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
In the comments above the code I mean that when I write:
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var item in IAsyncResult)
{
}
When I try to write result. automatic puts me IAsyncResult.. I don't know why.. ?
Can I get an example of how to loop all the pages and change colors on the markers ?
My GetDataFromAPI look like this:
public IEnumerable<AlertLevel> GetDataFromAPI(int mapCode)
{
var listAlert = new List<AlertLevel>();
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint, mapCode));
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
var currentData = new AlertLevel()
{
dateForecast = item.DateTimeForecast,
levelForecast = item.AlertLevelForecast
};
listAlert.Add(currentData);
}
return listAlert;
}
My GetWaterDataForecast look like this:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using MaritsaTundzhaForecast.Models;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Services
{
public class RestServiceData
{
HttpClient _client1;
HttpClient _client2;
public RestServiceData()
{
_client1 = new HttpClient();
_client2 = new HttpClient();
}
public WaterBindingData GetWaterDataForecast(string query, string query2)
{
WaterDataJson waterData = new WaterDataJson();
WaterStationsJson waterStations = new WaterStationsJson();
WaterBindingData result = new WaterBindingData();
try
{
var task = Task.Run(() => _client1.GetAsync(query));
task.Wait();
var response = task.Result;
var task2 = Task.Run(() => _client2.GetAsync(query2));
task2.Wait();
var response2 = task2.Result;
if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
var content2 = response2.Content.ReadAsStringAsync().Result;
var json = content2.Replace("\"ardaforecast\":[[", "\"ardaforecast\":[ {\"items\": [")
.Replace("}],{\"fieldCount\"", "}],\"details\":{\"fieldCount\"")
.Replace("}]}", "}}]}");
waterData = JsonConvert.DeserializeObject<WaterDataJson>(json);
waterStations = JsonConvert.DeserializeObject<WaterStationsJson>(content);
result.WaterData = waterData;
result.WaterStation = waterStations;
}
}
catch (Exception ex)
{
Debug.WriteLine("\t\tERROR {0}", ex.Message);
}
return result;
}
}
}
My WaterBindingData look like:
using System;
namespace MaritsaTundzhaForecast.Models
{
public class WaterBindingData
{
public WaterDataJson WaterData { get; set; }
public WaterStationsJson WaterStation { get; set; }
}
}
My WaterDataJson and WaterStations look like:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast
{
public class WaterDataJson
{
public List<ForecastBody> Ardaforecast { get; set; }
}
public class ForecastBody
{
public ForecastItem[] Items { get; set; }
public ForecastDetails Details { get; set; }
}
public class ForecastItem
{
[JsonProperty("Dt")]
public DateTime DateTimeForecast { get; set; }
[JsonProperty("AL")]
public int AlertLevelForecast { get; set; }
}
public class ForecastDetails
{
public int fieldCount { get; set; }
public int affectedRows { get; set; }
public int insertId { get; set; }
public int serverStatus { get; set; }
public int warningCount { get; set; }
public int changedRows { get; set; }
public string message { get; set; }
public bool protocol41 { get; set; }
}
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Models
{
public class WaterStationsJson
{
public List<ForecastStations> Stations { get; set; }
}
public class ForecastStations
{
[JsonProperty("Map_code")]
public int MapCode { get; set; }
[JsonProperty("NAME_IME")]
public string NameEN { get; set; }
[JsonProperty("NAME_CYR")]
public string NameBG { get; set; }
[JsonProperty("Alertlevelwebsite")]
public int AlertLevelStation { get; set; }
[JsonProperty("CODENUM")]
public int CodeNum { get; set; }
}
}
I created two registration forms
1.User Registration
2.Company Registration (In one database)
I created a sign In page. How to retrieve the particular user from the tables.
class UserReg
{
[AutoIncrement, PrimaryKey]
public int UserID { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
public string Gender { get; set; }
public string State { get; set; }
}
The above code is for user registration table
class FuelReg
{
[AutoIncrement,PrimaryKey]
public int FuelID { get; set; }
public string FuelName { get; set; }
public string FuelPassword { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
}
The above code is for company registration.
Now the user and company should login with the same login page. How to implement this.
I tried some code but I cannot compare the particular user. My main problem is if the user and company provides similar user and password that would be a failure. So how to change it. (No validations given in the project)
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Map.db";
var con = new SQLiteAsyncConnection(dbpath);
try
{
UserReg t = new UserReg();
string query = string.Format("select UserName,UserPassword,Gender,State,Name from UserReg where UserName='{0}' and UserPassword='{1}'", text_user.Text, text_pass.Password);
List<UserReg> mylist = await con.QueryAsync<UserReg>(query);
if (mylist.Count == 1)
{
t = mylist[0];
}
if (t.UserName == text_user.Text && t.UserPassword == text_pass.Password && t.Gender!=null && t.Name!=null && t.State!=null)
{
this.Frame.Navigate(typeof(MainPage));
}
else
{
FuelReg f = new FuelReg();
string query1 = string.Format("select FuelName,FuelPassword,CompanyName,CompanyAddress from FuelReg where FuelName='{0}' and FuelPassword='{1}'", text_user.Text, text_pass.Password);
List<FuelReg> mylist1 = await con.QueryAsync<FuelReg>(query1);
if (mylist1.Count == 1)
{
f = mylist1[0];
}
if (f.FuelName == text_user.Text && f.FuelPassword == text_pass.Password && f.CompanyName!=null && f.CompanyAddress!=null)
{
this.Frame.Navigate(typeof(NewPage));
}
}
}
catch(Exception ex)
{
var msd = new MessageDialog("" + ex).ShowAsync();
}
}
So how to fetch the exact data when the user inputs in the SignIn page from the two tables
I set up three models. I'm not sure if I did it the best way, but it's the way I could understand it easily. I invoke the DepartmentProfile class. The first user found is not a manager so it goes into the else statement and successfully fills in the AD_UserProfile and adds it to the DepartmentProfile class.
The second user is the department manager so it goes into the if statement and errors out on the very first line with object not set to instance of object. What am I missing? Did I not set up the models correctly?
When it errors out
public class AD_UserProfile
{
public string distinguishedName { get; set; }
public string email { get; set; }
public string manager { get; set; }
public string name { get; set; }
public string userPrincipalName { get; set; } // Useful if we need to allow a user to 'log on' as a different user.
public string userName { get; set; }
}
public class AD_ManagerProfile
{
public string distinguishedName { get; set; }
public string email { get; set; }
public string manager { get; set; }
public string name { get; set; }
public string userPrincipalName { get; set; } // Useful if we need to allow a user to 'log on' as a different user.
public string userName { get; set; }
}
public class AD_DepartmentProfile
{
public AD_DepartmentProfile()
{
this.AD_UserProfile = new HashSet<AD_UserProfile>();
}
public string name { get; set; }
public virtual AD_ManagerProfile AD_ManagerProfile { get; set; }
public virtual ICollection<AD_UserProfile> AD_UserProfile { get; set; }
}
Here is the invocation of the classes:
public void GetDepartmentInfo(string department, string owner = "jeremy")
{
DirectoryEntry de = new DirectoryEntry("LDAP://server.server.com");
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = ("(&(objectCategory=person)(objectClass=User)(department=" + department + "))");
ds.SearchScope = SearchScope.Subtree;
AD_DepartmentProfile dp = new AD_DepartmentProfile();
dp.name = department; // assign department name
foreach (SearchResult temp in ds.FindAll())
{
if (owner == temp.Properties["sAMAccountName"][0].ToString())
{
//Current user is manager of department
dp.AD_ManagerProfile.distinguishedName = temp.Properties["distinguishedName"][0].ToString(); // This line errors out with instance not set to object error.
dp.AD_ManagerProfile.email = temp.Properties["mail"][0].ToString();
dp.AD_ManagerProfile.manager = temp.Properties["manager"][0].ToString();
dp.AD_ManagerProfile.name = temp.Properties["name"][0].ToString();
dp.AD_ManagerProfile.userPrincipalName = temp.Properties["userPrincipalName"][0].ToString();
dp.AD_ManagerProfile.userName = temp.Properties["sAMAccountName"][0].ToString();
}
else
{
//Current user is in department and does not manage it
AD_UserProfile p = new AD_UserProfile();
p.distinguishedName = temp.Properties["distinguishedName"][0].ToString();
p.email = temp.Properties["mail"][0].ToString();
p.manager = temp.Properties["manager"][0].ToString();
p.name = temp.Properties["name"][0].ToString();
p.userPrincipalName = temp.Properties["userPrincipalName"][0].ToString();
p.userName = temp.Properties["sAMAccountName"][0].ToString();
dp.AD_UserProfile.Add(p);
}
}
}
I don't see anywhere that you're initializing dp.AD_ManagerProfile, so it is likely null. You could either give it a value in GetDepartmentInfo or in the constructor.
if (owner == temp.Properties["sAMAccountName"][0].ToString())
{
//Current user is manager of department
dp.AD_ManagerProfile = new AD_ManagerProfile();
dp.AD_ManagerProfile.distinguishedName = temp.Properties["distinguishedName"][0].ToString(); // This line errors out with instance not set to object error.
or
public AD_DepartmentProfile()
{
this.AD_UserProfile = new HashSet<AD_UserProfile>();
this.AD_ManagerProfile = new AD_ManagerProfile();
}
I have an issue with serialization. I understand that methods can not be serialized for good reason, so I created a factory class to convert my existing class into a more manageable class.
This is the original class:
using Assets.Components;
using Assets.Data;
using IO.Components;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Assets
{
[Serializable]
public class Asset
{
#region Fields
Metadata _metadata;
string _fileName;
string _companyId;
#endregion
#region Properties
[Required]
public string DisplayName { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public int Id { get; set; }
public int CategoryId { get; set; }
public AssetType Type { get; set; }
public int LanguageId { get; set; }
public int StatusId { get; set; }
public DateTime DateCreated { get; set; }
public long DateCreatedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public int Views { get; set; }
public int Downloads { get; set; }
public string ThumbNail { get; set; }
public string Filename
{
set { _fileName = value; }
}
[Required]
public string CompanyId
{
set { _companyId = value; }
}
public string GetBaseDirectory
{
get { return "/Public/Uploads/" + this._companyId + "/0"; }
}
public double Rating
{
get
{
List<int> Score = new List<int>();
foreach (IRating oRating in this.Ratings())
{
Score.Add(oRating.Score);
}
return (Score.Count > 0) ? Score.Average() : 0;
}
}
public Metadata Metadata
{
get
{
if (_metadata == null)
{
_metadata = new Metadata(this.Id);
if (_metadata.AssetId == 0)
{
try
{
if (GetFilename() != null)
{
string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath(this.GetBaseDirectory), GetFilename());
if (!System.IO.File.Exists(path))
_metadata = new Metadata();
else
{
_metadata = MetadataExtractor.Create(path, this.Id);
_metadata.save();
}
}
else
{
_metadata = new Metadata();
}
}
catch
{
_metadata = new Metadata();
}
}
}
return _metadata;
}
}
public bool IsConverted { get; set; }
public string UserId { get; set; }
public DateTime DateModified { get; set; }
public long DateModifiedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public string Culture { get; set; }
public string Language { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public int CategoryCount { get; set; }
public int AssetCount { get; set; }
public bool IgnoreRights { get; set; }
#endregion
#region Contructors
/// <summary>
/// Default constructor
/// </summary>
public Asset()
{
}
/// <summary>
/// Get's the asset from the database, but set's the status to the profiles Requires Approval state.
/// </summary>
/// <param name="Id">Asset Id</param>
/// <param name="IsViewing">Boolean to update the reports table</param>
/// <param name="IsDownloading">Boolean to update the reports table</param>
public Asset(int Id, string UserId, string CompanyId, bool IsViewing, bool IsDownloading)
{
try
{
Asset oAsset = AssetData.GetAsset(Id, IsViewing, IsDownloading, UserId, CompanyId);
// Assign the values to this class
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.IsConverted = oAsset.IsConverted;
this.StatusId = oAsset.StatusId;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.UserName = oAsset.UserName;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
catch (Exception ex)
{
Stars.BLL.Error.Handling.LogError("Skipstone", "Asset", "Asset", ex.Message, ex.ToString()); // Record our error
}
}
/// <summary>
/// Used for executing some of the public methods
/// </summary>
/// <param name="Id">Id of the asset to retrieve</param>
/// <param name="CompanyId">The CompanyId of the company for the User</param>
public Asset(int Id, string CompanyId)
{
this.Id = Id;
this.CompanyId = CompanyId;
}
#endregion
#region Public methods
public string GetCompanyId()
{
return _companyId;
}
public string GetFilename()
{
return _fileName;
}
public string GetThumbnail()
{
return this.GetBaseDirectory + "/" + this.ThumbNail;
}
public string GetSmallThumbnail()
{
return this.GetBaseDirectory + "/sml_" + this.ThumbNail;
}
public Collection<IRating> Ratings()
{
Collection<IRating> oRatings = new Collection<IRating>();
try
{
oRatings = RatingData.get(this.Id);
}
catch
{
// record our error
}
return oRatings;
}
public Collection<IComment> Comments()
{
Collection<IComment> oComments = new Collection<IComment>();
try
{
oComments = CommentData.getAssetComments(this.Id);
}
catch (Exception ex)
{
// record our error
}
return oComments;
}
public void SaveMetadata()
{
}
public Collection<GenericType> Categories()
{
return MiscellaneousManager.AssetCategories(this.Id, GetCompanyId());
}
public void Save()
{
if (this.Id > 0)
{
AssetData.update(this);
}
else
{
Asset oAsset = AssetData.create(this);
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
}
public void delete()
{
AssetData.delete(this.Id);
AssetManager.RemoveFromCache(this);
}
#endregion
}
}
and this is my factory method:
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
which is part of my audittrailmanager class:
using Assets;
using Core;
using Reports.Objects;
using System;
using System.IO;
using System.Xml.Serialization;
namespace Reports.Components
{
public static class AuditTrailManager
{
#region Public methods
public static Audit AuditTrailFactory(Profile Profile, Object Object, Event Event)
{
Audit Audit = new Audit(SerializeObject(Object))
{
UserId = Profile.UserId,
UserName = Profile.UserName,
CompanyId = Profile.CompanyId,
ObjectName = GetObjectNameFromType(Object.GetType().ToString()),
Event = Event
};
return Audit;
}
#endregion
#region Private methods
private static string GetObjectNameFromType(string Type)
{
switch (Type)
{
case "Assets.Asset": return "Asset";
case "Core.SiteSetting": return "CompanySettings";
}
return "";
}
private static string SerializeObject(Object Object)
{
string ObjectType = Object.GetType().ToString();
switch (ObjectType)
{
case "Assets.Asset": return Serialize(AssetFactory((Asset)Object));
}
return ""; // If we fail
}
private static string Serialize(Object Object)
{
XmlSerializer ser = new XmlSerializer(Object.GetType());
using (StringWriter Xml = new StringWriter())
{
ser.Serialize(Xml, Object);
return (Xml.ToString());
}
}
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
#endregion
}
}
What I am trying to do is create an audit trail which records the object I am working on (in this case an asset) and I am serializing the class and inserting it into the database for use in reporting, etc.
My question is; is this the way to do it. Is there a better way?