Delete item from inner collection - c#

Inner Collection
public class ItemsDetails
{
//Constructor
public ItemsDetails(int iID,
string sItemName,
Decimal iPrice,
int iQuantity,
int iPostalCode,
bool bisDB,
string SImagePath)
{
this.iID = iID;
this.sItemName = sItemName;
this.iPrice = iPrice;
this.iquantity = iQuantity;
this.iPostalCode = iPostalCode;
this.bisDB = bisDB;
this.sImagePath = SImagePath;
}
public ItemsDetails()
{
}
#region PrivateProperties
private int iID;
private string sItemName;
private Decimal iPrice;
private int iquantity;
private int iPostalCode;
private string sImagePath;
private int iMasterID;
#endregion
//static List<ItemsDetails> itemsDetails = new List<ItemsDetails>();
#region public Properties
public bool bisChanged = false;
public bool bisDB = true;
#endregion
public int IMasterID
{
get
{
return this.iMasterID;
}
set
{
if (this.iMasterID != value)
bisChanged = true;
this.iMasterID = value;
}
}
public bool BisChanged
{
get
{
return this.bisChanged;
}
set
{
this.bisChanged = value;
}
}
public int IPostalCode
{
get
{
return this.iPostalCode;
}
set
{
if (this.iPostalCode != value)
bisChanged = true;
this.iPostalCode = value;
}
}
public int Iquantity
{
get
{
return this.iquantity;
}
set
{
if (this.iquantity != value)
bisChanged = true;
this.iquantity = value;
}
}
public Decimal IPrice
{
get
{
return this.iPrice;
}
set
{
if (this.iPrice != value)
bisChanged = true;
this.iPrice = value;
}
}
public string SItemName
{
get
{
return this.sItemName;
}
set
{
if (this.sItemName != value)
bisChanged = true;
this.sItemName = value;
}
}
public string SImagePath
{
get
{
return this.sImagePath;
}
set
{
if (this.sImagePath != value)
bisChanged = true;
this.sImagePath = value;
}
}
public int IID // unique id
{
get
{
return this.iID;
}
set
{
if (this.iID != value)
bisChanged = true;
this.iID = value;
}
}
}
Main collection
public class ItemsMapping
{
private int itemMasterID;
private string sCatagoryName;
private string sImagePath;
private ICollection<ItemsDetails> iCollectionItemDetails;
public string SImagePath
{
get
{
return this.sImagePath;
}
set
{
this.sImagePath = value;
}
}
public string SCatagoryName
{
get
{
return this.sCatagoryName;
}
set
{
this.sCatagoryName = value;
}
}
public ICollection<ItemsDetails> ICollectionItemDetails
{
get
{
return this.iCollectionItemDetails;
}
set
{
this.iCollectionItemDetails = value;
}
}
public int ItemMasterID
{
get
{
return this.itemMasterID;
}
set
{
this.itemMasterID = value;
}
}
}
Object of collection
Collection<ItemsMapping> objItemCollection = getdata();// from db
Collection<ItemsDetails> objDeleteItems = itemsToDelete();// from selected items
Result i need to delete items from inner collection objItemCollection based on objDeleteItems collection.
I expect without using foreach/for loop. Trying to find solution on linq
Thanks in advance..

Linq (Language-Integrated Query)is for querying, not for modifying (i.e. updating, adding, deleting). Use foreach loop if you want to modify collection.
You can write query which returns set of items without those you want to delete, and then use results of this query instead of your original collection. If you have same instances of ItemsDetails objects in both collections (otherwise you will need to override Equals and GetHashCode of ItemsDetails class), and you don't need duplicates in result:
objItemCollection.ICollectionItemDetails =
objItemCollection.ICollectionItemDetails.Except(objDeleteItems);
But I would go without query. Simple loop will do the job (overriding of Equals and GetHashCode still required if you don't use same instances of ItemsDetails):
foreach(var item in objDeleteItems)
objItemCollection.ICollectionItemDetails.Remove(item);
You can move this logic to extension method
public static void RemoveAll<T>(
this ICollection<T> source, IEnumerable<T> itemsToRemove)
{
if (source == null)
throw new ArgumentNullException("source");
foreach(var item in itemsToRemove)
source.Remove(item);
}
Now code will look like:
objItemCollection.ICollectionItemDetails.RemoveAll(objDeleteItems);

Related

Using ServerManager to list virtual directories separated by type

I'm using ServerManager (Microsoft.Web.Administration.dll) to create an Application to manage my web servers, All of my server are running IIS 7 and above. Majority of the site is complete, i can manage servers, sites, FTP, SSL etc.
Here is my issue,
I am able to create virtual directories and applications, but having an issue with listing them separately when viewing the site information as you can do in IIS. I am able to list the all together as Virtual Directories by just getting item.VirtualDirectories[0].PhysicalPath but would like to show Applications in one column and basic virtual directories in the second column. I'm sure i need to be looking for if root application path is siteid, or if it has an AppPool somehow but having a hard time figuring how. Any help would be appreciated.
My Code:
SiteVirtualDirectory.cs
private string anonymousUsername;
private string anonymousUserPassword;
private string contentPath;
private bool enableWritePermissions;
private bool enableParentPaths;
private bool enableDirectoryBrowsing;
private bool enableAnonymousAccess;
private bool enableWindowsAuthentication;
private bool enableBasicAuthentication;
private bool enableDynamicCompression;
private bool enableStaticCompression;
private string defaultDocs;
private string httpRedirect;
private HttpError[] httpErrors;
private HttpErrorsMode errorMode;
private HttpErrorsExistingResponse existingResponse;
private MimeMap[] mimeMaps;
private HttpHeader[] httpHeaders;
private bool aspInstalled;
private string aspNetInstalled;
private string phpInstalled;
private bool perlInstalled;
private bool pythonInstalled;
private bool coldfusionInstalled;
private bool cgiBinInstalled;
private string applicationPool;
private bool dedicatedApplicationPool;
private string parentSiteName;
private bool redirectExactUrl;
private bool redirectDirectoryBelow;
private bool redirectPermanent;
private bool sharePointInstalled;
private bool iis7;
private string consoleUrl;
private string php5VersionsInstalled;
public string AnonymousUsername
{
get { return anonymousUsername; }
set { anonymousUsername = value; }
}
public string AnonymousUserPassword
{
get { return anonymousUserPassword; }
set { anonymousUserPassword = value; }
}
public string ContentPath
{
get { return contentPath; }
set { contentPath = value; }
}
public string HttpRedirect
{
get { return httpRedirect; }
set { httpRedirect = value; }
}
public string DefaultDocs
{
get { return defaultDocs; }
set { defaultDocs = value; }
}
public MimeMap[] MimeMaps
{
get { return mimeMaps; }
set { mimeMaps = value; }
}
public HttpError[] HttpErrors
{
get { return httpErrors; }
set { httpErrors = value; }
}
public HttpErrorsMode ErrorMode
{
get { return errorMode; }
set { errorMode = value; }
}
public HttpErrorsExistingResponse ExistingResponse
{
get { return existingResponse; }
set { existingResponse = value; }
}
public string ApplicationPool
{
get { return this.applicationPool; }
set { this.applicationPool = value; }
}
public bool EnableParentPaths
{
get { return this.enableParentPaths; }
set { this.enableParentPaths = value; }
}
public HttpHeader[] HttpHeaders
{
get { return this.httpHeaders; }
set { this.httpHeaders = value; }
}
public bool EnableWritePermissions
{
get { return this.enableWritePermissions; }
set { this.enableWritePermissions = value; }
}
public bool EnableDirectoryBrowsing
{
get { return this.enableDirectoryBrowsing; }
set { this.enableDirectoryBrowsing = value; }
}
public bool EnableAnonymousAccess
{
get { return this.enableAnonymousAccess; }
set { this.enableAnonymousAccess = value; }
}
public bool EnableWindowsAuthentication
{
get { return this.enableWindowsAuthentication; }
set { this.enableWindowsAuthentication = value; }
}
public bool EnableBasicAuthentication
{
get { return this.enableBasicAuthentication; }
set { this.enableBasicAuthentication = value; }
}
public bool EnableDynamicCompression
{
get { return this.enableDynamicCompression; }
set { this.enableDynamicCompression = value; }
}
public bool EnableStaticCompression
{
get { return this.enableStaticCompression; }
set { this.enableStaticCompression = value; }
}
public bool AspInstalled
{
get { return this.aspInstalled; }
set { this.aspInstalled = value; }
}
public string AspNetInstalled
{
get { return this.aspNetInstalled; }
set { this.aspNetInstalled = value; }
}
public string PhpInstalled
{
get { return this.phpInstalled; }
set { this.phpInstalled = value; }
}
public bool PerlInstalled
{
get { return this.perlInstalled; }
set { this.perlInstalled = value; }
}
public bool PythonInstalled
{
get { return this.pythonInstalled; }
set { this.pythonInstalled = value; }
}
public bool ColdFusionInstalled
{
get { return this.coldfusionInstalled; }
set { this.coldfusionInstalled = value; }
}
public bool DedicatedApplicationPool
{
get { return this.dedicatedApplicationPool; }
set { this.dedicatedApplicationPool = value; }
}
public string ParentSiteName
{
get { return this.parentSiteName; }
set { this.parentSiteName = value; }
}
public bool RedirectExactUrl
{
get { return this.redirectExactUrl; }
set { this.redirectExactUrl = value; }
}
public bool RedirectDirectoryBelow
{
get { return this.redirectDirectoryBelow; }
set { this.redirectDirectoryBelow = value; }
}
public bool RedirectPermanent
{
get { return this.redirectPermanent; }
set { this.redirectPermanent = value; }
}
public bool CgiBinInstalled
{
get { return this.cgiBinInstalled; }
set { this.cgiBinInstalled = value; }
}
public bool SharePointInstalled
{
get { return this.sharePointInstalled; }
set { this.sharePointInstalled = value; }
}
public bool IIs7
{
get { return this.iis7; }
set { this.iis7 = value; }
}
public string ConsoleUrl
{
get { return consoleUrl; }
set { consoleUrl = value; }
}
public string Php5VersionsInstalled
{
get { return php5VersionsInstalled; }
set { php5VersionsInstalled = value; }
}
[XmlIgnore]
public string VirtualPath
{
get
{
// virtual path is rooted
if (String.IsNullOrEmpty(ParentSiteName))
return "/"; //
else if (!Name.StartsWith("/"))
return "/" + Name;
//
return Name;
}
}
[XmlIgnore]
public string FullQualifiedPath
{
get
{
if (String.IsNullOrEmpty(ParentSiteName))
return Name;
else if (Name.StartsWith("/"))
return ParentSiteName + Name;
else
return ParentSiteName + "/" + Name;
}
}
Get Virtual Directories:
public class GetVirtualDirectories(ServerManager iismanager, string siteId)
{
if (!SiteExists(iismanager, siteId))
return new SiteVirtualDirectory[] { };
var vdirs = new List<SiteVirtualDirectory>();
var iisObject = iismanager.Sites[siteId];
//
foreach (var item in iisObject.Applications)
{
// do not list root Virtual Directory
if (item.Path == "/")
continue;
//
vdirs.Add(new SiteVirtualDirectory
{
Name = ConfigurationUtility.GetNonQualifiedVirtualPath(item.Path),
ContentPath = item.VirtualDirectories[0].PhysicalPath
});
}
//
return vdirs.ToArray();
}

Custom Collection/List To Store Custom Objects

I have a customer object class:
public class customerObject
{
private string _address1;
private string _address2;
private string _address3;
private string _category;
private string _country;
private string _county;
private string _custcode;
private string _fullname;
private string _int_rep_hou;
private string _int_rep_key;
private double _lat;
private double _lng;
private string _postcode;
private string _rep_code;
private string _telephone;
public customerObject()
{
}
public string Address1
{
get { return _address1; }
set { _address1 = value; }
}
public string Address2
{
get
{
return _address2;
}
set { _address2 = value; }
}
public string Address3 { get { return _address3; } set { _address3 = value; } }
public string Category
{
get { return _category; }
set { _category = value; }
}
public string Country { get { return _country; } set { _country = value; } }
public string County { get { return _county; } set { _county = value; } }
public string Custcode
{
get { return _custcode; }
set { _custcode = value; }
}
public string Fullname
{
get { return _fullname; }
set { _fullname = value; }
}
public string Int_rep_hou
{
get { return _int_rep_hou; }
set { _int_rep_hou = value; }
}
public string Int_rep_key
{
get { return _int_rep_key; }
set { _int_rep_key = value; }
}
public double Lat { get { return _lat; } set { _lat = value; } }
public double Lng { get { return _lng; } set { _lng = value; } }
public string Postcode { get { return _postcode; } set { _postcode = value; } }
public string Rep_code
{
get { return _rep_code; }
set { Rep_code = value; }
}
public string Telephone { get { return _telephone; } set { _telephone = value; }
}
}
I have a CustomCollections class
public class CustomerCollection
{
public List<customerObject> Customers { get; set; }
}
My method that loops through dt rows and converts to a customer object
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//Create Collection Object
Valueobjects.CustomerCollection Collection = new Valueobjects.CustomerCollection();
foreach (DataRow row in temptablename.Rows)
{
//Create Customer Object
Valueobjects.customerObject Customer = new Valueobjects.customerObject();
//set values of customer object
Customer.Rep_code = "";
Customer.Int_rep_key = "";
Customer.Int_rep_hou = "";
Customer.Fullname = row["Fullname"].ToString().Trim();
Customer.Custcode = row["Custcode"].ToString().Trim();
Customer.Category = row["Category"].ToString().Trim();
Customer.Address1 = row["Address1"].ToString().Trim();
Customer.Address2 = row["Address2"].ToString().Trim();
Customer.Address3 = row["Address3"].ToString().Trim();
Customer.Postcode = row["Postcode"].ToString().Trim();
Customer.Country = row["Country"].ToString().Trim();
Customer.Telephone = row["Telephone"].ToString().Trim();
Customer.Lat = Convert.ToDouble(row["Lat"]);
Customer.Lng = Convert.ToDouble(row["Lng"]);
Customer.County = row["County"].ToString().Trim();
//add to the collection (list)
Collection.Customers.Add(Customer);
}
temptablename = null;
return Collection;
}
However when I create a new Customer object and a new CustomerCollection object I am getting an error when adding the customer to the collection list.
Error:
Error 32 Cannot implicitly convert type
'Classes.Valueobjects.CustomerCollection' to
'System.Collections.Generic.List'
Your method is returning a List<CustomerCollection>:
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//...
}
But the code is trying to return a CustomerCollection:
return Collection;
Just as the error says, these two types are different.
If a CustomerCollection is already a collection of customers, then semantically what is a List<Valueobjects.CustomerCollection>? A collection of collections? It seems like you're over-pluralizing your objects :)
There are two approaches here. Either return a CustomerCollection from the method:
public CustomerCollection dolist(DataTable temptablename)
{
//...
}
Or use a List<Customer> if you want to use generic lists as your collection containers:
public List<Customer> dolist(DataTable temptablename)
{
//...
var Collection = new List<Customer>();
//...
Collection.Add(Customer);
//...
return Collection;
}
Side note: You may want to stick to C# conventions for variable naming. As you can see from the code highlighting here on Stack Overflow, your variable names can easily be mistaken for classes/types, which can cause confusion when supporting the code.
Return a CustomerCollection instead of a List<Valueobjects.CustomerCollection>:
public Valueobjects.CustomerCollection Dolist(DataTable temptablename)
{
// ...
Your object has a list, it is not a list.
MSDN: Inheritance

LINQ using shared object

I have a table (called !test) containing the following data:
id code desc
0 55 fifty-five
1 66 sixty-six
2 100 hundred
When I use the following code to access that table, it compiles & runs OK,
but doesn't populate the Tuple structure.
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.!test")]
public partial class Test
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ID;
private TupleClass _Tuple;
public Test()
{
_Tuple = new TupleClass();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", DbType="Int NOT NULL", IsPrimaryKey=true)]
public int ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this._ID = value;
}
}
}
public TupleClass Tuple
{
get
{
return this._Tuple;
}
set
{
if ((this._Tuple.Code != value.Code))
{
this._Tuple.Code = value.Code;
}
if ((this._Tuple.Desc != value.Desc))
{
this._Tuple.Desc = value.Desc;
}
}
}
}
public class TupleClass
{
private int _Code;
private string _Desc;
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Code", DbType = "Int NOT NULL")]
public int Code
{
get
{
return this._Code;
}
set
{
if ((this._Code != value))
{
this._Code = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Desc", DbType = "NVarChar(50)")]
public string Desc
{
get
{
return this._Desc;
}
set
{
if ((this._Desc != value))
{
this._Desc = value;
}
}
}
}
Any ideas what I've done wrong here? Thanks

C# - Marshall by value problem!

Here is the thing, I have a problem creating a new object using the remote mechanism "marshal by value".
Here is my class:
[Serializable]
internal class Empleado_MBV
{
public Empleado_MBV()
{
Id = 123456789;
Nombres = "NotEntry";
Apellidos = "NotEntry";
FechaNacimiento = DateTime.MinValue;
Direccion = "NotEntry";
Metapreferencias = "NotEntry";
}
private List<Multas> _multas;
internal List<Multas> Multas
{
get { return _multas; }
set { _multas = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _nombres;
public string Nombres
{
get { return _nombres; }
set { _nombres = value; }
}
private string _apellidos;
public string Apellidos
{
get { return _apellidos; }
set { _apellidos = value; }
}
private DateTime _FecNac;
public DateTime FechaNacimiento
{
get { return _FecNac; }
set { _FecNac = value; }
}
private string _direccion;
public string Direccion
{
get { return _direccion; }
set { _direccion = value; }
}
private string _metapreferencias;
public string Metapreferencias
{
get { return _metapreferencias; }
set { _metapreferencias = value; }
}
public string _AppDomainHost
{
get { return AppDomain.CurrentDomain.FriendlyName.ToString(); }
}
}
But when I try to create an object in another "appdomain", the property "_AppDomainHost" of "Empleado" does not show the "appdomain" I had created, but show the "appdomain" by default. Some ideas?
AppDomain ad1 = AppDomain.CreateDomain("NewAppDomain");
//Crear new object in my new AD.
Empleado_MBV mbv_emp = (Empleado_MBV)ad1.CreateInstanceFromAndUnwrap("DEMO_MBV_MBR.exe", "DEMO_MBV_MBR.Empleado_MBV");
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName.ToString());
Console.WriteLine("MBV : {0}",mbv_emp._AppDomainHost.ToString());
Console.ReadLine();
Result:
DEMO_MBV_MBR.vshost.exe
MBV : DEMO_MBV_MBR.vshost.exe
The result that I want:
DEMO_MBV_MBR.vshost.exe
MBV : NewAppDomain
You need to store AppDomain in Empleado_MBV's constructor.
What you are doing right now is displaying current AppDomain using its Current static property. It will return the AppDomain where current code is being executed.
Example:
private string _appDomainHost;
public string _AppDomainHost
{
get { return _appDomainHost; }
}
and in constructor:
_appDomainHost = AppDomain.CurrentDomain.FriendlyName.ToString();

Errors: How to save a many-to-many relationship in Castle Active Record?

I've been trying for hours to get many-to-many relationship to save with Castle ActiveRecord. What am I doing wrong? I can't find anything in the documentation or on google. There is data in the database.
Courses have a many to many relationship with Books.
Test code.
Database.Course c = new Database.Course();
c.Number = "CS 433";
c.Name = "Databases";
c.Size = 34;
c.Books = Database.Book.FindAll();
c.Save();
Also doesn't work
foreach(Database.Book b in Database.Book.FindAll()){
c.Books.Add(b);
}
Database Classes
[ActiveRecord]
public class Course : ActiveRecordValidationBase<Course>
{
private int? id;
private string number;
private string name;
private string description;
private int size; //number of students in class
//references
private IList books = new ArrayList();
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
get
{
return string.Format("{0} - {1}", Number, Name);
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Number
{
get { return number; }
set { number = value; }
}
[Property, ValidateNonEmpty]
public string Name
{
get { return name; }
set { name = value; }
}
[Property(ColumnType="StringClob")]
public string Description
{
get { return description; }
set { description = value; }
}
[Property]
public int Size
{
get { return size; }
set { size = value; }
}
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id", Inverse = true)]
public IList Books
{
get { return books; }
set { books = value; }
}
}
[ActiveRecord]
public class Book : ActiveRecordValidationBase<Book>
{
private int? id;
private string title;
private string edition;
private string isbn;
private bool is_available_for_order;
//relations
private IList authors = new ArrayList();
private IList bookordercount = new ArrayList();
private IList courses = new ArrayList();
private Inventory inventory;
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
//*
get {
string str;
if (Edition == null || Edition == "")
str = Title;
else
str = string.Format("{0} ({1})", Title, Edition);
if (Authors.Count != 0)
{
return string.Format("{0} by {1}", str, FormattedAuthors);
}
else
{
return str;
}
}
/*/
get
{
return Title;
}
//*/
}
public string FormattedAuthors
{
get
{
if (Authors.Count == 0) return "";
StringBuilder sb = new StringBuilder();
int i = 0, end = Authors.Count;
foreach (Author a in Authors)
{
i++;
sb.Append(a.FormattedName);
if (i != end) sb.Append("; ");
}
return sb.ToString();
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Title
{
get { return title; }
set { title = value; }
}
[Property]
public string Edition
{
get { return edition; }
set { edition = value; }
}
[Property, ValidateNonEmpty]
public string Isbn
{
get { return isbn; }
set { isbn = value; }
}
[Property]
public bool IsAvailableForOrder
{
get { return is_available_for_order; }
set { is_available_for_order = value; }
}
//relations
[HasAndBelongsToMany(typeof(Author),
Table = "BookAuthor", ColumnKey = "book_id", ColumnRef = "author_id")]
public IList Authors
{
get { return authors; }
set { authors = value; }
}
[HasMany(typeof(BookOrderCount), Table = "BookOrderCounts", ColumnKey = "BookId")]
public IList BookOrderCount
{
get { return bookordercount; }
set { bookordercount = value; }
}
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id")]
public IList Courses
{
get { return courses; }
set { courses = value; }
}
[OneToOne]
public Inventory Inventory
{
get { return inventory; }
set { inventory = value; }
}
}
Make sure you put the Inverse = true where you want it. From the Castle AR docs,
It is wise to choose one side of the
relation as the owner. The other side,
the non-writable, need to use
Inverse=true.
Put the Inverse = true on the other side of the relationship, like this:
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id")]
public IList<Book> Books
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id", Inverse = true)]
public IList<Course> Courses
You also have to add attributes to the top of both classes - at the moment they don't know what tables they're mapped to. Currently you have this:
public class Course : ActiveRecordBase<Course>
Add this (where "course" is the name of your Course table):
[ActiveRecord("course")]
public class Course : ActiveRecordBase<Course>

Categories