Skip to content

Instantly share code, notes, and snippets.

@ANRCorleone
Last active April 12, 2017 06:01
Show Gist options
  • Save ANRCorleone/d4ef8c86f993bc4ff6bad2ab0ff1ed18 to your computer and use it in GitHub Desktop.
Save ANRCorleone/d4ef8c86f993bc4ff6bad2ab0ff1ed18 to your computer and use it in GitHub Desktop.
Some of my C# code snippets from our team project - Project Billion
//Use on reflection, works on nested properties too
public static object GetPropertyValue(object obj, string propertyName)
{
var names = propertyName.Split('.');
foreach (var item in names)
{
var propInfo = obj?.GetType().GetProperty(item);
obj = propInfo?.GetValue(obj);
}
return obj;
}
//Use to Map a collection..depends on Omu.ValueInjecter :)
public static ICollection<TDest> InjectFrom<TSource, TDest>(this ICollection<TDest> dest, IEnumerable<TSource> source) where TDest : new()
{
foreach (var item in source)
{
var target = new TDest();
target.InjectFrom(item);
dest.Add(target);
}
return dest;
}
//Use to save a file/files to the server ,with a provided accepted extensions.
public static IEnumerable<string> SaveFiles(HttpFileCollectionBase files,
IEnumerable<string> extensions, string virtualPath)
{
if (files?.Count < 1 || extensions?.Count() < 1 || !virtualPath.StartsWith("~/"))
{
throw new ArgumentException("Please make sure the arguments passed are correct");
}
var acceptedExtensions = new List<string>();
var directory = HttpContext.Current.Server.MapPath(virtualPath);
var filePaths = new List<string>();
extensions.ForEachT(item => acceptedExtensions.Add(item.ToLower()));
Directory.CreateDirectory(directory);
for (int i = 0, length = files.Count; i < length; i++)
{
var file = files[i];
var extension = Path.GetExtension(file.FileName);
if (!acceptedExtensions.Contains(extension.ToLower()))
{
break;
}
else
{
var newName = FileUtil.GetNewFileName(file.FileName);
var physicalPath = Path.Combine(directory, newName);
file.SaveAs(physicalPath);
filePaths.Add(virtualPath + newName);
}
}
return filePaths;
}
}
public class LibraryController : BillionAreasControllerBase<Library, LibraryEditViewModel,
LibraryEditViewModel, LibraryEditViewModel, LibraryListViewModel>
{
IBillionService<Library> _libraryService;
IBillionService<LibraryType> _libraryTypeService;
IEnumerable<LibraryType> _libraryTypes;
public LibraryController(
IBillionService<Library> libraryService,
IBillionService<LibraryType> libraryTypeService,
IValidationService<Library> validationService,
IUserAppContext userApplicationContext) :
base(userApplicationContext,
libraryService,
validationService)
{
_libraryService = libraryService;
_libraryTypeService = libraryTypeService;
_libraryTypes = _libraryTypeService.GetAll().ToList();
}
public override ActionResult Index()
{
return View();
}
[ChildActionOnly]
public override ActionResult Search()
{
var libraries = _libraryService.GetAll()
.Where(x => !x.IsDeleted)
.AsEnumerable();
var model = libraries.MapPagedItems<Library, LibraryListViewModel>(MapEntityToListModel);
return PartialView(model);
}
public override ActionResult Edit(int id)
{
return View("Form", base.GetEditModel(id));
}
[HttpPost]
public override ActionResult Edit(int id, LibraryEditViewModel model)
{
var uploadResult = SaveUpload();
if (uploadResult.Count() > 0)
{
model.ThumbnailUrl = Url.Content(uploadResult.Single());
}
if (model.Id == 0)
{
return Create(model);
}
else
{
return base.Edit(id, model);
}
}
public override ActionResult Create()
{
return View("Form", base.GetCreateModel());
}
[HttpPost]
public override ActionResult Create(LibraryEditViewModel model)
{
//Should come from UserId.Hard-coded for now
model.OrgId = 5;
return base.Create(model);
}
[HttpPost]
public override ActionResult Delete(int id)
{
var library = _libraryService.GetById(id);
if (library == null)
{
return HttpNotFound("Can't find this library");
}
else
{
library.IsDeleted = true;
_libraryService.Edit(library);
_libraryService.Save();
return Json(id);
}
}
protected override void MapEntityToEditModel(Library entity, LibraryEditViewModel editModel)
{
base.MapEntityToEditModel(entity, editModel);
editModel.LibraryTypes = _libraryTypes;
}
protected override void MapEntityToCreateModel(Library entity, LibraryEditViewModel createModel)
{
base.MapEntityToCreateModel(entity, createModel);
createModel.LibraryTypes = _libraryTypes;
}
protected override void MapEntityToListModel(Library entity, LibraryListViewModel listModel)
{
base.MapEntityToListModel(entity, listModel);
listModel.LibraryType = entity.LibraryType.Name;
}
public ActionResult UploadThumbnail(int id)
{
var uploadResult = SaveUpload();
var status = false;
if (uploadResult.Count() > 0)
{
var library = _libraryService.GetById(id);
library.ThumbnailUrl = Url.Content(uploadResult.Single());
_libraryService.Save();
status = true;
}
return Json(new { Success = status });
}
private IEnumerable<string> SaveUpload()
{
var photos = Request.Files;
string[] extensions = { ".jpg", ".jpeg", ".png", ".gif" };
var path = "~/Images/";
return FileService.SaveFiles(photos, extensions, path);
}
}
public class QuestionListViewModel
{
[DisplayName("Question Id")]
public int Id { get; set; }
[DisplayName("Library")]
public string Library { get; set; }
[DisplayName("Asked By")]
public string CreatedBy { get; set; }
}
public class QuestionEntryModel
{
public QuestionEntryModel()
{
QuestionAnswers = new Collection<QuestionAnswerViewModel>();
}
public int Id { get; set; }
[AllowHtml]
public string Description { get; set; }
public int LibraryId { get; set; }
[DisplayName("Library")]
public List<SelectListItem> LibraryDropDownList { get; set; }
[DisplayName("Multiple Answer")]
public bool IsMultipleAnswer { get; set; }
public ICollection<QuestionAnswerViewModel> QuestionAnswers { get; set; }
public QuestionAnswerViewModel AddedAnswer { get; set; }
public void CreateAnswer()
{
var answer = new QuestionAnswerViewModel
{
Id = 0,
QuestionId = Id,
Answer = "",
IsCorrect = false
};
AddedAnswer = answer;
}
public void UpdateAnswers(QuestionEntryModel editModel, Question entity)
{
var addedAnswer = new QuestionAnswer();
addedAnswer.InjectThis(editModel.AddedAnswer);
entity.QuestionAnswers.Add(addedAnswer);
foreach (var answer in editModel.QuestionAnswers)
{
var oldAnswer = entity.QuestionAnswers.FirstOrDefault(a => a.Id == answer.Id);
oldAnswer?.InjectThis(answer);
if (oldAnswer == null)
{
var newAnswer = new QuestionAnswer();
newAnswer.InjectThis(answer);
entity.QuestionAnswers.Add(newAnswer);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment