C# - Look up direct reports in active directory - c#

I am using System.DirectoryServices.AccountManagement to manage my login user account.
I am able to get information for login user, but not able to get direct reports user id based on manager.
var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
I have refer to this link: C# - Look up a users manager in active directory
But still didn't get any clue. Anyone can help me on this?

I managed to figure out the directory property for direct reports("directReports").
Just to add a new directory property as below:
// Create the "Direct Report" property.
[DirectoryProperty("directReports")]
public List<string> DirectReports
{
get
{
var directReportsName = new List<string>();
if (ExtensionGet("directReports").Length == 0)
return directReportsName;
for (int i = 0; i < ExtensionGet("directReports").Length; i++)
{
string userString = (string)ExtensionGet("directReports")[i];
//example of userString = CN=name,OU=Users,OU=department,OU=AP,OU=Software,DC=company,DC=priv,DC=company,DC=com
//split by comma
var tempCN = userString.Split(',').First();
var tempName = tempCN.Split('=');
var userName= tempName[1];
directReportsAlias.Add(userName);
}
return directReportsName;
}
}

I have designed class for active directory search.
This class support.
Search Employee By Same Account Name
Search Employee By Employee Id
Search Employee By Employee Code
Search Employee By Employee Email
Search Employee Manage
Search Team Member
CLASS CODE
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace UAT.COMMON
{
#region RefranceHelpers
/*
//https://www.c-sharpcorner.com/article/active-directory-and-net/
//https://ianatkinson.net/computing/adcsharp.htm
//https://ianatkinson.net/computing/adcsharp.htm
*/
#endregion
public enum SearchBy
{
StartNTID=0,
}
public class ManageDirectoryServices : IDisposable
{
public ContextType contextType = ContextType.Domain;
public PrincipalContext Context { get; protected set; }
public UserPrincipal User { get; protected set; }
public UserPrincipal Manager { get; protected set; }
public bool IsManager { get; protected set; }
public List<UserPrincipal> DirectReports { get; protected set; }
public class AuthenticationResult
{
public AuthenticationResult()
{
IdentityError = new List<IdentityError>();
IsSuccess = IdentityError.Count > 0;
}
public List<IdentityError> IdentityError { get; private set; }
public String RoleName { get; private set; }
public Boolean IsSuccess { get; set; }
public ManageDirectoryServices Context { get; set; }
}
public ManageDirectoryServices()
{
Context = new PrincipalContext(contextType);
DirectReports = new List<UserPrincipal>();
}
public ManageDirectoryServices(string ntid)
{
Context = new PrincipalContext(contextType);
DirectReports = new List<UserPrincipal>();
GetEmployeeByNTID(NormalizeNTID(ntid));
}
/// <summary>
///
/// </summary>
/// <param name="ntid">This is SamAccountName</param>
/// <returns></returns>
public ManageDirectoryServices GetEmployeeByNTID(string ntid)
{
if (string.IsNullOrWhiteSpace(ntid)) return null;
UserPrincipal searchTemplate = new UserPrincipal(Context)
{
SamAccountName = ntid
};
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
public ManageDirectoryServices GetEmployee(string strSearch,string prop)
{
if (string.IsNullOrWhiteSpace(strSearch)) return this;
if (string.IsNullOrWhiteSpace(prop)) return this;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(cn={0})", strSearch);
search.PropertiesToLoad.Add(prop);
var result = search.FindAll();
if (result != null)
{
int directReports = result.Count; //result.Properties["displayname"].Count;
if (directReports < 0) return null;
for (int counter = 0; counter < directReports; counter++)
{
var user = (string)result[counter].Properties["givenname"][counter];
var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
this.DirectReports.Add(reporte);
IsManager = true;
}
return this;
}
return null;
}
public ManageDirectoryServices GetEmployee(UserPrincipal searchTemplate)
{
if (searchTemplate == null) return null;
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
/// <summary>
///
/// </summary>
/// <param name="NTID">This is SamAccountName</param>
/// <returns></returns>
public bool IsUserExist(string NTID)
{
var data = GetEmployeeByNTID(NormalizeNTID(NTID));
return !string.IsNullOrWhiteSpace(data?.User?.SamAccountName);
}
public bool IsUserExist()
{
var data = User;
return !string.IsNullOrWhiteSpace(data?.SamAccountName);
}
public ManageDirectoryServices GetEmployeeByEmail(string email)
{
if (string.IsNullOrWhiteSpace(email)) return null;
UserPrincipal searchTemplate = new UserPrincipal(Context)
{
EmailAddress = email
};
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
public ManageDirectoryServices GetEmployeeByEmpId(string employeeId)
{
if (string.IsNullOrWhiteSpace(employeeId)) return null;
UserPrincipal searchTemplate = new UserPrincipal(Context)
{
EmployeeId = employeeId
};
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
public ManageDirectoryServices GetManager()
{
if (this.User == null) return null;
DirectoryEntry ManagerDE = this.User.GetUnderlyingObject() as DirectoryEntry;
var manager = ManagerDE.Properties["manager"].Value.ToString();
UserPrincipal oManager = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, manager);
this.Manager = oManager;
return this;
}
public ManageDirectoryServices GetDirectReports()
{
if (this.User == null) return this;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(cn={0})", this.User.SamAccountName);
search.PropertiesToLoad.Add("directReports");
SearchResult result = search.FindOne();
if (result != null)
{
int directReports = result.Properties["directReports"].Count;
if (directReports < 0) return null;
for (int counter = 0; counter < directReports; counter++)
{
var user = (string)result.Properties["directReports"][counter];
var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
this.DirectReports.Add(reporte);
IsManager = true;
}
return this;
}
return null;
}
public string NormalizeNTID(string Id)
{
if (string.IsNullOrWhiteSpace(Id)) return "";
return Id.Trim().ToUpper().Replace(#"\", "")
.Replace("\\", "")
.Replace("/", "")
.Replace("//", "")
.Replace("MS", "")
.Replace("MS//", "")
.Replace("MS\\", "");
}
public AuthenticationResult SignIn(string ntid, string password)
{
var NormalizeNTID = this.NormalizeNTID(ntid);
bool IsAuthenticated = false;
IdentityError identityError = new IdentityError();
ManageDirectoryServices context = null;
AuthenticationResult authenticationResult = new AuthenticationResult();
var IsSuccess = Context.ValidateCredentials(NormalizeNTID, password, ContextOptions.Negotiate);
context = GetEmployeeByNTID(NormalizeNTID);
if (IsSuccess)
{
if (context.User != null)
{
IsAuthenticated = true;
this.User = context.User;
authenticationResult.Context = context;
authenticationResult.IsSuccess = true;
}
}
else
{
if (!IsAuthenticated || User == null)
{
authenticationResult.IdentityError.Add(new IdentityError
{
Code = "InCorrectUserAndPassword",
Description = "Username or Password is not correct"
});
}
if (context.User.IsAccountLockedOut())
{
authenticationResult.IdentityError.Add(new IdentityError
{
Code = "YourAccountIsLocked",
Description = "Your account is locked."
});
}
if (context.User.Enabled.HasValue && User.Enabled.Value == false)
{
authenticationResult.IdentityError.Add(identityError = new IdentityError
{
Code = "YourAccountIsDisabled",
Description = "Your account is disabled"
});
}
else
{
authenticationResult.IdentityError.Add(new IdentityError
{
Code = "InvalidLogin",
Description = "In valid login!! Please try again"
});
}
}
return authenticationResult;
}
#region ************Async Envelope**************
public async Task<ManageDirectoryServices> GetEmployeeByNTIDAsync(string ntid)
{
return await Task.Run(() => GetEmployeeByNTID(ntid));
}
public async Task<ManageDirectoryServices> GetEmployeeByEmailAsync(string email)
{
return await Task.Run(() => GetEmployeeByEmail(email));
}
public async Task<ManageDirectoryServices> GetEmployeeByEmpIdAsync(string employeeId)
{
return await Task.Run(() => GetEmployeeByEmpId(employeeId));
}
public async Task<ManageDirectoryServices> GetManagerAsync()
{
return await Task.Run(() => GetManager());
}
public async Task<ManageDirectoryServices> GetDirectReportsAsync()
{
return await Task.Run(() => GetDirectReports());
}
public async Task<AuthenticationResult> SignInAsync(string ntid, string password)
{
return await Task.Run(() => SignIn(ntid, password));
}
#endregion
public void Dispose()
{
this.Dispose();
GC.Collect();
}
}
}
How To Use
[TestMethod]
public void ContractorInitialsSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices(MSID);
var context = manageDirectoryServices.User;
Assert.AreEqual(MSID, context.SamAccountName);
}
[TestMethod]
public void SignInSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.SignIn(MSID,MSPASSWORD);
Assert.AreEqual(EMAIL, context.Context.User.EmailAddress);
}
[TestMethod]
public void GetEmployeeByNTIDSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
Assert.AreEqual(MSID, context.User.SamAccountName);
}
[TestMethod]
public void GetManagerSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
var manager = context.GetManager();
Assert.AreEqual(MANAGER_NTID, context.Manager.SamAccountName);
}
[TestMethod]
public void GetReportesSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
var repcontext = context.GetDirectReports();
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}
[TestMethod]
public void GetEmployeeByEmailSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByEmail(EMAIL);
Assert.AreEqual(EMAIL, context.User.EmailAddress);
}
[TestMethod]
public void GetEmployeeByEmployeeIdSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByEmpId(EMPLOYEEID);
Assert.AreEqual(EMPLOYEEID, context.User.EmployeeId);
}
[TestMethod]
public void IsUserExistSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var IsExist = manageDirectoryServices.IsUserExist(MSID);
Assert.AreEqual(true, IsExist);
}
[TestMethod]
public void IsUserExistFail()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var IsExist = manageDirectoryServices.IsUserExist("invalidid");
Assert.AreEqual(false, IsExist);
}
[TestMethod]
public void GetEmployeeSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var searchTemplate = new System.DirectoryServices.AccountManagement.UserPrincipal(manageDirectoryServices.Context) {
SamAccountName= MSID,
EmailAddress=EMAIL,
EmployeeId=EMPLOYEEID
};
var context = manageDirectoryServices.GetEmployee(searchTemplate);
Assert.AreEqual(MSID, context.User.SamAccountName);
}
[TestMethod]
public void GetEmployeeNameSuccess0()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var repcontext = manageDirectoryServices.GetEmployee("abhishek", "givenname");
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}
[TestMethod]
public void GetEmployeeNameSuccess1()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var repcontext = manageDirectoryServices.GetEmployee("abhishek", "name");
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}
[TestMethod]
public void GetEmployeeNameSuccess2()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var repcontext = manageDirectoryServices.GetEmployee("abhishek", "displayname");
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}

Related

NullReferenceException when trying to add a new object to a list using inheritance

I am having an issue adding a new Account() to a list that is in FileAccountRepository.cs, I am still learning about inheritance, so there might be something that I do not know. In PremiumAccountTestRepository.cs, I am trying to pass the _account that is a new Account() with properties and try to add it to the list that is in FileAccountRepository.cs. The error message I get is that _fileAccountRepository was null on PremiumAccountTestRepository.cs. Would like to know the reason I cannot add to the list that is FileAccountRepository.cs?
FileAccountRepository.cs
public class FileAccountRepository : IAccountRepository
{
public List<Account> fileAccounts = new List<Account>();
public FileAccountRepository(string mode)
{
GetUsers(mode);
}
public void GetUsers(string mode) {
var dictionaryOfModes = new Dictionary<string, string>
{
["FreeTest"] = "F",
["BasicTest"] = "B",
["PremiumTest"] = "P"
};
string path = #".\Accounts.txt";
string[] rows = File.ReadAllLines(path);
for (int i = 1; i < rows.Length; i++)
{
string[] columns = rows[i].Split(',');
if (columns[3] == dictionaryOfModes[mode])
{
Account _account = new Account();
_account.AccountNumber = columns[0];
_account.Name = columns[1];
_account.Balance = Decimal.Parse(columns[2]);
if (columns[3] == "F")
{
_account.Type = AccountType.Free;
}
else if (columns[3] == "B")
{
_account.Type = AccountType.Basic;
}
else if (columns[3] == "P")
{
_account.Type = AccountType.Premium;
}
//fileAccounts.Add(_account);
StoreAccounts(_account);
}
}
}
public Account LoadAccount(string AccountNumber)
{
return fileAccounts.FirstOrDefault(x => x.AccountNumber == AccountNumber);
}
public void SaveAccount(Account account)
{
//_account = account;
}
public void StoreAccounts(Account addAccount)
{
fileAccounts.Add(addAccount);
}
}
PremiumAccountTestRepository.cs
public class PremiumAccountTestRepository : IAccountRepository
{
private FileAccountRepository _fileAccountRepository;
public PremiumAccountTestRepository(FileAccountRepository fileAccountRepository)
{
_fileAccountRepository = fileAccountRepository;
}
public PremiumAccountTestRepository()
{
StoreAccounts(_account);
}
private static Account _account = new Account
{
Name = "Premium Account",
Balance = 100M,
AccountNumber = "44444",
Type = AccountType.Premium
};
public Account LoadAccount(string AccountNumber)
{
if (_fileAccountRepository.fileAccounts.Any(x => x.AccountNumber == AccountNumber))
{
return _account;
}
return null;
}
public void SaveAccount(Account account)
{
_account = account;
}
public void StoreAccounts(Account addAccount)
{
_fileAccountRepository.fileAccounts.Add(addAccount); //_fileAccountRepository was null.
}
}
AccountManagerFactory.cs
public static AccountManager Create()
{
string mode = ConfigurationManager.AppSettings["Mode"].ToString();
switch (mode)
{
case "FreeTest":
return new AccountManager(new FileAccountRepository(mode), new FreeAccountTestRepository());
case "BasicTest":
return new AccountManager(new FileAccountRepository(mode), new BasicAccountTestRepository());
case "PremiumTest":
return new AccountManager(new FileAccountRepository(mode), new PremiumAccountTestRepository());
default:
throw new Exception("Mode value in app config is not valid");
}
}
Try this code, I was not able to test it :
public class PremiumAccountTestRepository : IAccountRepository
{
private FileAccountRepository _fileAccountRepository;
private Account _account;
public PremiumAccountTestRepository(FileAccountRepository fileAccountRepository)
{
_fileAccountRepository = fileAccountRepository;
_account= new Account
{
Name = "Premium Account",
Balance = 100M,
AccountNumber = "44444",
Type = AccountType.Premium
};
StoreAccounts(_account);
}
public Account LoadAccount(string AccountNumber)
{
if (_fileAccountRepository.fileAccounts.Any(x => x.AccountNumber == AccountNumber))
{
return _account;
}
return null;
}
public void SaveAccount(Account account)
{
_account = account;
}
public void StoreAccounts(Account addAccount)
{
_fileAccountRepository.fileAccounts.Add(addAccount); //_fileAccountRepository was
null.
}
}
The issue in your code is that you have two constructors, _fileAccountRepository is not initialized with the dependency injection because of the other empty constructor
_fileAccountRepository is set in exactly one place in your code, in
public PremiumAccountTestRepository(FileAccountRepository fileAccountRepository)
The second creator
public PremiumAccountTestRepository()
Does not set it, so it will be null.
I suggest putting a break in both creators and see which is being called, and then you will know where from.
I don't see the top level driving code in your posting. I strongly suspect that the second form of the creator is getting called, and thus _fileAccountRepository is null.
what happens if this line is altered from
private FileAccountRepository _fileAccountRepository
to
private FileAccountRepository _fileAccountRepository = new FileAccountRepository()

Exception of type 'Braintree.Exceptions.AuthenticationException' and Private key is seen as "PrivateKey"

Check out Controller
public class CheckoutsController : Controller
{
public IBraintreeConfiguration config = new BraintreeConfiguration();
public static readonly TransactionStatus[] transactionSuccessStatuses = {
TransactionStatus.AUTHORIZED,
TransactionStatus.AUTHORIZING,
TransactionStatus.SETTLED,
TransactionStatus.SETTLING,
TransactionStatus.SETTLEMENT_CONFIRMED,
TransactionStatus.SETTLEMENT_PENDING,
TransactionStatus.SUBMITTED_FOR_SETTLEMENT
};
public ActionResult New()
{
var gateway = config.GetGateway();
This is the line that is triggering the error ('Braintree.Exceptions.AuthenticationException')
var clientToken = gateway.ClientToken.generate();
ViewBag.ClientToken = clientToken;
return View();
}
public ActionResult Create()
{
var gateway = config.GetGateway();
Decimal amount;
try
{
amount = Convert.ToDecimal(Request["amount"]);
}
catch (FormatException e)
{
TempData["Flash"] = "Error: 81503: Amount is an invalid format.";
return RedirectToAction("New");
}
var nonce = Request["payment_method_nonce"];
var request = new TransactionRequest
{
Amount = amount,
PaymentMethodNonce = nonce,
Options = new TransactionOptionsRequest
{
SubmitForSettlement = true
}
};
Result<Transaction> result = gateway.Transaction.Sale(request);
if (result.IsSuccess())
{
Transaction transaction = result.Target;
return RedirectToAction("Show", new { id = transaction.Id });
}
else if (result.Transaction != null)
{
return RedirectToAction("Show", new { id = result.Transaction.Id });
}
else
{
string errorMessages = "";
foreach (ValidationError error in result.Errors.DeepAll())
{
errorMessages += "Error: " + (int)error.Code + " - " + error.Message + "\n";
}
TempData["Flash"] = errorMessages;
return RedirectToAction("New");
}
}
public ActionResult Show(String id)
{
var gateway = config.GetGateway();
Transaction transaction = gateway.Transaction.Find(id);
if (transactionSuccessStatuses.Contains(transaction.Status))
{
TempData["header"] = "Sweet Success!";
TempData["icon"] = "success";
TempData["message"] = "Your test transaction has been successfully processed. See the Braintree API response and try again.";
}
else
{
TempData["header"] = "Transaction Failed";
TempData["icon"] = "fail";
TempData["message"] = "Your test transaction has a status of " + transaction.Status + ". See the Braintree API response and try again.";
};
ViewBag.Transaction = transaction;
return View();
}
}
BrainTree Configuration
public class BraintreeConfiguration : IBraintreeConfiguration
{
public string Environment { get; set; }
public string MerchantId { get; set; }
public string PublicKey { get; set; }
public string PrivateKey { get; set; }
private IBraintreeGateway BraintreeGateway { get; set; }
public IBraintreeGateway CreateGateway()
{
Environment = System.Environment.GetEnvironmentVariable("BraintreeEnvironment");
MerchantId = System.Environment.GetEnvironmentVariable("BraintreeMerchantId");
PublicKey = System.Environment.GetEnvironmentVariable("BraintreePublicKey");
PrivateKey = System.Environment.GetEnvironmentVariable("BraintreePrivateKey");
if (MerchantId == null || PublicKey == null || PrivateKey == null)
{
Environment = GetConfigurationSetting("BraintreeEnvironment");
MerchantId = GetConfigurationSetting("BraintreeMerchantId");
PublicKey = GetConfigurationSetting("BraintreePublicKey");
PrivateKey = GetConfigurationSetting("BraintreePrivateKey");
}
return new BraintreeGateway(Environment, MerchantId, PublicKey, PrivateKey);
}
public string GetConfigurationSetting(string setting)
{
//watch this
MerchantId = "**************";
PublicKey = "***************";
The merchant id and public Key are being assigned their correct values but the private Key is being assigned as "PrivateKey"
PrivateKey = "*************************";
return ConfigurationManager.AppSettings[setting];
}
public IBraintreeGateway GetGateway()
{
if (BraintreeGateway == null)
{
BraintreeGateway = CreateGateway();
}
return BraintreeGateway;
}
}

EF cannot update column when success savechanges

I can not update my database using EF (UpdateSpecified() method is not working). My Add() method works fine.
Edit: I observed the SaveChanges Method it always return 1 ,it let me confused because I updated 3 tables.
I discovered the RepositoryFactory's IQueryable code, it had changed:
My code:
public class GoodsModel
{
private IRepositoryFactory _repositoryFactory;
private IServiceFactory _serviceFactory;
private IGoodsService _goodsService;
private IGoodsTypeService _goodsTypeService;
private IUsersService _userService;
private IOrderService _orderService;
private IOrdersRepository orderRepo;
private IUsersRepository userRepo;
private IGoodsRepository goodsRepo;
public GoodsModel()
{
_repositoryFactory = new RepositoryFactory();
_repositoryFactory.OpenSession();
_serviceFactory = new ServiceFactory(_repositoryFactory);
_goodsService = _serviceFactory.CreateGoodsService();
_goodsTypeService = _serviceFactory.CreateGoodsTypeService();
_userService = _serviceFactory.CreateUsersService();
_orderService = _serviceFactory.CreateOrderService();
userRepo = _repositoryFactory.CreateUsersRepository();
orderRepo = _repositoryFactory.CreateOrdersRepository();
goodsRepo = _repositoryFactory.CreateGoodsRepository();
orderRepo = _repositoryFactory.CreateOrdersRepository();
}
public bool BuyProduct(BuyProductDto model)
{
string name = HttpContext.Current.User.Identity.Name;
// _repositoryFactory.OpenSession();
using (_repositoryFactory)
{
var user = _userService.Filter(x => x.UserName == name).FirstOrDefault();
var good = _goodsService.Filter(x => x.GoodNumber == model.GoodNumber).FirstOrDefault();
//var userRepo = _repositoryFactory.CreateUsersRepository();
//var goodRepo = _repositoryFactory.CreateGoodsRepository();
Users u = new Users();
Goods g = new Goods();
try
{
//substract when buy product.
int remainScore = user.UserScore - (int)good.GoodScore;
if (remainScore < 0)
{
return false;
}
u.UserId = user.UserId;
u.UserScore = remainScore;
userRepo.Attach(u);
userRepo.UpdateSpecified(u);
g.Id = good.Id;
//same as above syntax
g.GoodsQuantity = good.GoodsQuantity - 1;
goodsRepo.Attach(g);
goodsRepo.UpdateSpecified(g);
//orderRepo = _repositoryFactory.CreateOrdersRepository();
orderRepo.Add(new Orders
{
GoodId = good.Id,
InsertTime = DateTime.Now,
Status = 0,
UserId = user.UserId,
OrderNo = DateTime.Now.ToString("yyyyMMddss"),
UpdateTime = DateTime.Now
});
_repositoryFactory.Commit();
}
catch (Exception ex)
{
_repositoryFactory.RollBack();
return false;
}
}
return true;
}
}
The code of framework is here:
public void UpdateSpecified(T entity)
{
var type = entity.GetType();
if (type.IsPrimitive || type == typeof(string))
{
var props = type.GetProperties();
foreach (var prop in props)
{
string propValue = prop.GetValue(entity, null) != null ? prop.GetValue(entity, null).ToString() : string.Empty;
if (!string.IsNullOrEmpty(propValue))
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = true;
}
else
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = false;
}
}
}
}
public void Attach(T entity)
{
DataContext.Set<T>().Attach(entity);
}
}
The entity code like this, it contains the navigation attribute:
public class Users
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime InsertTime { get; set; }
public ICollection<UsersUserGroup> UsersUserGroups { get; set; }
public int UserScore { get; set; }
}
oaky.... I have solved it ,it is fool question ,I admit; Correct Code:
public void UpdateSpecified(T entity)
{
var props = entity.GetType().GetProperties();
foreach (var prop in props)
{
if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string))
{
string propValue = prop.GetValue(entity, null) != null ? prop.GetValue(entity, null).ToString() : string.Empty;
if (!string.IsNullOrEmpty(propValue))
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = true;
}
else
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = false;
}
}
}
}

Download Bundle File into a folder inside another folder

I made an application to download files into a folder inside another folder.
The name for the folder obtained from DataFile name from database and match the name of the image that has been downloaded.
I'm having a problem, that when downloading to a folder for the first bundle of data is fine, but at the time of downloading the data bundle again the previous folder and the new folder also download both files.
When downloading the files that differ it will create a new folder again and the two previous folders are also downloaded the file. For more details, can see in the image below:
And should one folder contains two files.
JSON:
RHData Class:
[PrimaryKey]
public string SKU { get; set; }
public string Judul { get; set; }
public string Tipe { get; set; }
public string Harga { get; set; }
public string Gratis { get; set; }
public string DataFile { get; set; }
RHViewModel class:
class RHViewModel
{
private string sku = string.Empty;
public string SKU
{
get { return sku; }
set
{
if (sku == value)
return;
sku = value;
RaisePropertyChanged("SKU");
}
}
private string judul = string.Empty;
public string Judul
{
get { return judul; }
set
{
if (judul == value)
return;
judul = value;
RaisePropertyChanged("Judul");
}
}
private string tipe = string.Empty;
public string Tipe
{
get { return tipe; }
set
{
if (tipe == value)
return;
tipe = value;
RaisePropertyChanged("Tipe");
}
}
private string harga = string.Empty;
public string Harga
{
get { return harga; }
set
{
if (harga == value)
return;
harga = value;
RaisePropertyChanged("Harga");
}
}
private string cover = string.Empty;
private string gratis = string.Empty;
public string Gratis
{
get { return gratis; }
set
{
if (gratis == value)
return;
gratis = value;
RaisePropertyChanged("Gratis");
}
}
private string dataFile = string.Empty;
public string DataFile
{
get { return dataFile; }
set
{
if (dataFile == value)
return;
dataFile = value;
RaisePropertyChanged("DataFile");
}
}
public RHViewModel GetItem(string itemSku)
{
var item = new RHViewModel();
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var _item = (db.Table<RHData>().Where(
c => c.SKU == itemSku)).Single();
item.SKU = _item.SKU;
item.Judul = _item.Judul;
item.Tipe = _item.Tipe;
item.Harga = _item.Harga;
item.Gratis = _item.Gratis;
item.DataFile = _item.DataFile;
}
return item;
}
public string SaveItem(RHViewModel item)
{
string result = string.Empty;
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
try
{
var existingItem = (db.Table<RHData>().Where(
c => c.SKU == item.sku)).SingleOrDefault();
if (existingItem != null)
{
existingItem.SKU = item.SKU;
existingItem.Judul = item.Judul;
existingItem.Tipe = item.Tipe;
existingItem.Harga = item.Harga;
existingItem.Gratis = item.Gratis;
existingItem.DataFile = item.DataFile;
int success = db.Update(existingItem);
}
else
{
int success = db.Insert(new RHData()
{
SKU = item.SKU,
Judul = item.Judul,
//Deskripsi = item.Deskripsi,
Tipe = item.Tipe,
Harga = item.Harga,
Gratis = item.Gratis,
//Cover = item.Cover,
//File = item.File,
DataFile = item.DataFile
});
}
result = "Success";
}
catch
{
result = "This item was not saved.";
}
}
return result;
}
public string DeleteItem(string itemDataFile)
{
string result = string.Empty;
using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var existingItem = dbConn.Query<RHData>("select * from RH where DataFile =" + itemDataFile).FirstOrDefault();
if (existingItem != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingItem);
if (dbConn.Delete(existingItem) > 0)
{
result = "Success";
}
else
{
result = "This item was not removed";
}
});
}
return result;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
RHItemsViewModel Class:
class RHItemsViewModel : RHViewModel
{
private ObservableCollection<RHViewModel> items;
public ObservableCollection<RHViewModel> Items
{
get
{
return items;
}
set
{
items = value;
RaisePropertyChanged("Items");
}
}
public ObservableCollection<RHViewModel> GetItems()
{
items = new ObservableCollection<RHViewModel>();
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var query = db.Table<RHData>().OrderBy(c => c.SKU);
foreach (var _item in query)
{
var item = new RHViewModel()
{
//SKU = _item.SKU,
SKU = _item.SKU,
Judul = _item.Judul,
//Deskripsi = _item.Deskripsi,
Tipe = _item.Tipe,
Harga = _item.Harga,
Gratis = _item.Gratis,
//Cover = _item.Cover,
//File = _item.File,
DataFile = _item.DataFile
};
items.Add(item);
}
}
return items;
}
}
}
App.Xaml.CS
public static string DB_PATH = Path.Combine(ApplicationData.Current.LocalFolder.Path, "RH.sqlite");
public static SQLite.Net.Platform.WinRT.SQLitePlatformWinRT SQLITE_PLATFORM;
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
SQLITE_PLATFORM = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
if (!CheckFileExists("RH.sqlite").Result)
{
using (var db = new SQLiteConnection(SQLITE_PLATFORM, DB_PATH))
{
db.CreateTable<RHData>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
}
return false;
}
Code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//GC.Collect();
BukuAudio dlList = e.Parameter as BukuAudio;
if (dlList != null)
{
Queue<DownloadOperation> downloadOperationList = new Queue<DownloadOperation>();
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadProgress.Visibility = Visibility.Visible;
downloadfilename.Visibility = Visibility.Visible;
statusdownload.Visibility = Visibility.Visible;
deleteBtn.Visibility = Visibility.Collapsed;
viewBtn.Visibility = Visibility.Collapsed;
foreach (var path in dlList.BundlePath)
{
DownloadBuku(path);
for (int i = 0; i<dlList.BundlePath.Count;i++)
{
downloadfilename.Text = dlList.BundleName.ElementAt(i);
Uri uri = new Uri(path);
string filename = path.Substring(uri.LocalPath.LastIndexOf("/") + 1);
downloadfilename.Text = String.Format("Unduh '{0}'", filename);
}
}
DownloadGambar(dlList.Cover);
}
else
{
DownloadProgress.Visibility = Visibility.Collapsed;
downloadfilename.Visibility = Visibility.Collapsed;
statusdownload.Visibility = Visibility.Collapsed;
deleteBtn.Visibility = Visibility.Visible;
viewBtn.Visibility = Visibility.Visible;
}
bookAudio = e.Parameter as BookAudio;
}
private async void downloadClicked(object sender, RoutedEventArgs e)
{
Uri uri = new Uri(itemDetail.BundlePath.First());
string filename = System.IO.Path.GetFileName(uri.LocalPath);
string statustext = String.Format("Download Buku '{0}'?", itemDetail.Judul);
string sudahada = String.Format("Buku '{0}' sudah ada/sedang didownload", itemDetail.Judul);
MessageDialog messageDialog;
try
{
StorageFolder library = await ApplicationData.Current.LocalFolder.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
var file = await library.GetFileAsync(filename);
messageDialog = new MessageDialog(sudahada, "Buku sudah ada");
messageDialog.Commands.Add(new UICommand("Library", (command) =>
{
this.Frame.Navigate(typeof(library.LibraryPage));
}));
messageDialog.Commands.Add(new UICommand("Batal", (command) =>
{
//rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
}));
}
catch (FileNotFoundException ex)
{
//file not exists show download dialog
// Create the message dialog and set its content and title
messageDialog = new MessageDialog(statustext, "Download");
// Add commands and set their callbacks
messageDialog.Commands.Add(new UICommand("Download", (command) =>
{
itemsViewModel = new RHItemsViewModel();
itemsViewModel.SaveItem(new RHViewModel()
{
SKU = itemDetail.SKU.ToString(),
Judul = itemDetail.Judul.ToString(),
Tipe = itemDetail.Tipe.ToString(),
Harga = itemDetail.Harga.ToString(),
Gratis = itemDetail.Gratis.ToString(),
DataFile = itemDetail.DataFile.ToString()
});
this.Frame.Navigate(typeof(library.LibraryPage), itemDetail);
}));
messageDialog.Commands.Add(new UICommand("Batal", (command) =>
{
//rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
}));
}
// Show the message dialog
await messageDialog.ShowAsync();
}
}
Library Page:
private async void DownloadBuku(string fileLocation)
{
itemsViewModel = new RHItemsViewModel();
items = new ObservableCollection<RHViewModel>();
using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var existingItem = dbConn.Table<RHData>().OrderBy(c => c.DataFile);
if (existingItem != null)
{
foreach (var _item in existingItem)
{
var item = new RHViewModel()
{
DataFile = _item.DataFile
};
items.Add(item);
var uri = new Uri(fileLocation);
var downloader = new BackgroundDownloader();
StorageFolder library = await installedLocation.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
StorageFolder pdf = await library.CreateFolderAsync(item.DataFile.ToString(), CreationCollisionOption.OpenIfExists);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
StorageFile file = await pdf.CreateFileAsync(filename,
CreationCollisionOption.ReplaceExisting);
DownloadOperation download = downloader.CreateDownload(uri, file);
await StartDownloadAsync(download);
}
}
}
}
BukuAudio Class:
class BukuAudio
{
public string SKU { get; set; }
public string Judul { get; set; }
public string Deskripsi { get; set; }
public string Tipe { get; set; }
public string NamaTipe { get; set; }
public string Harga { get; set; }
public string Cover { get; set; }
public string File { get; set; }
public string Gratis { get; set; }
public string Tanggal { get; set; }
public string DataFile { get; set; }
public JsonArray Bundle_file { get; set; }
public List<string> BundleName { get; set; }
public List<string> BundlePath { get; set; }
}
How to handle it?
Note:
First Bundle File downloaded in the folder "bundle.24b"
Second Bundle file downloaded files in the folder "bundle.23b"
Third Bundle downloaded file in the folder "bundle.22b
Supposedly the file name "bundle.24b ....." downloaded in folder bundle.24b, the file name "bundle.23b ....." downloaded in folder bundle.23b, the file name "bundle.22b ....." downloaded in folder bundle.22b

c# get custom attribute value by class name and method name

I Create Class named RoleController.cs :
[Dynaphore(Id=2)]
[Dynaphore(Name="Role Module")]
[Dynaphore(Description="Role will Control Capability of user")]
public class RoleController : BaseController
{
[Dynaphore(Id = 20)]
[Dynaphore(Name = "List of Role")]
[Dynaphore(Description = "Show all role in list")]
public ActionResult Index()
{
return View();
}
[Dynaphore(Id = 21)]
[Dynaphore(Name = "Role Editor")]
[Dynaphore(Description = "Edit Role")]
public ActionResult Editor(Guid? id)
{
var role = dbIntegrated.Roles.Where(p => p.Id == id).FirstOrDefault();
if (role == null)
{
var cons = AccessLogic.GetAllCapabilities();
List<VMRoleCapabilityItem> model = new List<VMRoleCapabilityItem>();
foreach (var c in cons)
{
foreach (var a in c.Actions)
{
VMRoleCapabilityItem domain = new VMRoleCapabilityItem();
domain.Controller = c.Controller.Replace("Controller", "");
domain.Action = Util.PrettySplitter(a);
domain.IsActive = false;
VMRoleCapabilityItem result = new VMRoleCapabilityItem();
result = domain;
model.Add(domain);
}
}
return View(model);
}
else
{
var cons = AccessLogic.GetAllCapabilities();
List<VMRoleCapabilityItem> model = new List<VMRoleCapabilityItem>();
foreach (var c in cons)
{
foreach (var a in c.Actions)
{
VMRoleCapabilityItem domain = new VMRoleCapabilityItem();
domain.Controller = c.Controller.Replace("Controller", "");
domain.Action = Util.PrettySplitter(a);
var rc = dbIntegrated.RoleCapabilities
.Where(p => p.Controller == c.Controller)
.Where(p => p.Action == a)
.FirstOrDefault();
if (rc != null) domain.IsActive = true;
else domain.IsActive = false;
model.Add(domain);
}
}
return View(model);
}
}
[Dynaphore(Id = 22)]
[Dynaphore(Name = "Save Role")]
[Dynaphore(Description = "Save a role")]
public ActionResult Save(VMCapabilityItem domain)
{
return RedirectToAction("Index");
}
[Dynaphore(Id = 298)]
[Dynaphore(Name = "Soft Delete Role")]
[Dynaphore(Description = "Delete Role from view")]
public ActionResult SoftDelete(Guid id)
{
return Json(new { is_success = true });
}
[Dynaphore(Id = 299)]
[Dynaphore(Name = "Hard Delete Role")]
[Dynaphore(Description = "Delete Role permanently")]
public ActionResult HardDelete(Guid id)
{
return Json(new { is_success = true });
}
}
and this is my custom attribute class :
/// <summary>
///
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DynaphoreAttribute : Attribute
{
/// <summary>
/// String field.
/// </summary>
int _id;
String _name;
String _desc;
/// <summary>
/// Attribute constructor.
/// </summary>
public DynaphoreAttribute()
{
}
/// <summary>
/// Get and set.
/// </summary>
public int Id
{
get { return this._id; }
set { this._id = value; }
}
public String Name
{
get { return this._name; }
set { this._name = value; }
}
public String Description {
get { return this._desc; }
set { this._desc = value; }
}
}
How to get Id, Name and Description of class and method by class name and method name?
i create two methods for it.
first to get class id :
public static int GetDynaphoreClassId(String className)
{
return 0;
}
second, get method id
public static int GetDynaphoreMethodId(String className, String methodName)
{
return 0;
}
how to solve this problem?

Categories

Resources