Senro.AspNetCore.Tools
1.16.3
See the version list below for details.
dotnet add package Senro.AspNetCore.Tools --version 1.16.3
NuGet\Install-Package Senro.AspNetCore.Tools -Version 1.16.3
<PackageReference Include="Senro.AspNetCore.Tools" Version="1.16.3" />
<PackageVersion Include="Senro.AspNetCore.Tools" Version="1.16.3" />
<PackageReference Include="Senro.AspNetCore.Tools" />
paket add Senro.AspNetCore.Tools --version 1.16.3
#r "nuget: Senro.AspNetCore.Tools, 1.16.3"
#:package Senro.AspNetCore.Tools@1.16.3
#addin nuget:?package=Senro.AspNetCore.Tools&version=1.16.3
#tool nuget:?package=Senro.AspNetCore.Tools&version=1.16.3
Senro.AspNetCore.Tools
مجموعه کاملی از ابزارهای کاربردی برای توسعه پروژههای ASP.NET Core که توسط امیرحسین خلیفه توسعه داده شده است.
📋 نمای کلی
Senro.AspNetCore.Tools یک کتابخانه NuGet جامع است که شامل ابزارهای ضروری برای توسعه سریع و ایمن برنامههای ASP.NET Core میباشد. این کتابخانه شامل Extension Methods، سرویسهای آماده، و ابزارهای کمکی متنباز است.
✨ ویژگیها
🔧 Extension Methods
- String Extensions: عملیات پیشرفته روی رشتهها، تصحیح حروف فارسی، مقایسه تشابه، تولید کلید و رمز
- DateTime Extensions: عملیات پیشرفته روی تاریخ و زمان
- Number Extensions: عملیات ریاضی پیشرفته
- File Extensions: عملیات پیشرفته روی فایلها
- Enum Extensions: کار با enumها و localization
- Generic Extensions: عملیات عمومی روی اشیاء
- Hash Extensions: عملیات هش و رمزنگاری
- JWT Extensions: کار با توکنهای JWT
- XML Extensions: عملیات روی فایلهای XML
- Validation Extensions: اعتبارسنجی پیشرفته
- Two-Factor Authentication Extensions: احراز هویت دو مرحلهای
🚀 سرویسهای آماده
- Excel Service: خواندن و نوشتن فایلهای Excel
- LDAP Service: اتصال و کار با Active Directory
- Data Protector Service: رمزنگاری و رمزگشایی دادهها
- Captcha Service: تولید کپچای تصویری
- Sitemap Service: تولید نقشه سایت XML
🛠️ ابزارهای کمکی
- JWT Helper: تولید و اعتبارسنجی توکنهای JWT
- Hash Helper: عملیات هش (MD5, SHA256, SHA512)
- QR Code Helper: تولید کد QR
- TOTP Helper: احراز هویت دو مرحلهای مبتنی بر زمان
- Dependency Injection Helper: مدیریت سرویسهای DI
📦 نصب
از طریق NuGet Package Manager
Install-Package Senro.AspNetCore.Tools -Version 1.16.2
از طریق .NET CLI
dotnet add package Senro.AspNetCore.Tools --version 1.16.2
از طریق Package Reference
<PackageReference Include="Senro.AspNetCore.Tools" Version="1.16.2" />
⚙️ تنظیمات اولیه
۱. اضافه کردن سرویسها در Program.cs
using Senro.AspNetCore.Tools;
var builder = WebApplication.CreateBuilder(args);
// اضافه کردن سرویسهای پایه
builder.Services.AddSenroServices();
// اضافه کردن سرویسهای مدیریت وابستگی (اختیاری)
builder.Services.AddSenroServiceHandler();
// تنظیمات JWT (اختیاری)
SenroConfig.JwtKey = Encoding.UTF8.GetBytes("your-jwt-secret-key-here");
SenroConfig.JwtIssuer = "your-issuer";
SenroConfig.JwtDecryptionKey = Encoding.UTF8.GetBytes("your-decryption-key");
// تنظیمات رمزنگاری (اختیاری)
SenroConfig.EncriptKey = "your-encryption-key";
var app = builder.Build();
۲. اضافه کردن Middlewareها (اختیاری)
// برای استفاده از HttpContext Extensions
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
📖 نحوه استفاده
🔧 Extension Methods
String Extensions
Integration() - پاکسازی متن
using Senro.AspNetCore.Tools.Extentions;
string text = "متن تست-برای پاکسازی_و مقایسه";
string cleaned = text.Integration(); // "متنتستبرایپاکسازیومقایسه"
// با تعیین کاراکتر جایگزین
string withSpaces = text.Integration(" "); // "متن تست برای پاکسازی و مقایسه"
// با حذف کاراکترهای خاص اضافی
string customClean = text.Integration("", "-", "_", "/"); // حذف خط تیره، زیرخط و اسلش
FixPersianChars() - تصحیح حروف عربی به فارسی
string arabicText = "كتاب ي است";
string persianText = arabicText.FixPersianChars(); // "کتاب ی است"
// مثالهای دیگر
"ﮎ".FixPersianChars(); // "ک"
"ﮏ".FixPersianChars(); // "ک"
"ي".FixPersianChars(); // "ی"
GetComparisonPercentage() - مقایسه تشابه دو متن
int similarity1 = "hello world".GetComparisonPercentage("helo word"); // ۸۰
int similarity2 = "test".GetComparisonPercentage("test"); // ۱۰۰
int similarity3 = "abc".GetComparisonPercentage("xyz"); // ۰
// کاربرد در جستجو هوشمند
if (userInput.GetComparisonPercentage(databaseValue) > 70)
{
// مطابقت خوب
}
CalcLevenshteinDistance() - محاسبه فاصله ویرایشی
int distance1 = StringExtensions.CalcLevenshteinDistance("kitten", "sitting"); // ۳
int distance2 = StringExtensions.CalcLevenshteinDistance("book", "back"); // ۲
int distance3 = StringExtensions.CalcLevenshteinDistance("test", "test"); // ۰
GenerateSecretKey() - تولید کلید رندم برای Base32
string key16 = StringExtensions.GenerateSecretKey(16); // ۱۶ کاراکتر
string key32 = StringExtensions.GenerateSecretKey(32); // ۳۲ کاراکتر
string key10 = StringExtensions.GenerateSecretKey(); // ۱۰ کاراکتر (پیشفرض)
// برای 2FA
string totpSecret = StringExtensions.GenerateSecretKey(32);
GeneratePassword() - تولید رمز عبور امن
string pass1 = StringExtensions.GeneratePassword(8, 1); // ۸ کاراکتر، ۱ کاراکتر خاص
string pass2 = StringExtensions.GeneratePassword(12, 3); // ۱۲ کاراکتر، ۳ کاراکتر خاص
string pass3 = StringExtensions.GeneratePassword(); // ۱۰ کاراکتر، ۲ کاراکتر خاص (پیشفرض)
// نمونه خروجی: "Ab3XyZ9#mNp2@"
ToCamelCase() - تبدیل به فرمت CamelCase
"user_name_field".ToCamelCase(); // "userNameField"
"product_category_name".ToCamelCase(); // "productCategoryName"
"API_KEY".ToCamelCase(); // "apiKey"
CustomIntersect() - مقایسه رشتهها
// مقایسه دو لیست رشته
List<string> list1 = new() { "a", "b", "c" };
List<string> list2 = new() { "b", "c", "d" };
List<string> common = list1.CustomIntersect(list2); // ["b", "c"]
// مقایسه کاراکترهای دو رشته
List<char> commonChars = "hello".CustomIntersect("world"); // ['l', 'o']
DateTime Extensions
ToPersianDateString() - تبدیل به تاریخ شمسی
DateTime dt = new DateTime(2024, 3, 15, 14, 30, 0);
string persianDate = dt.ToPersianDateString(); // "۱۴۰۳/۰۱/۲۵"
// با زمان
string fullDate = $"{dt.ToPersianDateString()} {dt:HH:mm:ss}"; // "۱۴۰۳/۰۱/۲۵ ۱۴:۳۰:۰۰"
AddWeeks() - اضافه کردن هفته
DateTime today = DateTime.Now;
DateTime nextWeek = today.AddWeeks(1);
DateTime twoWeeksAgo = today.AddWeeks(-2);
// کاربرد در برنامهریزی
DateTime deadline = projectStart.AddWeeks(4);
IsWeekend() - بررسی روز تعطیل
DateTime saturday = new DateTime(2024, 3, 16); // شنبه
bool isWeekend1 = saturday.IsWeekend(); // true
DateTime wednesday = new DateTime(2024, 3, 13); // چهارشنبه
bool isWeekend2 = wednesday.IsWeekend(); // false
CalculateAge() - محاسبه سن
DateTime birthDate = new DateTime(1990, 5, 15);
int age = birthDate.CalculateAge(); // ۳۴
// بررسی سن قانونی
if (birthDate.CalculateAge() >= 18)
{
// کاربر بالغ است
}
ToPersian_TimeDifference() - نمایش اختلاف زمانی به فارسی
DateTime pastDate = DateTime.Now.AddHours(-5);
string timeDiff = pastDate.ToPersian_TimeDifference(); // "۵ ساعت قبل"
DateTime yesterday = DateTime.Now.AddDays(-1);
string yesterdayDiff = yesterday.ToPersian_TimeDifference(); // "۱ روز قبل"
DateTime futureDate = DateTime.Now.AddDays(3);
string futureDiff = futureDate.ToPersian_TimeDifference(); // "۳ روز بعد"
// مثالهای دیگر
DateTime lastWeek = DateTime.Now.AddDays(-10);
string weekDiff = lastWeek.ToPersian_TimeDifference(); // "۱۰ روز قبل"
DateTime nextMonth = DateTime.Now.AddMonths(2);
string monthDiff = nextMonth.ToPersian_TimeDifference(); // "۲ ماه بعد"
DateTime lastYear = DateTime.Now.AddYears(-1);
string yearDiff = lastYear.ToPersian_TimeDifference(); // "۱ سال قبل"
ToPersian_TimeDifferenceDetail() - نمایش اختلاف زمانی دقیق به فارسی
DateTime pastDate = DateTime.Now.AddDays(-5).AddHours(-3).AddMinutes(-30);
string detailedDiff = pastDate.ToPersian_TimeDifferenceDetail();
// خروجی: "۵ روز و ۳ ساعت و ۳۰ دقیقه قبل"
// مثالهای دیگر
DateTime futureDate = DateTime.Now.AddMonths(1).AddDays(5);
string futureDetailed = futureDate.ToPersian_TimeDifferenceDetail();
// خروجی: "۱ ماه و ۵ روز بعد"
Number Extensions
ToPersianNumber() - تبدیل اعداد به فارسی
string persian1 = 123.ToPersianNumber(); // "۱۲۳"
string persian2 = 456789.ToPersianNumber(); // "۴۵۶۷۸۹"
string persian3 = 0.ToPersianNumber(); // "۰"
// کاربرد در UI
decimal price = 150000;
string displayPrice = $"{price.ToPersianNumber()} تومان"; // "۱۵۰۰۰۰ تومان"
ToEnglishNumber() - تبدیل اعداد فارسی به انگلیسی
string english1 = "۱۲۳".ToEnglishNumber(); // "123"
string english2 = "۴۵۶".ToEnglishNumber(); // "456"
string english3 = "۰۰۰".ToEnglishNumber(); // "000"
// کاربرد در پردازش ورودی کاربر
int userInput = int.Parse(userInputString.ToEnglishNumber());
CalculatePercentage() - محاسبه درصد
decimal result1 = 1000.CalculatePercentage(10); // ۱۰۰
decimal result2 = 500.CalculatePercentage(25); // ۱۲۵
decimal result3 = 200.CalculatePercentage(150); // ۳۰۰
// کاربرد در تخفیف
decimal discount = originalPrice.CalculatePercentage(discountPercent);
decimal finalPrice = originalPrice - discount;
IsEven() - بررسی عدد زوج
bool even1 = 10.IsEven(); // true
bool even2 = 15.IsEven(); // false
bool even3 = 0.IsEven(); // true
// کاربرد در حلقهها
for (int i = 0; i < count; i++)
{
if (i.IsEven())
{
// پردازش عناصر زوج
}
}
File Extensions
GetMimeType() - دریافت نوع MIME فایل
// در Controller
[HttpPost("upload")]
public IActionResult UploadFile(IFormFile file)
{
string mimeType = file.GetMimeType();
if (mimeType.StartsWith("image/"))
{
// فایل تصویر است
}
else if (mimeType == "application/pdf")
{
// فایل PDF است
}
return Ok(new { MimeType = mimeType });
}
GetFileExtension() - دریافت پسوند فایل
string ext1 = file.GetFileExtension(); // ".jpg"
string ext2 = Path.GetFileName("document.pdf").GetFileExtension(); // ".pdf"
// بررسی پسوند امن
string[] allowedExtensions = { ".jpg", ".png", ".pdf" };
if (allowedExtensions.Contains(file.GetFileExtension().ToLower()))
{
// پسوند مجاز است
}
IsImage() - بررسی فایل تصویر
bool isImage1 = uploadedFile.IsImage(); // true برای jpg, png, gif و...
// کاربرد در validation
if (!file.IsImage())
{
return BadRequest("فقط فایلهای تصویری مجاز هستند");
}
Enum Extensions
GetDisplayName() - دریافت نام نمایشی enum
public enum Status
{
[Display(Name = "فعال")]
Active,
[Display(Name = "غیرفعال")]
Inactive,
[Display(Name = "در انتظار")]
Pending
}
string display1 = Status.Active.GetDisplayName(); // "فعال"
string display2 = Status.Pending.GetDisplayName(); // "در انتظار"
ToSelectList() - تبدیل enum به SelectList
// در Controller
public IActionResult GetStatusOptions()
{
var options = Status.Active.ToSelectList();
return Ok(options);
}
// خروجی JSON:
[
{ "value": 0, "text": "فعال" },
{ "value": 1, "text": "غیرفعال" },
{ "value": 2, "text": "در انتظار" }
]
Generic Extensions
CreateInstance<T>() - ایجاد نمونه از نوع
// ایجاد نمونه از کلاس
User newUser = GenericExtensions.CreateInstance<User>();
// ایجاد نمونه با پارامتر
var instance = typeof(MyClass).CreateInstance<MyClass>();
GetDisplayName() - دریافت نام نمایشی property
public class User
{
[Display(Name = "شناسه کاربر")]
public int Id { get; set; }
[Display(Name = "نام و نام خانوادگی")]
public string FullName { get; set; }
}
var property = typeof(User).GetProperty("FullName");
string displayName = property.GetDisplayName(); // "نام و نام خانوادگی"
GetChildren<T>() - دریافت فرزندان interface
// یافتن تمام کلاسهایی که از یک interface ارث بردهاند
var services = typeof(IService).GetChildren<IService>();
foreach (var serviceType in services)
{
// ثبت خودکار سرویسها
builder.Services.AddScoped(serviceType);
}
Hash Extensions
ToMD5() - هش MD5
string hash1 = "password".ToMD5(); // هش MD5
string hash2 = "123456".ToMD5(); // هش MD5
// هش فایل
string fileContent = File.ReadAllText("file.txt");
string fileHash = fileContent.ToMD5();
ToSHA256() - هش SHA256
string hash1 = "password".ToSHA256(); // هش SHA256 امنتر
string hash2 = "sensitive-data".ToSHA256();
// هش ایمن برای ذخیره رمز عبور
string secureHash = userPassword.ToSHA256();
ToSHA512() - هش SHA512
string hash1 = "password".ToSHA512(); // هش SHA512 بسیار امن
string hash2 = "critical-data".ToSHA512();
// برای دادههای بسیار حساس
string bankHash = accountData.ToSHA512();
JWT Extensions
GenerateJwtToken() - تولید توکن JWT
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Role, user.Role),
new Claim(JwtRegisteredClaimNames.Iss, SenroConfig.JwtIssuer),
new Claim(JwtRegisteredClaimNames.Aud, "my-app")
};
string token = claims.GenerateJwtToken(
key: SenroConfig.JwtKey,
issuer: SenroConfig.JwtIssuer,
expires: DateTime.UtcNow.AddHours(1)
);
ValidateJwtToken() - اعتبارسنجی توکن JWT
try
{
var principal = token.ValidateJwtToken(
key: SenroConfig.JwtKey,
issuer: SenroConfig.JwtIssuer
);
if (principal != null)
{
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var username = principal.FindFirst(ClaimTypes.Name)?.Value;
// توکن معتبر است
}
}
catch (SecurityTokenException)
{
// توکن نامعتبر
}
XML Extensions
ToXmlString<T>() - تبدیل شیء به XML
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
var person = new Person { Name = "علی", Age = 25, Email = "ali@example.com" };
string xml = person.ToXmlString();
// خروجی XML:
// <Person>
// <Name>علی</Name>
// <Age>25</Age>
// <Email>ali@example.com</Email>
// </Person>
FromXmlString<T>() - تبدیل XML به شیء
string xml = @"<Person>
<Name>مریم</Name>
<Age>30</Age>
<Email>maryam@example.com</Email>
</Person>";
var person = xml.FromXmlString<Person>();
// person.Name = "مریم"
// person.Age = 30
Validation Extensions
IsValidEmail() - اعتبارسنجی ایمیل
bool valid1 = "user@example.com".IsValidEmail(); // true
bool valid2 = "invalid-email".IsValidEmail(); // false
bool valid3 = "user@.com".IsValidEmail(); // false
// کاربرد در registration
if (!email.IsValidEmail())
{
return BadRequest("ایمیل وارد شده معتبر نیست");
}
IsValidPhoneNumber() - اعتبارسنجی شماره تلفن
bool valid1 = "09123456789".IsValidPhoneNumber(); // true (ایران)
bool valid2 = "+989123456789".IsValidPhoneNumber(); // true
bool valid3 = "12345".IsValidPhoneNumber(); // false
// کاربرد در فرمها
if (!phone.IsValidPhoneNumber())
{
ModelState.AddModelError("Phone", "شماره تلفن معتبر نیست");
}
Two-Factor Authentication Extensions
GenerateTOTP() - تولید کد TOTP
string secretKey = StringExtensions.GenerateSecretKey(32);
string currentCode = secretKey.GenerateTOTP(); // کد ۶ رقمی فعلی
// ارسال به کاربر یا نمایش
return Ok(new { Code = currentCode, ExpiresIn = 30 }); // ۳۰ ثانیه اعتبار دارد
ValidateTOTP() - اعتبارسنجی کد TOTP
string userCode = "123456"; // کد وارد شده توسط کاربر
bool isValid = secretKey.ValidateTOTP(userCode);
// با تحمل زمانی
bool isValidWithTolerance = secretKey.ValidateTOTP(userCode, 2); // ±۲ دقیقه
if (isValid)
{
// احراز هویت موفق
return Ok("ورود با موفقیت انجام شد");
}
GenerateQRCode() - تولید کد QR
string totpUrl = $"otpauth://totp/MyApp:{username}?secret={secretKey}&issuer=MyApp";
string qrCodeBase64 = totpUrl.GenerateQRCode();
// نمایش در view
<img src="data:image/png;base64,@qrCodeBase64" alt="QR Code" />
HttpContext Extensions
GetIP() - دریافت آدرس IP کاربر
// در Controller یا Middleware
string userIP = HttpContext.GetIP();
// ذخیره IP برای لاگ
_logger.LogInformation($"Request from IP: {userIP}");
// کاربرد در security
if (IsBlockedIP(userIP))
{
return Forbid();
}
GetUserAgent() - دریافت User Agent
string userAgent = HttpContext.GetUserAgent();
// تشخیص دستگاه
if (userAgent.Contains("Mobile"))
{
// کاربر موبایل دارد
}
else if (userAgent.Contains("Chrome"))
{
// مرورگر Chrome
}
🚀 سرویسها (Services)
Excel Service
IExcelService - رابط سرویس Excel
سرویس کار با فایلهای Excel با استفاده از کتابخانه ClosedXML.
متدهای IExcelService
ToExcel<T>(IEnumerable<T> objs, string sheetName = "data") - تبدیل به Excel
تبدیل لیست اشیاء به فایل Excel.
پارامترها:
objs: لیست اشیاء برای تبدیلsheetName: نام شیت (پیشفرض: "data")
نوع بازگشتی: byte[] - بایتهای فایل Excel
مثال:
using Senro.AspNetCore.Tools.Services.Excel;
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
[ApiController]
[Route("api/[controller]")]
public class ExcelController : ControllerBase
{
private readonly IExcelService _excelService;
public ExcelController(IExcelService excelService)
{
_excelService = excelService;
}
[HttpGet("export")]
public IActionResult ExportUsers()
{
var users = new List<User>
{
new User { Name = "علی", Age = 25, Email = "ali@example.com" },
new User { Name = "مریم", Age = 30, Email = "maryam@example.com" }
};
byte[] excelBytes = _excelService.ToExcel(users, "Users");
return File(excelBytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"users.xlsx");
}
}
FromExcel<T>(string file) - خواندن از مسیر فایل
خواندن دادهها از فایل Excel موجود در مسیر.
پارامترها:
file: مسیر فایل Excel
نوع بازگشتی: IEnumerable<T> - لیست اشیاء خوانده شده
مثال:
[HttpPost("import-from-path")]
public IActionResult ImportFromPath(string filePath)
{
try
{
var users = _excelService.FromExcel<User>(filePath);
return Ok(new { Count = users.Count(), Users = users });
}
catch (Exception ex)
{
return BadRequest($"خطا در خواندن فایل: {ex.Message}");
}
}
FromExcel<T>(Stream file) - خواندن از Stream
خواندن دادهها از Stream فایل Excel.
پارامترها:
file: Stream فایل Excel
نوع بازگشتی: IEnumerable<T> - لیست اشیاء خوانده شده
مثال:
[HttpPost("import-from-stream")]
public IActionResult ImportFromStream(IFormFile file)
{
using var stream = file.OpenReadStream();
var users = _excelService.FromExcel<User>(stream);
return Ok(users);
}
FromExcel<T>(IFormFile file) - خواندن از IFormFile
خواندن دادهها از فایل آپلود شده ASP.NET Core.
پارامترها:
file: فایل آپلود شده
نوع بازگشتی: IEnumerable<T> - لیست اشیاء خوانده شده
مثال:
[HttpPost("import-users")]
public IActionResult ImportUsers(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("فایل انتخاب نشده است");
if (!file.FileName.EndsWith(".xlsx") && !file.FileName.EndsWith(".xls"))
return BadRequest("فرمت فایل باید Excel باشد");
try
{
var users = _excelService.FromExcel<User>(file);
var validUsers = users.Where(u => !string.IsNullOrEmpty(u.Name)).ToList();
return Ok(new {
TotalRecords = users.Count(),
ValidRecords = validUsers.Count,
Users = validUsers
});
}
catch (Exception ex)
{
return BadRequest($"خطا در پردازش فایل Excel: {ex.Message}");
}
}
FromExcel<T>(LoadOptions loadOptions) - خواندن با تنظیمات پیشرفته
خواندن دادهها با تنظیمات پیشرفته بارگذاری.
پارامترها:
loadOptions: تنظیمات بارگذاری
نوع بازگشتی: IEnumerable<T> - لیست اشیاء خوانده شده
FromExcel<T>(Stream stream, LoadOptions loadOptions) - خواندن Stream با تنظیمات
خواندن از Stream با تنظیمات پیشرفته.
FromExcel<T>(string file, LoadOptions loadOptions) - خواندن فایل با تنظیمات
خواندن از مسیر فایل با تنظیمات پیشرفته.
FromExcel<T>(XLWorkbook workbook) - خواندن از Workbook
خواندن مستقیم از شیء XLWorkbook.
SampleForImport<T>() - تولید نمونه فایل
تولید فایل Excel نمونه برای ایمپورت.
نوع بازگشتی: byte[] - بایتهای فایل نمونه
مثال:
[HttpGet("sample-excel")]
public IActionResult GetSampleExcel()
{
var sampleData = new List<User>
{
new User { Name = "نام نمونه", Age = 0, Email = "sample@example.com" }
};
byte[] sampleBytes = _excelService.SampleForImport(sampleData);
return File(sampleBytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"sample_users.xlsx");
}
SampleForImport<T>(IEnumerable<T> objs) - تولید نمونه با داده
تولید فایل Excel نمونه با دادههای مشخص.
پارامترها:
objs: لیست اشیاء نمونه
نوع بازگشتی: byte[] - بایتهای فایل نمونه
LDAP Service
ILDAPService - رابط سرویس LDAP
سرویس اتصال و کار با Active Directory.
متدهای ILDAPService
GetUsers() - دریافت کاربران پایه
دریافت لیست کاربران از Active Directory.
پارامترها:
ldapAddress: آدرس سرور LDAP (مثال: "domain.local")userName: نام کاربری ادمینpassword: رمز عبور ادمین
نوع بازگشتی: IEnumerable<LDAPUserDto> - لیست کاربران
مثال:
using Senro.AspNetCore.Tools.Services.LDAP;
[ApiController]
[Route("api/[controller]")]
public class LdapController : ControllerBase
{
private readonly ILDAPService _ldapService;
public LdapController(ILDAPService ldapService)
{
_ldapService = ldapService;
}
[HttpGet("users")]
public IActionResult GetUsers()
{
try
{
var users = _ldapService.GetUsers(
ldapAddress: "company.local",
userName: "admin@company.local",
password: "AdminPass123"
);
return Ok(users);
}
catch (Exception ex)
{
return BadRequest($"خطا در اتصال به LDAP: {ex.Message}");
}
}
}
GetUsers<T>() - دریافت کاربران با نوع سفارشی
دریافت کاربران با تبدیل به نوع سفارشی.
پارامترها:
ldapAddress: آدرس سرور LDAPuserName: نام کاربری ادمینpassword: رمز عبور ادمین
نوع بازگشتی: List<T> - لیست اشیاء از نوع سفارشی
مثال:
// تعریف کلاس سفارشی با LDAPInfo attribute
[LDAPInfo]
public class CustomUser
{
[LDAPInfo(Name = "samAccountName")]
public string Username { get; set; }
[LDAPInfo(Name = "givenName")]
public string FirstName { get; set; }
[LDAPInfo(Name = "sn")]
public string LastName { get; set; }
[LDAPInfo(Name = "mail")]
public string Email { get; set; }
[LDAPInfo(Name = "department")]
public string Department { get; set; }
[LDAPInfo(Name = "title")]
public string Position { get; set; }
[LDAPInfo(Name = "telephoneNumber")]
public string Phone { get; set; }
[LDAPInfo(Name = "whenCreated")]
public string CreatedDate { get; set; }
}
[HttpGet("custom-users")]
public IActionResult GetCustomUsers()
{
var users = _ldapService.GetUsers<CustomUser>(
ldapAddress: "company.local",
userName: "admin@company.local",
password: "AdminPass123"
);
return Ok(users);
}
ValidateUser() - اعتبارسنجی کاربر
بررسی اعتبار کاربر در Active Directory.
پارامترها:
userLdapAddress: آدرس LDAP کاربرuserName: نام کاربریpassword: رمز عبور
نوع بازگشتی: bool - نتیجه اعتبارسنجی
مثال:
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
bool isValid = _ldapService.ValidateUser(
userLdapAddress: "company.local",
userName: model.Username,
password: model.Password
);
if (isValid)
{
// تولید JWT token
var token = GenerateJwtToken(model.Username);
return Ok(new { Token = token, Message = "ورود موفق" });
}
return Unauthorized("نام کاربری یا رمز عبور اشتباه است");
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
Data Protector Service
IDataProtectorService - رابط سرویس رمزنگاری
سرویس رمزنگاری و رمزگشایی دادهها با استفاده از ASP.NET Core Data Protection.
متدهای IDataProtectorService
Encrypt() - رمزنگاری داده
رمزنگاری رشته به فرمت امن.
پارامترها:
plainText: متن ساده
نوع بازگشتی: string - متن رمزنگاری شده
مثال:
using Senro.AspNetCore.Tools.Services.DataProtector;
[ApiController]
[Route("api/[controller]")]
public class SecurityController : ControllerBase
{
private readonly IDataProtectorService _dataProtector;
public SecurityController(IDataProtectorService dataProtector)
{
_dataProtector = dataProtector;
}
[HttpPost("encrypt")]
public IActionResult EncryptData([FromBody] string plainText)
{
try
{
string encrypted = _dataProtector.Encrypt(plainText);
return Ok(new {
Original = plainText,
Encrypted = encrypted,
Length = encrypted.Length
});
}
catch (Exception ex)
{
return BadRequest($"خطا در رمزنگاری: {ex.Message}");
}
}
}
Decrypt() - رمزگشایی داده
رمزگشایی رشته رمزنگاری شده.
پارامترها:
encryptedText: متن رمزنگاری شده
نوع بازگشتی: string - متن اصلی
مثال:
[HttpPost("decrypt")]
public IActionResult DecryptData([FromBody] string encryptedText)
{
try
{
string decrypted = _dataProtector.Decrypt(encryptedText);
return Ok(new {
Encrypted = encryptedText,
Decrypted = decrypted
});
}
catch (Exception ex)
{
return BadRequest($"خطا در رمزگشایی: {ex.Message}");
}
}
کاربردهای عملی:
// رمزنگاری اطلاعات حساس کاربر
public async Task SaveUserSensitiveData(User user)
{
user.Email = _dataProtector.Encrypt(user.Email);
user.PhoneNumber = _dataProtector.Encrypt(user.PhoneNumber);
user.NationalId = _dataProtector.Encrypt(user.NationalId);
await _context.Users.AddAsync(user);
await _context.SaveChangesAsync();
}
// رمزگشایی برای نمایش
public async Task<User> GetUserWithDecryptedData(int userId)
{
var user = await _context.Users.FindAsync(userId);
user.Email = _dataProtector.Decrypt(user.Email);
user.PhoneNumber = _dataProtector.Decrypt(user.PhoneNumber);
user.NationalId = _dataProtector.Decrypt(user.NationalId);
return user;
}
Captcha Service
ICaptchaService - رابط سرویس کپچا
سرویس تولید کپچای تصویری با استفاده از SixLabors.ImageSharp.
کلاس CaptchaResult
public class CaptchaResult
{
public string Id { get; set; } // شناسه منحصر به فرد کپچا
public string Text { get; set; } // متن کپچا (برای توسعه)
public string ImageBase64 { get; set; } // تصویر Base64
}
متدهای ICaptchaService
GenerateCaptcha() - تولید کپچا
تولید کپچای تصویری جدید.
نوع بازگشتی: CaptchaResult - نتیجه تولید کپچا
مثال:
using Senro.AspNetCore.Tools.Services.Captcha;
[ApiController]
[Route("api/[controller]")]
public class CaptchaController : ControllerBase
{
private readonly ICaptchaService _captchaService;
public CaptchaController(ICaptchaService captchaService)
{
_captchaService = captchaService;
}
[HttpGet("generate")]
public IActionResult GenerateCaptcha()
{
var captcha = _captchaService.GenerateCaptcha();
// ذخیره در Session برای اعتبارسنجی بعدی
HttpContext.Session.SetString("CaptchaId", captcha.Id);
return Ok(new
{
CaptchaId = captcha.Id,
ImageBase64 = captcha.ImageBase64,
// Text فقط برای محیط توسعه
Text = HttpContext.RequestServices
.GetService<IWebHostEnvironment>()?
.IsDevelopment() == true ? captcha.Text : null
});
}
}
ValidateCaptcha() - اعتبارسنجی کپچا
بررسی کد وارد شده توسط کاربر.
پارامترها:
userInput: کد وارد شده توسط کاربرcaptchaId: شناسه کپچا
نوع بازگشتی: bool - نتیجه اعتبارسنجی
مثال:
[HttpPost("validate")]
public IActionResult ValidateCaptcha([FromBody] CaptchaValidationModel model)
{
bool isValid = _captchaService.ValidateCaptcha(model.UserInput, model.CaptchaId);
if (isValid)
{
return Ok(new { Message = "کپچا صحیح است" });
}
return BadRequest(new { Error = "کد کپچا اشتباه است" });
}
[HttpPost("register")]
public IActionResult Register([FromBody] RegisterModel model)
{
// اعتبارسنجی کپچا
bool captchaValid = _captchaService.ValidateCaptcha(model.CaptchaCode, model.CaptchaId);
if (!captchaValid)
{
return BadRequest("کد امنیتی اشتباه است");
}
// ادامه روند ثبت نام...
}
public class CaptchaValidationModel
{
public string UserInput { get; set; }
public string CaptchaId { get; set; }
}
public class RegisterModel
{
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string CaptchaCode { get; set; }
public string CaptchaId { get; set; }
}
Sitemap Service
ISitemapService - رابط سرویس نقشه سایت
سرویس تولید نقشه سایت XML برای موتورهای جستجو.
کلاسهای Sitemap
SitemapUrl
public class SitemapUrl
{
public string Location { get; set; } // URL صفحه
public DateTime? LastModified { get; set; } // تاریخ آخرین تغییر
public SitemapUpdateFrequency? ChangeFrequency { get; set; } // فرکانس بروزرسانی
public double? Priority { get; set; } // اولویت (0.0 تا 1.0)
public List<SitemapImage> Images { get; set; } // تصاویر صفحه
public List<SitemapVideo> Videos { get; set; } // ویدیوهای صفحه
public SitemapNews News { get; set; } // اخبار صفحه
}
SitemapUpdateFrequency
public enum SitemapUpdateFrequency
{
Always,
Hourly,
Daily,
Weekly,
Monthly,
Yearly,
Never
}
متدهای ISitemapService
GenerateSitemap() - تولید نقشه سایت
تولید XML نقشه سایت از لیست URLها.
پارامترها:
urls: لیست URLهای سایت
نوع بازگشتی: string - XML نقشه سایت
مثال:
using Senro.AspNetCore.Tools.Services.Sitemap;
[ApiController]
[Route("api/[controller]")]
public class SitemapController : ControllerBase
{
private readonly ISitemapService _sitemapService;
private readonly IHttpContextAccessor _httpContextAccessor;
public SitemapController(
ISitemapService sitemapService,
IHttpContextAccessor httpContextAccessor)
{
_sitemapService = sitemapService;
_httpContextAccessor = httpContextAccessor;
}
[HttpGet("generate")]
public IActionResult GenerateSitemap()
{
var baseUrl = $"{_httpContextAccessor.HttpContext?.Request.Scheme}://{_httpContextAccessor.HttpContext?.Request.Host}";
var urls = new List<SitemapUrl>
{
new SitemapUrl
{
Location = $"{baseUrl}/",
LastModified = DateTime.UtcNow,
ChangeFrequency = SitemapUpdateFrequency.Weekly,
Priority = 1.0
},
new SitemapUrl
{
Location = $"{baseUrl}/products",
LastModified = DateTime.UtcNow.AddDays(-1),
ChangeFrequency = SitemapUpdateFrequency.Daily,
Priority = 0.8
},
new SitemapUrl
{
Location = $"{baseUrl}/about",
LastModified = DateTime.UtcNow.AddDays(-7),
ChangeFrequency = SitemapUpdateFrequency.Monthly,
Priority = 0.6
},
new SitemapUrl
{
Location = $"{baseUrl}/contact",
LastModified = DateTime.UtcNow.AddDays(-30),
ChangeFrequency = SitemapUpdateFrequency.Yearly,
Priority = 0.4
}
};
string sitemapXml = _sitemapService.GenerateSitemap(urls);
return Content(sitemapXml, "application/xml");
}
[HttpGet("sitemap.xml")]
public IActionResult GetSitemapXml()
{
// تولید خودکار بر اساس دادههای دیتابیس
var urls = GenerateUrlsFromDatabase();
string sitemapXml = _sitemapService.GenerateSitemap(urls);
return Content(sitemapXml, "application/xml");
}
private List<SitemapUrl> GenerateUrlsFromDatabase()
{
var baseUrl = $"{_httpContextAccessor.HttpContext?.Request.Scheme}://{_httpContextAccessor.HttpContext?.Request.Host}";
var urls = new List<SitemapUrl>();
// صفحه اصلی
urls.Add(new SitemapUrl
{
Location = $"{baseUrl}/",
ChangeFrequency = SitemapUpdateFrequency.Weekly,
Priority = 1.0
});
// صفحات محصولات (فرض بر وجود Product entity)
var products = _context.Products.Where(p => p.IsActive).ToList();
foreach (var product in products)
{
urls.Add(new SitemapUrl
{
Location = $"{baseUrl}/products/{product.Id}",
LastModified = product.LastModified,
ChangeFrequency = SitemapUpdateFrequency.Weekly,
Priority = 0.7
});
}
// صفحات اخبار (فرض بر وجود News entity)
var news = _context.News.Where(n => n.IsPublished).ToList();
foreach (var newsItem in news)
{
urls.Add(new SitemapUrl
{
Location = $"{baseUrl}/news/{newsItem.Id}",
LastModified = newsItem.PublishDate,
ChangeFrequency = SitemapUpdateFrequency.Monthly,
Priority = 0.6,
News = new SitemapNews
{
Title = newsItem.Title,
PublicationDate = newsItem.PublishDate,
Name = "My News Site"
}
});
}
return urls;
}
}
Senro Service
ISenroService - سرویس عمومی
سرویس حاوی توابع عمومی کاربردی.
متدهای ISenroService
GenerateGuid() - تولید GUID
تولید GUID جدید.
نوع بازگشتی: string - GUID به فرمت رشته
مثال:
string newId = _senroService.GenerateGuid(); // "550e8400-e29b-41d4-a716-446655440000"
GetCurrentDateTime() - دریافت تاریخ فعلی
دریافت تاریخ و زمان فعلی سرور.
نوع بازگشتی: DateTime - تاریخ فعلی
مثال:
DateTime now = _senroService.GetCurrentDateTime();
// کاربرد: اطمینان از استفاده از زمان سرور به جای زمان کلاینت
CalculateAge() - محاسبه سن
محاسبه سن بر اساس تاریخ تولد.
پارامترها:
birthDate: تاریخ تولد
نوع بازگشتی: int - سن محاسبه شده
مثال:
DateTime birthDate = new DateTime(1990, 5, 15);
int age = _senroService.CalculateAge(birthDate); // ۳۴
🛠️ Helper Classes
JWT Helper
کلاس JwtHelper - ابزارهای توکن JWT
توابع استاتیک برای کار با توکنهای JWT.
متدهای JwtHelper
GenerateToken() - تولید توکن JWT
تولید توکن JWT با پارامترهای مشخص.
پارامترها:
claims: لیست ادعاهای توکنkey: کلید رمزنگاری (باید 256 بیت یا بیشتر باشد)issuer: صادرکننده توکنexpires: تاریخ انقضا
نوع بازگشتی: string - توکن JWT
مثال:
using Senro.AspNetCore.Tools.Helper.DataProtector;
public class AuthHelper
{
public string CreateToken(string username, string role)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Email, $"{username}@example.com"),
new Claim(ClaimTypes.Role, role),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iss, SenroConfig.JwtIssuer),
new Claim(JwtRegisteredClaimNames.Aud, "my-app-audience")
};
return JwtHelper.GenerateToken(
claims: claims,
key: SenroConfig.JwtKey,
issuer: SenroConfig.JwtIssuer,
expires: DateTime.UtcNow.AddHours(2)
);
}
}
ValidateToken() - اعتبارسنجی توکن JWT
بررسی اعتبار توکن و استخراج ClaimsPrincipal.
پارامترها:
token: توکن JWT برای بررسیkey: کلید رمزنگاریissuer: صادرکننده توکنaudience: مخاطب توکن (اختیاری)
نوع بازگشتی: ClaimsPrincipal - اطلاعات کاربر یا null
مثال:
public ClaimsPrincipal GetUserFromToken(string token)
{
try
{
var principal = JwtHelper.ValidateToken(
token: token,
key: SenroConfig.JwtKey,
issuer: SenroConfig.JwtIssuer,
audience: "my-app-audience"
);
if (principal != null)
{
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var username = principal.FindFirst(ClaimTypes.Name)?.Value;
var roles = principal.FindAll(ClaimTypes.Role).Select(c => c.Value);
return principal;
}
}
catch (SecurityTokenException)
{
// توکن نامعتبر
}
return null;
}
DecodeToken() - decode توکن بدون اعتبارسنجی
استخراج اطلاعات از توکن بدون بررسی اعتبار.
پارامترها:
token: توکن JWT
نوع بازگشتی: JwtSecurityToken - شیء توکن decode شده
مثال:
public string GetUsernameFromToken(string token)
{
var jwtToken = JwtHelper.DecodeToken(token);
return jwtToken.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
}
public bool IsTokenExpired(string token)
{
var jwtToken = JwtHelper.DecodeToken(token);
var expiry = jwtToken.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value;
if (long.TryParse(expiry, out var exp))
{
var expiryDate = DateTimeOffset.FromUnixTimeSeconds(exp).UtcDateTime;
return expiryDate < DateTime.UtcNow;
}
return true;
}
GenerateKey() - تولید کلید رمزنگاری
تولید کلید رندم برای استفاده در JWT.
پارامترها:
size: اندازه کلید به بایت (پیشفرض: 32)
نوع بازگشتی: byte[] - کلید تولید شده
مثال:
// تولید کلید 256 بیتی (32 بایت)
byte[] key256 = JwtHelper.GenerateKey(32);
// تولید کلید 512 بیتی (64 بایت)
byte[] key512 = JwtHelper.GenerateKey(64);
// تولید کلید پیشفرض
byte[] defaultKey = JwtHelper.GenerateKey();
Hash Helper Classes
MD5Helper - هش MD5
public static class MD5Helper
{
public static string ComputeHash(string input)
public static string ComputeHash(byte[] input)
public static bool VerifyHash(string input, string hash)
}
مثال:
using Senro.AspNetCore.Tools.Helper.Hash;
// هش رشته
string hash1 = MD5Helper.ComputeHash("password"); // "5f4dcc3b5aa765d61d8327deb882cf99"
// هش فایل
byte[] fileBytes = File.ReadAllBytes("document.pdf");
string fileHash = MD5Helper.ComputeHash(fileBytes);
// بررسی هش
bool isValid = MD5Helper.VerifyHash("password", "5f4dcc3b5aa765d61d8327deb882cf99");
SHA256Helper - هش SHA256
public static class SHA256Helper
{
public static string ComputeHash(string input)
public static string ComputeHash(byte[] input)
public static bool VerifyHash(string input, string hash)
}
مثال:
// هش امن رمز عبور
string password = "MySecurePassword123!";
string hashedPassword = SHA256Helper.ComputeHash(password);
// ذخیره در دیتابیس
await _context.Users.AddAsync(new User
{
Username = "johndoe",
PasswordHash = hashedPassword
});
// بررسی رمز عبور
bool isPasswordValid = SHA256Helper.VerifyHash(password, hashedPassword);
SHA512Helper - هش SHA512
public static class SHA512Helper
{
public static string ComputeHash(string input)
public static string ComputeHash(byte[] input)
public static bool VerifyHash(string input, string hash)
}
مثال:
// هش دادههای بسیار حساس
string criticalData = "sensitive-bank-information";
string secureHash = SHA512Helper.ComputeHash(criticalData);
// هش فایلهای بزرگ
using (var stream = File.OpenRead("large-file.zip"))
{
using (var sha512 = SHA512.Create())
{
byte[] hashBytes = sha512.ComputeHash(stream);
string fileHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}
}
QR Code Helper
کلاس QRCodeHelper - تولید کد QR
تولید کد QR با استفاده از QRCoder.
متدهای QRCodeHelper
GenerateQRCode() - تولید کد QR ساده
تولید کد QR از متن.
پارامترها:
text: متن برای تبدیل به QRpixelSize: اندازه پیکسلها (پیشفرض: 20)
نوع بازگشتی: string - تصویر Base64
مثال:
using Senro.AspNetCore.Tools.Helper.Image;
public class QRService
{
public string GenerateUrlQR(string url)
{
return QRCodeHelper.GenerateQRCode(url, 15);
}
public string GenerateTextQR(string text)
{
return QRCodeHelper.GenerateQRCode(text);
}
public string GenerateContactQR(string name, string phone, string email)
{
string vcard = $"BEGIN:VCARD\nVERSION:3.0\nFN:{name}\nTEL:{phone}\nEMAIL:{email}\nEND:VCARD";
return QRCodeHelper.GenerateQRCode(vcard);
}
public string GenerateWifiQR(string ssid, string password, string encryption = "WPA")
{
string wifiString = $"WIFI:T:{encryption};S:{ssid};P:{password};;";
return QRCodeHelper.GenerateQRCode(wifiString);
}
}
GenerateQRCodeWithLogo() - تولید کد QR با لوگو
تولید کد QR با لوگو وسط تصویر.
پارامترها:
text: متن برای QRlogoPath: مسیر فایل لوگوpixelSize: اندازه پیکسلها
نوع بازگشتی: string - تصویر Base64
مثال:
public string GenerateBrandedQR(string url)
{
string logoPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "logo.png");
return QRCodeHelper.GenerateQRCodeWithLogo(url, logoPath, 20);
}
TOTP Helper
کلاس GoogleTwoFactorAuthHelper - احراز هویت دو مرحلهای
توابع TOTP (Time-based One-Time Password) برای 2FA.
متدهای GoogleTwoFactorAuthHelper
GenerateSecretKey() - تولید کلید رمز
تولید کلید رمز برای TOTP.
پارامترها:
length: طول کلید (پیشفرض: 32)
نوع بازگشتی: string - کلید رمز Base32
مثال:
using Senro.AspNetCore.Tools.Helper.TOTP;
public class TwoFactorSetupService
{
public string SetupUser2FA(string username)
{
// تولید کلید منحصر به فرد برای کاربر
string secretKey = GoogleTwoFactorAuthHelper.GenerateSecretKey(32);
// ذخیره در دیتابیس
// user.TwoFactorSecret = secretKey;
return secretKey;
}
}
GenerateTOTP() - تولید کد TOTP
تولید کد ۶ رقمی برای زمان فعلی.
پارامترها:
secretKey: کلید رمز کاربرtimeStep: قدم زمانی سفارشی (اختیاری)
نوع بازگشتی: string - کد ۶ رقمی
مثال:
public string GetCurrentTOTPCode(string secretKey)
{
return GoogleTwoFactorAuthHelper.GenerateTOTP(secretKey);
}
// تولید کد برای زمان خاص (برای تست)
public string GetTOTPForTime(string secretKey, long timeStep)
{
return GoogleTwoFactorAuthHelper.GenerateTOTP(secretKey, timeStep);
}
ValidateTOTP() - اعتبارسنجی کد TOTP
بررسی کد وارد شده توسط کاربر.
پارامترها:
secretKey: کلید رمز کاربرuserCode: کد وارد شدهtimeTolerance: تحمل زمانی به دقیقه (پیشفرض: 2)
نوع بازگشتی: bool - نتیجه اعتبارسنجی
مثال:
public bool VerifyTOTPCode(string secretKey, string userCode)
{
// بررسی با تحمل ±۲ دقیقه
return GoogleTwoFactorAuthHelper.ValidateTOTP(secretKey, userCode, 2);
}
public bool VerifyTOTPExact(string secretKey, string userCode)
{
// بررسی بدون تحمل زمانی
return GoogleTwoFactorAuthHelper.ValidateTOTP(secretKey, userCode, 0);
}
GenerateTOTPUrl() - تولید URL استاندارد
تولید URL برای Google Authenticator.
پارامترها:
issuer: نام برنامهaccountName: نام حساب کاربریsecretKey: کلید رمز
نوع بازگشتی: string - URL otpauth
مثال:
public string GetTOTPSetupUrl(string username, string secretKey)
{
return GoogleTwoFactorAuthHelper.GenerateTOTPUrl(
issuer: "MyCompany App",
accountName: username,
secretKey: secretKey
);
// خروجی: "otpauth://totp/MyCompany%20App:username?secret=JBSWY3DPEHPK3PXP&issuer=MyCompany%20App"
}
مثال کامل 2FA Setup:
public class TwoFactorManager
{
private readonly IDataProtectorService _dataProtector;
public TwoFactorManager(IDataProtectorService dataProtector)
{
_dataProtector = dataProtector;
}
public TwoFactorSetupResult Setup2FA(string username)
{
// 1. تولید کلید رمز
string secretKey = GoogleTwoFactorAuthHelper.GenerateSecretKey();
// 2. تولید URL برای Google Authenticator
string totpUrl = GoogleTwoFactorAuthHelper.GenerateTOTPUrl(
"MyApp", username, secretKey);
// 3. تولید کد QR
string qrCodeBase64 = QRCodeHelper.GenerateQRCode(totpUrl);
// 4. تولید کد فعلی برای تست
string currentCode = GoogleTwoFactorAuthHelper.GenerateTOTP(secretKey);
return new TwoFactorSetupResult
{
SecretKey = _dataProtector.Encrypt(secretKey), // رمزنگاری برای ذخیره
TOTPUrl = totpUrl,
QRCodeBase64 = qrCodeBase64,
CurrentCode = currentCode // فقط برای نمایش در UI
};
}
public async Task<bool> Enable2FA(int userId, string verificationCode)
{
var user = await _context.Users.FindAsync(userId);
if (user == null) return false;
// رمزگشایی کلید
string secretKey = _dataProtector.Decrypt(user.TwoFactorSecret);
// اعتبارسنجی کد
if (!GoogleTwoFactorAuthHelper.ValidateTOTP(secretKey, verificationCode))
return false;
// فعال کردن 2FA
user.IsTwoFactorEnabled = true;
await _context.SaveChangesAsync();
return true;
}
public bool Verify2FA(string secretKey, string code)
{
return GoogleTwoFactorAuthHelper.ValidateTOTP(secretKey, code);
}
}
public class TwoFactorSetupResult
{
public string SecretKey { get; set; }
public string TOTPUrl { get; set; }
public string QRCodeBase64 { get; set; }
public string CurrentCode { get; set; }
}
Sitemap Helper
کلاس SitemapHelper - تولید نقشه سایت
توابع تولید XML نقشه سایت.
متدهای SitemapHelper
GenerateSitemapXml() - تولید نقشه سایت
تولید XML نقشه سایت از لیست URLها.
پارامترها:
urls: لیست SitemapUrl
نوع بازگشتی: string - XML نقشه سایت
مثال:
using Senro.AspNetCore.Tools.Helper.Seo.Sitemap;
public class SitemapGenerator
{
public string GenerateSiteSitemap()
{
var urls = new List<SitemapUrl>
{
new SitemapUrl
{
Location = "https://example.com/",
LastModified = DateTime.UtcNow,
ChangeFrequency = SitemapUpdateFrequency.Weekly,
Priority = 1.0
},
new SitemapUrl
{
Location = "https://example.com/products",
LastModified = DateTime.UtcNow.AddDays(-1),
ChangeFrequency = SitemapUpdateFrequency.Daily,
Priority = 0.8
}
};
return SitemapHelper.GenerateSitemapXml(urls);
}
}
GenerateSitemapIndex() - تولید ایندکس نقشه سایت
تولید XML ایندکس برای نقشه سایتهای بزرگ.
پارامترها:
sitemaps: لیست SitemapFile
نوع بازگشتی: string - XML ایندکس
مثال:
public string GenerateSitemapIndex()
{
var sitemaps = new List<SitemapFile>
{
new SitemapFile
{
FileName = "sitemap-products.xml",
Urls = GetProductUrls()
},
new SitemapFile
{
FileName = "sitemap-blog.xml",
Urls = GetBlogUrls()
}
};
return SitemapHelper.GenerateSitemapIndex(sitemaps);
}
Dependency Injection Helpers
Interfaceها برای ثبت خودکار
IScoped - ثبت به عنوان Scoped
public interface IScoped { }
مثال:
[Scoped]
public class UserService : IUserService, IScoped
{
// این کلاس به صورت Scoped ثبت میشود
}
ISingleton - ثبت به عنوان Singleton
public interface ISingleton { }
مثال:
[Singleton]
public class CacheService : ICacheService, ISingleton
{
// این کلاس به صورت Singleton ثبت میشود
}
ITransient - ثبت به عنوان Transient
public interface ITransient { }
مثال:
[Transient]
public class EmailService : IEmailService, ITransient
{
// این کلاس به صورت Transient ثبت میشود
}
استفاده:
// در Program.cs
builder.Services.AddSenroServiceHandler();
// این کد تمام کلاسهایی که از interfaceهای بالا ارث بردهاند را ثبت میکند
📚 API Reference کامل
Extension Methods
String Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
Integration() |
string replaceString = "" |
string |
پاکسازی متن |
FixPersianChars() |
- | string |
تصحیح حروف عربی به فارسی |
GetComparisonPercentage() |
string comparativeText |
int |
مقایسه تشابه دو متن |
CalcLevenshteinDistance() |
string a, string b |
int |
فاصله ویرایشی |
GenerateSecretKey() |
int length = 10 |
string |
تولید کلید رندم |
GeneratePassword() |
int length = 10, int nonAlpha = 2 |
string |
تولید رمز عبور |
ToCamelCase() |
- | string |
تبدیل به CamelCase |
CustomIntersect() |
List<string> comparativeText |
List<string> |
مقایسه لیستها |
DateTime Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
ToPersianDateString() |
- | string |
تاریخ شمسی |
AddWeeks() |
int weeks |
DateTime |
اضافه کردن هفته |
IsWeekend() |
- | bool |
بررسی تعطیل بودن |
CalculateAge() |
- | int |
محاسبه سن |
ToPersian_TimeDifference() |
- | string |
اختلاف زمانی به فارسی |
ToPersian_TimeDifference() |
DateTime firstDate, DateTime secondDate |
string |
اختلاف بین دو تاریخ |
ToPersian_TimeDifferenceDetail() |
- | string |
اختلاف زمانی دقیق |
ToPersian_TimeDifferenceDetail() |
DateTime firstDate, DateTime secondDate |
string |
اختلاف دقیق بین دو تاریخ |
Number Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
ToPersianNumber() |
- | string |
اعداد فارسی |
ToEnglishNumber() |
- | string |
اعداد انگلیسی |
CalculatePercentage() |
int percent |
decimal |
محاسبه درصد |
IsEven() |
- | bool |
بررسی زوج بودن |
File Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GetMimeType() |
- | string |
نوع MIME |
GetFileExtension() |
- | string |
پسوند فایل |
IsImage() |
- | bool |
بررسی تصویر |
Generic Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
CreateInstance<T>() |
- | T |
ایجاد نمونه |
GetDisplayName() |
- | string |
نام نمایشی |
GetChildren<T>() |
- | IList<Type> |
فرزندان interface |
JWT Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateJwtToken() |
claims, key, issuer, expires |
string |
تولید توکن |
ValidateJwtToken() |
token, key, issuer |
ClaimsPrincipal |
اعتبارسنجی توکن |
Two-Factor Authentication Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateTOTP() |
string secretKey |
string |
تولید کد TOTP |
ValidateTOTP() |
secretKey, userCode |
bool |
اعتبارسنجی TOTP |
GenerateQRCode() |
string text |
string |
تولید QR Code |
Hash Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
ToMD5() |
- | string |
هش MD5 |
ToSHA256() |
- | string |
هش SHA256 |
ToSHA512() |
- | string |
هش SHA512 |
XML Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
ToXmlString<T>() |
- | string |
شیء به XML |
FromXmlString<T>() |
- | T |
XML به شیء |
Validation Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
IsValidEmail() |
- | bool |
اعتبارسنجی ایمیل |
IsValidPhoneNumber() |
- | bool |
اعتبارسنجی تلفن |
HttpContext Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GetIP() |
- | string |
دریافت IP |
GetUserAgent() |
- | string |
دریافت User Agent |
Enum Extensions
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GetDisplayName() |
- | string |
نام نمایشی |
ToSelectList() |
- | IEnumerable<SelectListItem> |
لیست انتخابی |
Services
IExcelService
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
ToExcel<T>() |
objs, sheetName |
byte[] |
تبدیل به Excel |
FromExcel<T>() |
file/string/stream/IFormFile |
IEnumerable<T> |
خواندن از Excel |
SampleForImport<T>() |
- | byte[] |
فایل نمونه |
ILDAPService
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GetUsers() |
address, username, password |
IEnumerable<LDAPUserDto> |
دریافت کاربران |
GetUsers<T>() |
address, username, password |
List<T> |
کاربران سفارشی |
ValidateUser() |
address, username, password |
bool |
اعتبارسنجی کاربر |
IDataProtectorService
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
Encrypt() |
plainText |
string |
رمزنگاری |
Decrypt() |
encryptedText |
string |
رمزگشایی |
ICaptchaService
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateCaptcha() |
- | CaptchaResult |
تولید کپچا |
ValidateCaptcha() |
userInput, captchaId |
bool |
اعتبارسنجی کپچا |
ISitemapService
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateSitemap() |
urls |
string |
تولید نقشه سایت |
ISenroService
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateGuid() |
- | string |
تولید GUID |
GetCurrentDateTime() |
- | DateTime |
تاریخ فعلی |
CalculateAge() |
birthDate |
int |
محاسبه سن |
Helper Classes
JwtHelper
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateToken() |
claims, key, issuer, expires |
string |
تولید توکن |
ValidateToken() |
token, key, issuer, audience |
ClaimsPrincipal |
اعتبارسنجی |
DecodeToken() |
token |
JwtSecurityToken |
decode توکن |
GenerateKey() |
size |
byte[] |
تولید کلید |
Hash Helpers
| کلاس | متدها | توضیح |
|---|---|---|
MD5Helper |
ComputeHash(), VerifyHash() |
هش MD5 |
SHA256Helper |
ComputeHash(), VerifyHash() |
هش SHA256 |
SHA512Helper |
ComputeHash(), VerifyHash() |
هش SHA512 |
QRCodeHelper
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateQRCode() |
text, pixelSize |
string |
تولید QR ساده |
GenerateQRCodeWithLogo() |
text, logoPath, pixelSize |
string |
QR با لوگو |
GoogleTwoFactorAuthHelper
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateSecretKey() |
length |
string |
تولید کلید رمز |
GenerateTOTP() |
secretKey, timeStep |
string |
تولید کد TOTP |
ValidateTOTP() |
secretKey, userCode, timeTolerance |
bool |
اعتبارسنجی TOTP |
GenerateTOTPUrl() |
issuer, accountName, secretKey |
string |
URL استاندارد |
SitemapHelper
| متد | پارامترها | نوع بازگشتی | توضیح |
|---|---|---|---|
GenerateSitemapXml() |
urls |
string |
تولید XML نقشه سایت |
GenerateSitemapIndex() |
sitemaps |
string |
تولید ایندکس |
⚙️ تنظیمات پیشرفته
تنظیمات محیطی
Development
if (builder.Environment.IsDevelopment())
{
// تنظیمات سادهتر برای توسعه
SenroConfig.EncriptKey = "Dev-Encryption-Key-12345678901234567890";
SenroConfig.JwtKey = Encoding.UTF8.GetBytes("Dev-JWT-Key-12345678901234567890123456789012");
SenroConfig.JwtIssuer = "Dev-Issuer";
// نمایش خطاها در کپچا
// Captcha text will be visible in development
}
Production
if (builder.Environment.IsProduction())
{
// خواندن از Environment Variables
SenroConfig.EncriptKey = Environment.GetEnvironmentVariable("ENCRYPTION_KEY")
?? throw new InvalidOperationException("Encryption key not found");
SenroConfig.JwtKey = Encoding.UTF8.GetBytes(
Environment.GetEnvironmentVariable("JWT_KEY")
?? throw new InvalidOperationException("JWT key not found"));
SenroConfig.JwtIssuer = Environment.GetEnvironmentVariable("JWT_ISSUER") ?? "Production-Issuer";
// تنظیمات امنیتی پیشرفته
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("/app/keys"))
.ProtectKeysWithCertificate("certificate-thumbprint");
}
استفاده از appsettings.json
{
"SenroSettings": {
"EncryptionKey": "Your-Encryption-Key-Here",
"JwtSettings": {
"Key": "Your-JWT-Key-Here-32-chars-minimum",
"Issuer": "Your-App-Issuer",
"Audience": "Your-App-Audience",
"ExpiryHours": 2
},
"CaptchaSettings": {
"Width": 200,
"Height": 70,
"FontSize": 24
},
"LdapSettings": {
"DefaultDomain": "company.local",
"DefaultAdmin": "admin@company.local"
}
}
}
// خواندن تنظیمات
var senroSettings = builder.Configuration.GetSection("SenroSettings");
SenroConfig.EncriptKey = senroSettings["EncryptionKey"];
var jwtSettings = senroSettings.GetSection("JwtSettings");
SenroConfig.JwtKey = Encoding.UTF8.GetBytes(jwtSettings["Key"]);
SenroConfig.JwtIssuer = jwtSettings["Issuer"];
تنظیمات Dependency Injection
ثبت دستی سرویسها
builder.Services.AddScoped<ILDAPService, LDAPService>();
builder.Services.AddScoped<IExcelService, ExcelService>();
builder.Services.AddScoped<IDataProtectorService, DataProtectorService>();
builder.Services.AddScoped<ICaptchaService, SixLaborsCaptchaService>();
builder.Services.AddScoped<ISitemapService, SitemapService>();
استفاده از Auto-Registration
// ثبت خودکار تمام سرویسها
builder.Services.AddSenroServices();
// ثبت خودکار سرویسهای سفارشی
builder.Services.AddSenroServiceHandler();
🔧 عیبیابی و مشکلات رایج
مشکلات رایج Extension Methods
خطای "Method not found"
// مطمئن شوید using directive اضافه شده
using Senro.AspNetCore.Tools.Extentions;
// برای string extensions
string result = "text".Integration();
// برای DateTime extensions
DateTime dt = DateTime.Now;
string persian = dt.ToPersianDateString();
خطای "Nullable reference"
// اگر nullable reference فعال است
string? nullableText = null;
string result = nullableText?.Integration() ?? ""; // استفاده از null conditional
مشکلات رایج Services
خطای "Service not registered"
// مطمئن شوید سرویسها در Program.cs ثبت شدهاند
builder.Services.AddSenroServices();
// یا ثبت دستی
builder.Services.AddScoped<IExcelService, ExcelService>();
خطای LDAP Connection
// بررسی تنظیمات شبکه و firewall
// بررسی اعتبارنامه ادمین
// بررسی پورت LDAP (389 برای غیرSSL، 636 برای SSL)
try
{
var users = _ldapService.GetUsers(domain, username, password);
}
catch (LdapException ex)
{
_logger.LogError($"LDAP Error: {ex.Message}");
// نمایش پیام خطای مناسب به کاربر
}
خطای Excel Processing
// بررسی فرمت فایل
if (!file.FileName.EndsWith(".xlsx") && !file.FileName.EndsWith(".xls"))
{
return BadRequest("فرمت فایل باید Excel باشد");
}
// بررسی اندازه فایل
if (file.Length > 10 * 1024 * 1024) // 10MB
{
return BadRequest("حجم فایل نمیتواند بیشتر از ۱۰ مگابایت باشد");
}
try
{
var data = _excelService.FromExcel<Model>(file);
}
catch (Exception ex)
{
_logger.LogError($"Excel processing error: {ex.Message}");
return BadRequest("خطا در پردازش فایل Excel");
}
مشکلات رایج JWT
خطای "Invalid signature"
// بررسی کلید JWT
// مطمئن شوید کلید در تولید و اعتبارسنجی یکسان است
// کلید باید حداقل 256 بیت باشد
var key = Encoding.UTF8.GetBytes("your-256-bit-or-longer-key-here");
SenroConfig.JwtKey = key;
خطای "Token expired"
// تنظیم زمان انقضا مناسب
var expires = DateTime.UtcNow.AddHours(1); // 1 ساعت
// یا
var expires = DateTime.UtcNow.AddMinutes(30); // 30 دقیقه
مشکلات رایج 2FA
خطای TOTP Validation
// بررسی sync ساعت سرور و کلاینت
// استفاده از time tolerance
bool isValid = GoogleTwoFactorAuthHelper.ValidateTOTP(secretKey, code, 2); // ±2 minutes
// بررسی فرمت secret key (باید Base32 باشد)
if (!IsValidBase32(secretKey))
{
throw new InvalidOperationException("Invalid secret key format");
}
خطای QR Code Generation
// بررسی طول متن QR
if (text.Length > 1000)
{
return BadRequest("متن QR نمیتواند بیشتر از ۱۰۰۰ کاراکتر باشد");
}
// بررسی وجود مسیر لوگو
if (!string.IsNullOrEmpty(logoPath) && !File.Exists(logoPath))
{
return BadRequest("فایل لوگو یافت نشد");
}
🚀 Performance Tips
استفاده بهینه از Extension Methods
// ❌ کند - فراخوانی مکرر روی رشته ثابت
for (int i = 0; i < 1000; i++)
{
string result = "input".Integration(); // هر بار پردازش میشود
}
// ✅ سریع - یک بار پردازش
string cleanInput = "input".Integration();
for (int i = 0; i < 1000; i++)
{
// استفاده از cleanInput
}
Cache برای عملیات سنگین
private readonly IMemoryCache _cache;
public async Task<string> GetSitemapAsync()
{
return await _cache.GetOrCreateAsync("sitemap", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
return await GenerateSitemapXmlAsync();
});
}
استفاده از StringBuilder برای عملیات رشتهای سنگین
// برای پردازش تعداد زیادی رشته
var results = new StringBuilder();
foreach (var item in largeList)
{
results.AppendLine(item.ToPersianNumber());
}
return results.ToString();
مدیریت Memory در Excel Processing
// استفاده از using برای آزادسازی منابع
using var stream = file.OpenReadStream();
var data = _excelService.FromExcel<Model>(stream);
// پردازش data
// stream به طور خودکار آزاد میشود
📊 مقایسه عملکرد
Extension Methods Performance
| عملیات | زمان تقریبی | تعداد عملیات در ثانیه |
|---|---|---|
FixPersianChars() |
~50ns | ~20M |
Integration() |
~200ns | ~5M |
ToPersianNumber() |
~100ns | ~10M |
CalculateAge() |
~150ns | ~6M |
Services Performance
| سرویس | عملیات | زمان تقریبی |
|---|---|---|
| JWT | Generate | ~1ms |
| JWT | Validate | ~2ms |
| Excel | Read 1000 rows | ~500ms |
| LDAP | Authenticate | ~200-500ms |
| Captcha | Generate | ~50ms |
🔐 امنیت
هش ایمن رمز عبور
public class SecurePasswordHasher
{
public string HashPassword(string password)
{
// استفاده از PBKDF2 یا Argon2 به جای SHA مستقیم
return SHA256Helper.ComputeHash(password + GetSalt());
}
private string GetSalt()
{
return Guid.NewGuid().ToString();
}
}
تولید کلیدهای امن
public class SecureKeyGenerator
{
public byte[] GenerateSecureKey(int size = 32)
{
using var rng = RandomNumberGenerator.Create();
var key = new byte[size];
rng.GetBytes(key);
return key;
}
}
اعتبارسنجی ورودیها
public class InputValidator
{
public bool IsValidInput(string input)
{
if (string.IsNullOrEmpty(input)) return false;
if (input.Length > 1000) return false; // جلوگیری از DoS
if (!input.IsValidEmail()) return false;
return true;
}
}
📈 مثالهای پیشرفته
سیستم کامل احراز هویت با JWT و 2FA
سیستم مدیریت فایل با LDAP و Excel
سیستم نظرسنجی با Captcha و Sitemap
🤝 مشارکت
مشارکتها را خوشامد میگوییم! لطفاً برای مشارکت:
- این repository را fork کنید
- یک branch برای ویژگی جدید ایجاد کنید (
git checkout -b feature/AmazingFeature) - تغییرات خود را commit کنید (
git commit -m 'Add some AmazingFeature') - به branch push کنید (
git push origin feature/AmazingFeature) - یک Pull Request ایجاد کنید
راهنمای کد نویسی
- از PascalCase برای نام کلاسها و متدها استفاده کنید
- از camelCase برای پارامترها استفاده کنید
- کامنتهای XML را برای همه public members اضافه کنید
- تستهای واحد برای تغییرات جدید بنویسید
- مستندات را بهروز نگه دارید
📄 مجوز
این پروژه تحت مجوز MIT منتشر شده است. برای اطلاعات بیشتر فایل LICENSE را مشاهده کنید.
👨💻 توسعهدهنده
امیرحسین خلیفه
- ایمیل: [امیرحسین خلیفه]
- شرکت: Senro
- LinkedIn: [Senro Development Team]
⭐ اگر این کتابخانه برایتان مفید بود، لطفاً یک ستاره بدهید!
💡 پیشنهاد ویژگی جدید دارید؟ GitHub Issues را بررسی کنید یا یک issue جدید باز کنید. { _ldapService = ldapService; }
// دریافت کاربران public IActionResult GetUsers(string domain, string username, string password) { var users = _ldapService.GetUsers(domain, username, password); return Ok(users); }
// دریافت کاربران با نوع سفارشی public IActionResult GetUsersCustom(string domain, string username, string password) { var users = _ldapService.GetUsers<UserDto>(domain, username, password); return Ok(users); }
// اعتبارسنجی کاربر public IActionResult ValidateUser(string domain, string username, string password) { bool isValid = _ldapService.ValidateUser(domain, username, password); return Ok(new { IsValid = isValid }); }
### Data Protector Service
```csharp
using Senro.AspNetCore.Tools.Services.DataProtector;
// تزریق سرویس
private readonly IDataProtectorService _dataProtector;
public SecurityController(IDataProtectorService dataProtector)
{
_dataProtector = dataProtector;
}
// رمزنگاری داده
public IActionResult EncryptData(string plainText)
{
string encrypted = _dataProtector.Encrypt(plainText);
return Ok(new { Encrypted = encrypted });
}
// رمزگشایی داده
public IActionResult DecryptData(string encryptedText)
{
string decrypted = _dataProtector.Decrypt(encryptedText);
return Ok(new { Decrypted = decrypted });
}
Captcha Service
using Senro.AspNetCore.Tools.Services.Captcha;
// تزریق سرویس
private readonly ICaptchaService _captchaService;
public CaptchaController(ICaptchaService captchaService)
{
_captchaService = captchaService;
}
// تولید کپچا
public IActionResult GenerateCaptcha()
{
var captcha = _captchaService.GenerateCaptcha();
return Ok(new
{
ImageBase64 = captcha.ImageBase64,
Text = captcha.Text // در محیط توسعه
});
}
// اعتبارسنجی کپچا
public IActionResult ValidateCaptcha(string userInput, string captchaId)
{
bool isValid = _captchaService.ValidateCaptcha(userInput, captchaId);
return Ok(new { IsValid = isValid });
}
JWT Extensions
using Senro.AspNetCore.Tools.Extentions;
// تولید توکن JWT
public string GenerateToken(User user)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Email, user.Email)
};
var token = claims.GenerateJwtToken(
key: SenroConfig.JwtKey,
issuer: SenroConfig.JwtIssuer,
expires: DateTime.UtcNow.AddHours(1)
);
return token;
}
// اعتبارسنجی توکن
public ClaimsPrincipal ValidateToken(string token)
{
var principal = token.ValidateJwtToken(
key: SenroConfig.JwtKey,
issuer: SenroConfig.JwtIssuer
);
return principal;
}
Sitemap Service
using Senro.AspNetCore.Tools.Services.Sitemap;
// تزریق سرویس
private readonly ISitemapService _sitemapService;
public SitemapController(ISitemapService sitemapService)
{
_sitemapService = sitemapService;
}
// تولید Sitemap
public IActionResult GenerateSitemap()
{
var urls = new List<SitemapUrl>
{
new SitemapUrl
{
Location = "https://example.com/",
LastModified = DateTime.UtcNow,
ChangeFrequency = SitemapUpdateFrequency.Weekly,
Priority = 1.0
}
};
var sitemapXml = _sitemapService.GenerateSitemap(urls);
return Content(sitemapXml, "application/xml");
}
Two-Factor Authentication
using Senro.AspNetCore.Tools.Extentions;
// تولید کد QR برای Google Authenticator
public IActionResult Setup2FA(string username)
{
var secretKey = StringExtensions.GenerateSecretKey(32);
var qrCodeUrl = $"otpauth://totp/{username}?secret={secretKey}&issuer=YourApp";
// تولید کد QR
var qrCodeImage = qrCodeUrl.GenerateQRCode();
return Ok(new
{
SecretKey = secretKey,
QRCodeUrl = qrCodeUrl,
QRCodeImage = qrCodeImage
});
}
// تولید کد TOTP
public IActionResult GenerateTOTP(string secretKey)
{
var totpCode = secretKey.GenerateTOTP();
return Ok(new { Code = totpCode });
}
// اعتبارسنجی کد TOTP
public IActionResult ValidateTOTP(string secretKey, string userCode)
{
bool isValid = secretKey.ValidateTOTP(userCode);
return Ok(new { IsValid = isValid });
}
🔗 Dependency Injection Handler
// تعریف سرویسها با استفاده از attribute
[Scoped]
public class UserService : IUserService
{
// پیادهسازی
}
[Singleton]
public class CacheService : ICacheService
{
// پیادهسازی
}
[Transient]
public class EmailService : IEmailService
{
// پیادهسازی
}
// ثبت خودکار سرویسها
builder.Services.AddSenroServiceHandler();
📚 API Reference
Extension Methods
String Extensions
Integration(): پاکسازی متنFixPersianChars(): تصحیح حروف عربی به فارسیGetComparisonPercentage(): مقایسه تشابه دو متنCalcLevenshteinDistance(): محاسبه فاصله ویرایشیGenerateSecretKey(): تولید کلید رندمGeneratePassword(): تولید رمز عبورToCamelCase(): تبدیل به فرمت CamelCase
DateTime Extensions
ToPersianDateString(): تبدیل به تاریخ شمسیAddWeeks(): اضافه کردن هفتهIsWeekend(): بررسی روز تعطیلCalculateAge(): محاسبه سن
Number Extensions
ToPersianNumber(): تبدیل به عدد فارسیToEnglishNumber(): تبدیل به عدد انگلیسیCalculatePercentage(): محاسبه درصدIsEven(): بررسی عدد زوج
File Extensions
GetMimeType(): دریافت نوع MIMEGetFileExtension(): دریافت پسوند فایلIsImage(): بررسی فایل تصویر
Generic Extensions
CreateInstance<T>(): ایجاد نمونه از نوعGetDisplayName(): دریافت نام نمایشیGetChildren<T>(): دریافت فرزندان نوع
Services
IExcelService
ToExcel<T>(): تبدیل لیست به ExcelFromExcel<T>(): خواندن از ExcelSampleForImport<T>(): تولید نمونه فایل Excel
ILDAPService
GetUsers(): دریافت کاربران از Active DirectoryGetUsers<T>(): دریافت کاربران با نوع سفارشیValidateUser(): اعتبارسنجی کاربر
IDataProtectorService
Encrypt(): رمزنگاری دادهDecrypt(): رمزگشایی داده
ICaptchaService
GenerateCaptcha(): تولید کپچاValidateCaptcha(): اعتبارسنجی کپچا
ISitemapService
GenerateSitemap(): تولید نقشه سایت
🧪 مثال پروژه کامل
برای مشاهده مثال کامل، پروژه AspNetCoreSample در این repository را بررسی کنید.
🤝 مشارکت
مشارکتها را خوشامد میگوییم! لطفاً برای مشارکت:
- این repository را fork کنید
- یک branch برای ویژگی جدید ایجاد کنید
- تغییرات خود را commit کنید
- یک Pull Request ایجاد کنید
📄 مجوز
این پروژه تحت مجوز MIT منتشر شده است. برای اطلاعات بیشتر فایل LICENSE را مشاهده کنید.
👨💻 توسعهدهنده
امیرحسین خلیفه
- ایمیل: [امیرحسین خلیفه]
- شرکت: Senro
⭐ اگر این کتابخانه برایتان مفید بود، لطفاً یک ستاره بدهید!
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net6.0
- ClosedXML (>= 0.104.2)
- FileSignatures (>= 5.1.0)
- GoogleAuthenticator (>= 3.2.0)
- MD.PersianDateTime.Standard (>= 2.5.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 6.0.33)
- Microsoft.AspNetCore.DataProtection (>= 6.0.36)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
- Newtonsoft.Json (>= 13.0.3)
- Novell.Directory.Ldap.NETStandard (>= 3.6.0)
- QRCoder (>= 1.6.0)
- SixLabors.Fonts (>= 2.0.6)
- SixLabors.ImageSharp (>= 3.1.11)
- SixLaborsCaptcha.Core (>= 1.0.0)
-
net8.0
- ClosedXML (>= 0.104.2)
- FileSignatures (>= 5.1.0)
- GoogleAuthenticator (>= 3.2.0)
- MD.PersianDateTime.Standard (>= 2.5.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 8.0.8)
- Microsoft.AspNetCore.DataProtection (>= 8.0.11)
- Microsoft.Data.SqlClient (>= 5.2.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Newtonsoft.Json (>= 13.0.3)
- Novell.Directory.Ldap.NETStandard (>= 3.6.0)
- QRCoder (>= 1.6.0)
- SixLabors.Fonts (>= 2.0.6)
- SixLabors.ImageSharp (>= 3.1.11)
- SixLaborsCaptcha.Core (>= 1.0.0)
-
net9.0
- ClosedXML (>= 0.104.2)
- FileSignatures (>= 5.1.0)
- GoogleAuthenticator (>= 3.2.0)
- MD.PersianDateTime.Standard (>= 2.5.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.0)
- Microsoft.AspNetCore.DataProtection (>= 9.0.0)
- Microsoft.Data.SqlClient (>= 5.2.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.0)
- Newtonsoft.Json (>= 13.0.3)
- Novell.Directory.Ldap.NETStandard (>= 3.6.0)
- QRCoder (>= 1.6.0)
- SixLabors.Fonts (>= 2.0.6)
- SixLabors.ImageSharp (>= 3.1.11)
- SixLaborsCaptcha.Core (>= 1.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Senro.AspNetCore.Tools:
| Package | Downloads |
|---|---|
|
Senro.AspNetCore.Mvc.Tools
Commonly used codes in Asp.net Core Mvc Projects in the form of tools |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.17.2 | 436 | 12/10/2025 |
| 1.17.1 | 439 | 12/10/2025 |
| 1.17.0 | 440 | 12/10/2025 |
| 1.16.4 | 410 | 11/18/2025 |
| 1.16.3 | 184 | 11/15/2025 |
| 1.16.1 | 290 | 11/12/2025 |
| 1.16.0 | 189 | 10/8/2025 |
| 1.15.2 | 237 | 9/22/2025 |
| 1.15.1 | 285 | 9/15/2025 |
| 1.15.0 | 177 | 9/13/2025 |
| 1.14.0 | 162 | 9/5/2025 |
| 1.13.0 | 193 | 8/11/2025 |
| 1.12.0 | 188 | 8/11/2025 |
| 1.11.0 | 189 | 8/9/2025 |
| 1.10.3 | 170 | 8/9/2025 |
| 1.10.2 | 274 | 8/7/2025 |
| 1.10.1 | 264 | 8/7/2025 |
| 1.10.0 | 279 | 8/7/2025 |
| 1.9.10 | 247 | 4/28/2025 |
| 1.9.9 | 229 | 4/16/2025 |
| 1.9.8 | 268 | 4/16/2025 |
| 1.9.7 | 243 | 4/15/2025 |
| 1.9.6 | 277 | 4/15/2025 |
| 1.9.5 | 251 | 4/15/2025 |
| 1.9.4 | 243 | 4/15/2025 |
| 1.9.3 | 279 | 4/15/2025 |
| 1.9.2 | 259 | 4/15/2025 |
| 1.9.1 | 250 | 4/15/2025 |
| 1.9.0 | 250 | 4/8/2025 |
| 1.8.0 | 177 | 1/6/2025 |
| 1.7.10 | 200 | 12/5/2024 |
| 1.7.9 | 188 | 12/5/2024 |
| 1.7.8 | 151 | 12/5/2024 |
| 1.7.7 | 172 | 12/5/2024 |
| 1.7.6 | 175 | 11/30/2024 |
| 1.7.5 | 163 | 11/30/2024 |
| 1.7.4 | 166 | 11/30/2024 |
| 1.7.3 | 186 | 11/20/2024 |
| 1.7.2 | 158 | 11/18/2024 |
| 1.7.1 | 164 | 11/16/2024 |
| 1.7.0 | 158 | 11/16/2024 |
| 1.6.5 | 160 | 10/17/2024 |
| 1.6.4 | 200 | 10/10/2024 |
| 1.6.3 | 194 | 10/10/2024 |
| 1.6.2 | 209 | 10/10/2024 |
| 1.6.1 | 186 | 10/10/2024 |
| 1.6.0 | 173 | 10/7/2024 |
| 1.5.0 | 202 | 10/4/2024 |
| 1.4.1 | 173 | 10/4/2024 |
| 1.3.13 | 204 | 9/16/2024 |
| 1.3.12 | 205 | 9/16/2024 |
| 1.3.11 | 209 | 9/16/2024 |
| 1.3.10 | 190 | 9/16/2024 |
| 1.3.8 | 190 | 9/16/2024 |
| 1.3.4 | 230 | 9/16/2024 |
| 1.2.4 | 190 | 8/29/2024 |
| 1.1.4 | 179 | 8/29/2024 |
| 1.1.3 | 223 | 8/22/2024 |
| 1.1.2 | 256 | 8/20/2024 |
| 1.0.1 | 227 | 8/15/2024 |
| 1.0.0 | 201 | 8/15/2024 |