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?
Related
I have been developing an api in c# asp.net with table relationships returning a json format as default and I'm added a custom csv formatter from WebApiContrib.Core.Formatter.Csv
my problem is that when I'm returning csv format from this json data.
[
{
"userId": 1275,
"username": "sample",
"applicationName": "sample",
"email": "samples#gmail.com",
"password": "samplepass1234,
"iUserProfile": {
"profileId": 1275,
"profileName": "sample"
}
}
]
I'm getting a csv format like this.
UserId,Username,ApplicationName,Email,Password,IUserProfile
1275,sample,sample,sample#gmail.com,samplepass1234,Odysseus_API.v2.Models.IUserProfileList
it is not getting the IUserProfile data on the csv format.
this is my custom formatter I get from WebApiContrib.Core.Formatter.Csv
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace WebApiContrib.Core.Formatter.Csv
{
/// <summary>
/// Original code taken from
/// http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format
/// Adapted for ASP.NET Core and uses ; instead of , for delimiters
/// </summary>
public class CsvOutputFormatter : OutputFormatter
{
private readonly CsvFormatterOptions _options;
private readonly bool useJsonAttributes = true;
public string ContentType { get; private set; }
public CsvOutputFormatter(CsvFormatterOptions csvFormatterOptions)
{
ContentType = "text/csv";
SupportedMediaTypes.Add(Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/csv"));
_options = csvFormatterOptions ?? throw new ArgumentNullException(nameof(csvFormatterOptions));
}
protected override bool CanWriteType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return IsTypeOfIEnumerable(type);
}
private bool IsTypeOfIEnumerable(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return typeof(IEnumerable).IsAssignableFrom(type);
}
/// <summary>
/// Returns the JsonProperty data annotation name
/// </summary>
/// <param name="pi">Property Info</param>
/// <returns></returns>
private string GetDisplayNameFromNewtonsoftJsonAnnotations(PropertyInfo pi)
{
if (pi.GetCustomAttribute<JsonPropertyAttribute>(false)?.PropertyName is string value)
{
return value;
}
return pi.GetCustomAttribute<DisplayAttribute>(false)?.GetName() ?? pi.Name;
}
public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
var response = context.HttpContext.Response;
Type type = context.Object.GetType();
Type itemType;
if (type.GetGenericArguments().Length > 0)
{
itemType = type.GetGenericArguments()[0];
}
else
{
itemType = type.GetElementType();
}
var streamWriter = new StreamWriter(response.Body, _options.Encoding);
if (_options.IncludeExcelDelimiterHeader)
{
await streamWriter.WriteLineAsync($"sep ={_options.CsvDelimiter}");
}
if (_options.UseSingleLineHeaderInCsv)
{
var values = useJsonAttributes
? itemType.GetProperties().Where(pi => !pi.GetCustomAttributes<JsonIgnoreAttribute>(false).Any()) // Only get the properties that do not define JsonIgnore
.Select(pi => new
{
Order = pi.GetCustomAttribute<JsonPropertyAttribute>(false)?.Order ?? 0,
Prop = pi
}).OrderBy(d => d.Order).Select(d => GetDisplayNameFromNewtonsoftJsonAnnotations(d.Prop))
: itemType.GetProperties().Select(pi => pi.GetCustomAttribute<DisplayAttribute>(false)?.Name ?? pi.Name);
await streamWriter.WriteLineAsync(string.Join(_options.CsvDelimiter, values));
}
foreach (var obj in (IEnumerable<object>)context.Object)
{
var vals = useJsonAttributes
? obj.GetType().GetProperties()
.Where(pi => !pi.GetCustomAttributes<JsonIgnoreAttribute>().Any())
.Select(pi => new
{
Order = pi.GetCustomAttribute<JsonPropertyAttribute>(false)?.Order ?? 0,
Value = pi.GetValue(obj, null)
}).OrderBy(d => d.Order).Select(d => new { d.Value })
: obj.GetType().GetProperties().Select(
pi => new
{
Value = pi.GetValue(obj, null)
});
string valueLine = string.Empty;
foreach (var val in vals)
{
if (val.Value != null)
{
var _val = val.Value.ToString();
//Substitute smart quotes in Windows-1252
if (_options.Encoding.EncodingName == "Western European (ISO)")
_val = _val.Replace('“', '"').Replace('”', '"');
//Escape quotes
_val = _val.Replace("\"", "\"\"");
//Replace any \r or \n special characters from a new line with a space
if (_options.ReplaceLineBreakCharacters && _val.Contains("\r"))
_val = _val.Replace("\r", " ");
if (_options.ReplaceLineBreakCharacters && _val.Contains("\n"))
_val = _val.Replace("\n", " ");
//Check if the value contains a delimiter/quote/newline and place it in quotes if so
if (_val.Contains(_options.CsvDelimiter) || _val.Contains("\"") || _val.Contains("\r") || _val.Contains("\n"))
_val = string.Concat("\"", _val, "\"");
valueLine = string.Concat(valueLine, _val, _options.CsvDelimiter);
}
else
{
valueLine = string.Concat(valueLine, string.Empty, _options.CsvDelimiter);
}
}
await streamWriter.WriteLineAsync(valueLine.Remove(valueLine.Length - _options.CsvDelimiter.Length));
}
await streamWriter.FlushAsync();
}
}
}
using System.Text;
namespace WebApiContrib.Core.Formatter.Csv
{
public class CsvFormatterOptions
{
public bool UseSingleLineHeaderInCsv { get; set; } = true;
public string CsvDelimiter { get; set; } = ",";
public Encoding Encoding { get; set; } = Encoding.Default;
public bool IncludeExcelDelimiterHeader { get; set; } = false;
public bool ReplaceLineBreakCharacters { get; set; } = true;
}
}
Object Class with both User and Profile
using System.Runtime.Serialization;
namespace Test_API.Models
{
[DataContract]
public class IUser
{
[DataMember(Name = "UserId")]
public int UserId { get; set; }
[DataMember(Name = "Username")]
public string? Username { get; set; }
[DataMember(Name = "ApplicationName")]
public string? ApplicationName { get; set; }
[DataMember(Name = "Email")]
public string? Email { get; set; }
[DataMember(Name = "Password")]
public string? Password { get; set; }
[DataMember(Name = "IUserProfile")]
public virtual IUserProfileList? IUserProfile { get; set; }
}
[DataContract()]
public class IUserProfileList
{
[DataMember(Name = "ProfileId")]
public int ProfileId { get; set; }
[DataMember(Name = "ProfileName")]
public string? ProfileName { get; set; }
}
}
I am using the Caliburn.Micro MVVM pattern.
I am writing an application that has 2 DataGrids, one holds a BindableCollection of RepairOrder, the other a BindableCollection WriteOff.
BindableCollection_WriteOff is property of BindableCollection_RepairOrder. (See the below code).
I need to find a way to write all the RepairOrder including the WriteOff associated with each RO. Besides RepairOrder class holding the WriteOff class, the WriteOff class does not have a way to tie the WriteOff to a RepairOrder.
Repair Order Class:
public class RepairOrder
{
public string Schedule { get; set; }
public string ControlNumber { get; set; }
public int Age { get; set; }
public double Value { get; set; }
public string Note { get; set; }
public double OrgValue { get; set; }
private List<WriteOff> _myWriteOffs;
public List<WriteOff> GetMyWriteOffs()
{
return _myWriteOffs;
}
public void AddMyWriteOff(WriteOff value)
{ _myWriteOffs.Add(value); }
public void DeleteMyWriteOff(WriteOff value)
{ _myWriteOffs.Remove(value); }
public RepairOrder(string CN, string SC, double VL)
{
ControlNumber = CN;
Schedule = SC;
Value = Math.Round(VL, 2);
Note = null;
_myWriteOffs = new List<WriteOff>();
}
public RepairOrder()
{
_myWriteOffs = new List<WriteOff>();
}
public static RepairOrder FromCSV(string CSVLine, string Sched)
{
string[] values = CSVLine.Split(',');
RepairOrder rep = new RepairOrder();
rep.ControlNumber = values[2];
rep.Value = Math.Round(double.Parse(values[5]),2);
rep.Age = int.Parse(values[4]);
rep.Schedule = Sched;
return rep;
}
}
Write Off Class:
public class WriteOff
{
private string _store;
public string Account { get; set; }
public string Description { get; set; }
public double WriteOffAmount { get; set; }
public string Schedule { get; set; }
public string Store
{
get {
if (String.IsNullOrEmpty(_store)) return "";
string temp = _store.Substring(0, 3);
return temp;
}
set { _store = value; }
}
public string Note { get; set; }
public WriteOff(string Acct, string Desc, double Amount, string _store)
{
Account = Acct;
Description = Desc;
WriteOffAmount = Amount;
Store = _store;
}
public string GetWOAccount() {
string SchedAccountNumber = "";
//{ "Navistar", "Cummins", "Misc", "Kenworth", "Mack/Volvo" }
switch (Account)
{
case "Navistar":
SchedAccountNumber = "222000";
break;
case "Cummins":
SchedAccountNumber = "223000";
break;
case "Misc":
SchedAccountNumber = "224500";
break;
default:
SchedAccountNumber = "";
break;
}
return SchedAccountNumber;
}
}
I am Deserializing my xml into C# class.
<?xml version="1.0" encoding="UTF-8"?>
<Applications>
<Application Name = "name1" MakerCheckerType="Operational" SanctionCheckNeeded="N" PreExistCheckNeeded="N" >
<InstrumentTypes>
<InstrumentType Version="1.0" PrimaryKeyExcel="Security Name" Name="Equity">
</InstrumentType>
<InstrumentType Name="Bond" Version="1.0" PrimaryKeyExcel="Security Name">
</InstrumentType>
</InstrumentTypes>
<ProcessSteps>
<ProcessStep VBAFunction="xyz" ExcelName="xyz" Name="Upload" />
<ProcessStep Name ="Approve_Reject" VBAFunction="xyz" ExcelName="xyz"/>
</ProcessSteps>
</Application>
<Application Name = "name2" MakerCheckerType="Real" SanctionCheckNeeded="Y" PreExistCheckNeeded="Y">
<InstrumentTypes>
<InstrumentType Version="1.0" PrimaryKeyExcel="Security Name" Name="Equity">
</InstrumentType>
<InstrumentType Name="Bond" Version="1.0" PrimaryKeyExcel="Security Name">
</InstrumentType>
</InstrumentTypes>
<ProcessSteps>
<ProcessStep VBAFunction="xyz" ExcelName="xyz" Name="Upload" />
<ProcessStep Name ="Approve_Reject" VBAFunction="xyz" ExcelName="xyz"/>
</ProcessSteps>
</Application>
</Applications>
classes are:
[XmlType("ProcessStep")]
public class IMAProcessStep
{
private string name;
private string vbaFunction;
private string excelName;
[XmlAttribute("Name")]
public string Name
{
get { return name; }
set { name = value; }
}
[XmlAttribute("VBAFunction")]
public string VBAFunction
{
get { return vbaFunction; }
set { vbaFunction = value; }
}
[XmlAttribute("ExcelName")]
public string ExcelName
{
get { return excelName; }
set { excelName = value; }
}
}
[XmlType("InstrumentType")]
public class IMAInstrumentType
{
[XmlAttribute("Name")]
public string Name
{
get;
set;
}
[XmlAttribute("Version")]
public string Version
{
get;
set;
}
[XmlAttribute("PrimaryKeyExcel")]
public string PrimaryKeyExcel
{
get;
set;
}
}
[XmlType("Application")]
public class IMAApplication
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("MakerCheckerType")]
public string MakerCheckerType { get; set; }
public bool IsMakerCheckerType
{
get
{
if (MakerCheckerType == "Real")
return true;
return false;
}
set
{
if (value)
MakerCheckerType = "Real";
else
MakerCheckerType = "Operational";
}
}
[XmlAttribute("SanctionCheckNeeded")]
public string SanctionCheckNeeded { get; set; }
[XmlAttribute("PreExistCheckNeeded")]
public string PreExistCheckNeeded { get; set; }
public bool IsSanctionCheckNeeded
{
get
{
return SanctionCheckNeeded == "Y";
}
set
{
SanctionCheckNeeded = value ? "Y" : "N";
}
}
public bool IsPreExistCheckNeeded
{
get
{
if (PreExistCheckNeeded == "Y")
return true;
return false;
}
set
{
if (value)
PreExistCheckNeeded = "Y";
else
PreExistCheckNeeded = "N";
}
}
[XmlArray("ProcessSteps")]
[XmlArrayItem(ElementName = "ProcessStep")]
public List<IMAInstrumentType> SupportedInstrumentTypes { get; set; }
[XmlArray("InstrumentTypes")]
[XmlArrayItem(ElementName = "InstrumentType")]
public List<IMAProcessStep> ProcessSteps { get; set; }
}
Here How I am De serializing it...
List<IMAApplication> appConfig = null;
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFilePath);
var xRoot = new XmlRootAttribute();
xRoot.ElementName = "Applications";
xRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(List<IMAApplication>), xRoot);
using (var stream = File.OpenRead(path))
appConfig = (List<IMAApplication>)serializer.Deserialize(stream);
return appConfig;
IMAApplication Deserialize successfully but processSteps and InstrumentTypes get only their Name attribute values. Rest of attributes are null.
Can anyone tell me what wrong here.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
IMAApplications applications = Deserialize(FILENAME);
}
static IMAApplications Deserialize(string configFilePath)
{
IMAApplications appConfig = null;
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFilePath);
var xRoot = new XmlRootAttribute();
xRoot.ElementName = "Applications";
xRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(IMAApplications), xRoot);
using (var stream = File.OpenRead(path))
appConfig = (IMAApplications)serializer.Deserialize(stream);
return appConfig;
}
}
[XmlRoot("ProcessStep")]
public class IMAProcessStep
{
private string name;
private string vbaFunction;
private string excelName;
[XmlAttribute("Name")]
public string Name
{
get { return name; }
set { name = value; }
}
[XmlAttribute("VBAFunction")]
public string VBAFunction
{
get { return vbaFunction; }
set { vbaFunction = value; }
}
[XmlAttribute("ExcelName")]
public string ExcelName
{
get { return excelName; }
set { excelName = value; }
}
}
[XmlRoot("InstrumentType")]
public class IMAInstrumentType
{
[XmlAttribute("Name")]
public string Name
{
get;
set;
}
[XmlAttribute("Version")]
public string Version
{
get;
set;
}
[XmlAttribute("PrimaryKeyExcel")]
public string PrimaryKeyExcel
{
get;
set;
}
}
[XmlRoot("Applications")]
public class IMAApplications
{
[XmlElement("Application")]
public List<IMAApplication> applications { get; set; }
}
[XmlRoot("Application")]
public class IMAApplication
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("MakerCheckerType")]
public string MakerCheckerType { get; set; }
public bool IsMakerCheckerType
{
get
{
if (MakerCheckerType == "Real")
return true;
return false;
}
set
{
if (value)
MakerCheckerType = "Real";
else
MakerCheckerType = "Operational";
}
}
[XmlAttribute("SanctionCheckNeeded")]
public string SanctionCheckNeeded { get; set; }
[XmlAttribute("PreExistCheckNeeded")]
public string PreExistCheckNeeded { get; set; }
public bool IsSanctionCheckNeeded
{
get
{
return SanctionCheckNeeded == "Y";
}
set
{
SanctionCheckNeeded = value ? "Y" : "N";
}
}
public bool IsPreExistCheckNeeded
{
get
{
if (PreExistCheckNeeded == "Y")
return true;
return false;
}
set
{
if (value)
PreExistCheckNeeded = "Y";
else
PreExistCheckNeeded = "N";
}
}
[XmlArray("InstrumentTypes")]
[XmlArrayItem(ElementName = "InstrumentType")]
public List<IMAInstrumentType> SupportedInstrumentTypes { get; set; }
[XmlArray("ProcessSteps")]
[XmlArrayItem(ElementName = "ProcessStep")]
public List<IMAProcessStep> ProcessSteps { get; set; }
}
}
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.
I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}