Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Forked from linuxbender/ByteInfoAttribute.cs
Created September 25, 2017 01:34
Show Gist options
  • Save LSTANCZYK/eb2df335db880f4b4da1864d50896fe9 to your computer and use it in GitHub Desktop.
Save LSTANCZYK/eb2df335db880f4b4da1864d50896fe9 to your computer and use it in GitHub Desktop.
EF 4.2 - MVC 3 - File Validation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace demo_002.Models
{
public class ByteInfoAttribute : ValidationAttribute
{
// Todo from the web config - set default value
// on the EF model : [ByteInfo (MaxContentSize = 2)]
public int MaxContentSize = 10; // as MB
public override bool IsValid(object value)
{
var binaryInfo = value as byte[];
if (binaryInfo == null)
{
return true; // default is true
}
if (binaryInfo.Length > ((MaxContentSize / 1024) / 1024))
{
ErrorMessage = String.Format("Maximum sind : {0} MB erlaubt", MaxContentSize);
return false;
}
return base.IsValid(value);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace demo_002.Models
{
public class CheckFileInfoAttribute : ValidationAttribute
{
public string[] CheckFileExtensions;
public string[] CheckContentTypes;
public override bool IsValid(object value)
{
var fileInfo = value as string;
if (fileInfo == null)
{
return true; // default is true
}
if (CheckFileExtensions != null)
{
if (!CheckFileExtensions.Contains(fileInfo))
{
ErrorMessage = String.Format("Folgende Formate sind erlaubt : ", string.Join(", ", CheckFileExtensions));
return false;
}
}
if (CheckContentTypes != null)
{
if (!CheckContentTypes.Contains(fileInfo))
{
ErrorMessage = String.Format("Folgende MIME-Typen sind erlaubt : ", string.Join(", ", CheckContentTypes));
return false;
}
}
return base.IsValid(value);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace demo_002.Models
{
public class tblProfile
{
public int Id { get; set; }
public string Name { get; set; }
public string Vorname { get; set; }
[ByteInfo(MaxContentSize = 2)]
public byte[] Bild { get; set; }
[CheckFileInfo(CheckFileExtensions = new string[]{ ".jepg", ".jpg", ".png"})]
public string BildEndung { get; set; }
[CheckFileInfo(CheckContentTypes = new string[]{"image/jpeg","image/png"})]
public string BildType { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment