using (var db = new BloggingContext()) { using (var trn = db.Database.BeginTransaction()) { db.Blogs.Add(new Site { Url = "http://msdn.com/data/ef" }); db.Blogs.Add(new Site { Url = "http://blogs.msdn.com/adonet" }); db.SaveChanges(); db.Blogs.Add(new Site { Url = "http://twitter.com/efmagicunicorns" }); db.SaveChanges(); trn.Commit(); } }
نوشتن TagHelperهای سفارشی برای ASP.NET Core
فرض کنید قسمتی از صفحه را با یک Tag Helper سفارشی ایجاد کردهاید. اگر بخواهید یک دکمهی به روز رسانی را هم در اینجا اضافه کنید تا به صورت Ajax ایی این قسمت به روز شود، نیاز است بتوان این تگ هلپر را مجددا تولید کرد و سپس به صورت ()return Content بازگشت داد.
برای اینکار قسمتی که سبب رندر مجدد یک تگ هلپر میشود، به صورت زیر قابل پیاده سازی است:
var tagHelper = new MyCustomTagHelper(); var tagHelperContext = new TagHelperContext( allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>(), uniqueId: Guid.NewGuid().ToString("N")); var tagHelperOutput = new TagHelperOutput( tagName: "div", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent(string.Empty); return Task.FromResult<TagHelperContent>(tagHelperContent); }); tagHelper.Process(tagHelperContext, tagHelperOutput); var content = tagHelperOutput.Content.GetContent();
مشکل در رندر فوتر گروه ها
new PdfReport().DocumentPreferences(doc => { doc.RunDirection(PdfRunDirection.RightToLeft); doc.Orientation(PageOrientation.Portrait); doc.PageSize(PdfPageSize.A4); doc.DocumentMetadata(new DocumentMetadata { Author = _company, Application = "نرم افزار ", Keywords = "حساب تفصیلی " + _accountName, Subject = "حساب تفصیلی " + _accountName, Title = "حساب تفصیلی " + _accountName }); }) .DefaultFonts(fonts => { fonts.Path(Path.Combine(Environment.CurrentDirectory, @"fonts\irsans.ttf"), Path.Combine(Environment.CurrentDirectory, @"fonts\verdana.ttf")); fonts.Size(8); }) .PagesFooter(footer => { footer.DefaultFooter(string.Concat("کاربر : ", _userService.CurrentUser != null ? _userService.CurrentUser.UserName : string.Empty, " | ", "تاریخ تهیه گزارش : ", DateTimeHelper.ToPersianShortDateString(DateTime.Now, true, true))); }) .PagesHeader(header => { header.CustomHeader(new MasterDetailBookReportsHeader { PdfRptFont = header.PdfFont, Company = _company, FinancialYear = _financialPeriod.GetCurrentFinancialPeriodTitle(), ReportType = ReportType.SpecialDetailBook, ReportTitle = "دفتر تفصیلی" }); }) .MainTableTemplate(template => { template.CustomTemplate(new GrayTemplate()); }) .MainTablePreferences(table => { table.ColumnsWidthsType(TableColumnWidthType.Relative); table.GroupsPreferences(new GroupsPreferences { GroupType = GroupType.HideGroupingColumns, RepeatHeaderRowPerGroup = true, ShowOneGroupPerPage = true, SpacingBeforeAllGroupsSummary = 5f, NewGroupAvailableSpacingThreshold = 5f }); }) .MainTableDataSource(dataSource => { dataSource.AnonymousTypeList(_rows); }) .MainTableColumns(columns => { columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.Title); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Center); column.IsVisible(true); column.IsRowNumber(true); column.Order(0); column.Width(0.7f); column.Group(true, (val1, val2) => { return val1.ToString() == val2.ToString(); }); }); columns.AddColumn(column => { column.PropertyName("rowNumber"); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Center); column.IsVisible(true); column.IsRowNumber(true); column.Order(0); column.Width(0.7f); column.HeaderCell("ردیف"); }); columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.VoucherNumber); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Center); column.IsVisible(true); column.Order(0); column.Width(1); column.HeaderCell("سند"); }); columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.VoucherDate); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Center); column.IsVisible(true); column.Order(1); column.Width(1.5f); column.ColumnItemsTemplate(template => { template.TextBlock(); template.DisplayFormatFormula(obj => DateTimeHelper.ToPersianShortDateString((DateTime)obj)); }); column.HeaderCell("تاریخ"); }); columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.Description); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Left); column.IsVisible(true); column.Order(0); column.Width(4); column.HeaderCell("شرح"); }); columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.Debtor); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Right); column.IsVisible(true); column.Order(2); column.Width(1.5f); column.ColumnItemsTemplate(template => { template.TextBlock(); template.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj)); }); column.AggregateFunction(aggregateFunction => { aggregateFunction.NumericAggregateFunction(AggregateFunction.Sum); aggregateFunction.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj)); }); column.HeaderCell("بدهکار"); }); columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.Creditor); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Right); column.IsVisible(true); column.Order(3); column.Width(1.5f); column.ColumnItemsTemplate(template => { template.TextBlock(); template.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj)); }); column.AggregateFunction(aggregateFunction => { aggregateFunction.NumericAggregateFunction(AggregateFunction.Sum); aggregateFunction.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj)); }); column.HeaderCell("بستانکار"); }); columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.CaclulatedDetection); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Left); column.IsVisible(true); column.Order(4); column.Width(1); column.AggregateFunction(aggregateFunction => { aggregateFunction.CustomAggregateFunction(new CumulativeAggregateFunction(true)); aggregateFunction.DisplayFormatFormula(obj => obj == null ? string.Empty : obj.ToString()); }); column.HeaderCell("تشخیص"); }); columns.AddColumn(column => { column.PropertyName<VoucherRowPrintViewModel>(x => x.CaclulatedRemains); column.CellsHorizontalAlignment(PdfRpt.Core.Contracts.HorizontalAlignment.Right); column.IsVisible(true); column.Order(5); column.Width(1.5f); column.ColumnItemsTemplate(template => { template.TextBlock(); template.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj)); }); column.AggregateFunction(aggregateFunction => { aggregateFunction.CustomAggregateFunction(new CumulativeAggregateFunction()); aggregateFunction.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj)); }); column.HeaderCell("مانده"); }); }) .MainTableSummarySettings(summarySettings => { summarySettings.OverallSummarySettings("جمع کل"); summarySettings.PreviousPageSummarySettings("نقل از صفحه قبل"); }) .MainTableEvents(events => { events.DataSourceIsEmpty(message: "داده ای جهت نمایش وجود ندارد."); events.CellCreated(args => { args.Cell.BasicProperties.CellPadding = 4f; }); events.MainTableAdded(args => { var taxTable = new PdfGrid(3); // Create a clone of the MainTable's structure taxTable.RunDirection = 3; taxTable.SetWidths(new float[] { 3, 3, 3 }); taxTable.WidthPercentage = 100f; taxTable.SpacingBefore = 10f; taxTable.AddSimpleRow( (data, cellProperties) => { data.Value = "امضاء تنظیم کننده"; cellProperties.ShowBorder = true; cellProperties.PdfFont = args.PdfFont; }, (data, cellProperties) => { data.Value = "امضاء حسابدار"; cellProperties.ShowBorder = true; cellProperties.PdfFont = args.PdfFont; }, (data, cellProperties) => { data.Value = "امضاء مدیرعامل"; cellProperties.ShowBorder = true; cellProperties.PdfFont = args.PdfFont; }); args.PdfDoc.Add(taxTable); }); }) .Export(export => { export.ToExcel("خروجی اکسل"); export.ToCsv("خروجی CSV"); export.ToXml("خروجی XML"); }) .Generate(data => data.AsPdfFile(_documentSource));
سایتهای بسیاری هستند که سرویسهایی را برای بدست آوردن مشخصات کشور، از روی IP ارائه میدهند؛ ولی اکثر آنها برای این سرویسی که ارائه میدهند هزینه دریافت میکنند. سایتی که من در این مقاله معرفی خواهم کرد این سرویس را به رایگان ارائه میهد، به شرط اینکه درخواستهای شما در هر ساعت بیشتر از 10000 نباشد. اگر این اتفاق روی دهد، یعنی درخواستهای شما به بیش از 10000 در ساعت برسد، درخواستهای شما با خطای HTTP 403, forbidden مواجه خواهد شد و تا زمانیکه محدودیت شما به پایان برسد، باید منتظر بمانید.
سرویسی که این سایت ارائه میدهد، سورس باز و رایگان میباشد. اگر شما با این محدودیت 10000 درخواست در ساعت مشکلی داشتید، میتوانید این
سرویس را از اینجا دریافت و آنرا در سرور
خودتان اجرا کنید. سورس سرویس هم بر روی github موجود هست.
freegeoip.net/{format}/{IP_or_hostname}
freegeoip.net/xml/4.2.2.2 : XML freegeoip.net/csv/8.8.8.8 :CSV freegeoip.net/json/github.com :JSON
http://freegeoip.net/xml/162.158.88.214
<Response> <IP>162.158.88.214</IP> <CountryCode>DE</CountryCode> <CountryName>Germany</CountryName> <RegionCode>HE</RegionCode> <RegionName>Hesse</RegionName> <City>Frankfurt am Main</City> <ZipCode>60438</ZipCode> <TimeZone>Europe/Berlin</TimeZone> <Latitude>50.1167</Latitude> <Longitude>8.6833</Longitude> <MetroCode>0</MetroCode> </Response>
اگر آدرس IP را مشخص نکنید مشخصات مربوط به IP آدرس خودتان را دریافت خواهید کرد.
در ادامه از یک برنامه console application برای دریافت این پاسخ ارسال شده از سرویس و استخراج دادهها از آن استفاده خواهیم کرد.
البته این روش برای برنامههای تحت وب هم به همین صورت خواهد بود و تفاوتی نمیکند.
از این روش میتوانید برای بلاک کردن کشورهایی که نمیخواهید به برنامهی شما دسترسی پیدا کنند استفاده کنید و یا اینکه بدانید ip هایی که از سایت شما بازدید میکنند از کدام کشورهای جهان هستند و یا کار خلاقانهای که میتوانید انجام دهید، نمایش مکانهای بازدید کنندهها بر روی نقشه گوگل، با استفاده از طول و عرض جغرافیایی که این سرویس در اختیارتان میگذارد، میباشدpublic static void ReadXmlElements(string ipAddress) { XDocument xdoc=XDocument.Load("http://www.freegeoip.net/xml/" + ipAddress); var country = xdoc.Descendants("Response").Select(c => new { IpAddress = c.Element("IP")?.Value, CountryCode = c.Element("CountryCode")?.Value, CountryName = c.Element("CountryName")?.Value, RegionCode = c.Element("RegionCode")?.Value, RegionName = c.Element("RegionName")?.Value, City = c.Element("City")?.Value, ZipCode = c.Element("ZipCode")?.Value, TimeZone = c.Element("TimeZone")?.Value, Latitude = c.Element("Latitude")?.Value, Longitude = c.Element("Longitude")?.Value, MetroCode = c.Element("MetroCode")?.Value, }); var countryData = country.First(); Console.WriteLine("CountryName :" + countryData.CountryName +Environment.NewLine + "CountryCode :"+countryData.CountryCode + Environment.NewLine + "RegionCode :"+countryData.RegionCode + Environment.NewLine + "RegionName :" + countryData.RegionName + Environment.NewLine + "City :" + countryData.City + Environment.NewLine + "ZipCode :" + countryData.ZipCode + Environment.NewLine + "TimeZone :" + countryData.TimeZone + Environment.NewLine + "Latitude :" + countryData.Latitude + Environment.NewLine + "Longitude :" + countryData.Longitude + Environment.NewLine + "MetroCode :" + countryData.MetroCode ); Console.ReadKey(); }
در متد main برنامه، متد ReadXmlElements را فراخوانی کرده و آدرس آی
پی مورد نظر را پاس میدهیم:
static void Main(string[] args) { ReadXmlElements("162.158.88.214"); }
یک نکته : برای مقایسه کد کشور بدست آمده، باید لیست کاملی از کشورهای جهان را در اختیار داشته باشید، تا بتوانید تصمیم بگیرید که آیا کشور درخواست کننده، مد نظر شما هست یا خیر. برای اینکار، کلاسی را آماده کردهام که شامل کل کشورهای جهان میباشد و نام و کد کشورها، در آن وجود دارد؛ به صورت زیر:
public class WorldCountries { public string CountryCode { get; set; } public string CountryName { get; set; } }
public static class GenerateCountries { public static IList<WorldCountries> CreateCountries() { return new[] { new WorldCountries { CountryCode = "AF", CountryName = "Afghanistan"}, new WorldCountries { CountryCode = "AX", CountryName = "Åland Islands"}, new WorldCountries { CountryCode = "AL", CountryName = "Albania"}, new WorldCountries { CountryCode = "DZ", CountryName = "Algeria"}, new WorldCountries { CountryCode = "AS", CountryName = "American Samoa"}, new WorldCountries { CountryCode = "AD", CountryName = "Andorra"}, new WorldCountries { CountryCode = "AO", CountryName = "Angola"}, new WorldCountries { CountryCode = "AI", CountryName = "Anguilla"}, new WorldCountries { CountryCode = "AQ", CountryName = "Antarctica"}, new WorldCountries { CountryCode = "AG", CountryName = "Antigua and Barbuda"}, new WorldCountries { CountryCode = "AR", CountryName = "Argentina"}, new WorldCountries { CountryCode = "AM", CountryName = "Armenia"}, new WorldCountries { CountryCode = "AW", CountryName = "Aruba"}, new WorldCountries { CountryCode = "AU", CountryName = "Australia"}, new WorldCountries { CountryCode = "AT", CountryName = "Austria"}, new WorldCountries { CountryCode = "AZ", CountryName = "Azerbaijan"}, new WorldCountries { CountryCode = "BS", CountryName = "Bahamas"}, new WorldCountries { CountryCode = "BH", CountryName = "Bahrain"}, new WorldCountries { CountryCode = "BD", CountryName = "Bangladesh"}, new WorldCountries { CountryCode = "BB", CountryName = "Barbados"}, new WorldCountries { CountryCode = "BY", CountryName = "Belarus"}, new WorldCountries { CountryCode = "BE", CountryName = "Belgium"}, new WorldCountries { CountryCode = "BZ", CountryName = "Belize"}, new WorldCountries { CountryCode = "BJ", CountryName = "Benin"}, new WorldCountries { CountryCode = "BM", CountryName = "Bermuda"}, new WorldCountries { CountryCode = "BT", CountryName = "Bhutan"}, new WorldCountries { CountryCode = "BA", CountryName = "Bosnia and Herzegovina"}, new WorldCountries { CountryCode = "BW", CountryName = "Botswana"}, new WorldCountries { CountryCode = "BV", CountryName = "Bouvet Island"}, new WorldCountries { CountryCode = "BR", CountryName = "Brazil"}, new WorldCountries { CountryCode = "IO", CountryName = "British Indian Ocean Territory"}, new WorldCountries { CountryCode = "BN", CountryName = "Brunei Darussalam"}, new WorldCountries { CountryCode = "BG", CountryName = "Bulgaria"}, new WorldCountries { CountryCode = "BF", CountryName = "Burkina Faso"}, new WorldCountries { CountryCode = "BI", CountryName = "Burundi"}, new WorldCountries { CountryCode = "KH", CountryName = "Cambodia"}, new WorldCountries { CountryCode = "CM", CountryName = "Cameroon"}, new WorldCountries { CountryCode = "CA", CountryName = "Canada"}, new WorldCountries { CountryCode = "CV", CountryName = "Cape Verde"}, new WorldCountries { CountryCode = "KY", CountryName = "Cayman Islands"}, new WorldCountries { CountryCode = "CF", CountryName = "Central African Republic"}, new WorldCountries { CountryCode = "TD", CountryName = "Chad"}, new WorldCountries { CountryCode = "CL", CountryName = "Chile"}, new WorldCountries { CountryCode = "CN", CountryName = "China"}, new WorldCountries { CountryCode = "CX", CountryName = "Christmas Island"}, new WorldCountries { CountryCode = "CC", CountryName = "Cocos (Keeling) Islands"}, new WorldCountries { CountryCode = "CO", CountryName = "Colombia"}, new WorldCountries { CountryCode = "KM", CountryName = "Comoros"}, new WorldCountries { CountryCode = "CG", CountryName = "Congo"}, new WorldCountries { CountryCode = "CK", CountryName = "Cook Islands"}, new WorldCountries { CountryCode = "CR", CountryName = "Costa Rica"}, new WorldCountries { CountryCode = "HR", CountryName = "Croatia"}, new WorldCountries { CountryCode = "CU", CountryName = "Cuba"}, new WorldCountries { CountryCode = "CW", CountryName = "Curaçao"}, new WorldCountries { CountryCode = "CY", CountryName = "Cyprus"}, new WorldCountries { CountryCode = "CZ", CountryName = "Czech Republic"}, new WorldCountries { CountryCode = "DK", CountryName = "Denmark"}, new WorldCountries { CountryCode = "DJ", CountryName = "Djibouti"}, new WorldCountries { CountryCode = "DM", CountryName = "Dominica"}, new WorldCountries { CountryCode = "DO", CountryName = "Dominican Republic"}, new WorldCountries { CountryCode = "EC", CountryName = "Ecuador"}, new WorldCountries { CountryCode = "EG", CountryName = "Egypt"}, new WorldCountries { CountryCode = "SV", CountryName = "El Salvador"}, new WorldCountries { CountryCode = "GQ", CountryName = "Equatorial Guinea"}, new WorldCountries { CountryCode = "ER", CountryName = "Eritrea"}, new WorldCountries { CountryCode = "EE", CountryName = "Estonia"}, new WorldCountries { CountryCode = "ET", CountryName = "Ethiopia"}, new WorldCountries { CountryCode = "FK", CountryName = "Falkland Islands (Malvinas)"}, new WorldCountries { CountryCode = "FO", CountryName = "Faroe Islands"}, new WorldCountries { CountryCode = "FJ", CountryName = "Fiji"}, new WorldCountries { CountryCode = "FI", CountryName = "Finland"}, new WorldCountries { CountryCode = "FR", CountryName = "France"}, new WorldCountries { CountryCode = "GF", CountryName = "French Guiana"}, new WorldCountries { CountryCode = "PF", CountryName = "French Polynesia"}, new WorldCountries { CountryCode = "TF", CountryName = "French Southern Territories"}, new WorldCountries { CountryCode = "GA", CountryName = "Gabon"}, new WorldCountries { CountryCode = "GM", CountryName = "Gambia"}, new WorldCountries { CountryCode = "GE", CountryName = "Georgia"}, new WorldCountries { CountryCode = "DE", CountryName = "Germany"}, new WorldCountries { CountryCode = "GH", CountryName = "Ghana"}, new WorldCountries { CountryCode = "GI", CountryName = "Gibraltar"}, new WorldCountries { CountryCode = "GR", CountryName = "Greece"}, new WorldCountries { CountryCode = "GL", CountryName = "Greenland"}, new WorldCountries { CountryCode = "GD", CountryName = "Grenada"}, new WorldCountries { CountryCode = "GP", CountryName = "Guadeloupe"}, new WorldCountries { CountryCode = "GU", CountryName = "Guam"}, new WorldCountries { CountryCode = "GT", CountryName = "Guatemala"}, new WorldCountries { CountryCode = "GG", CountryName = "Guernsey"}, new WorldCountries { CountryCode = "GN", CountryName = "Guinea"}, new WorldCountries { CountryCode = "GW", CountryName = "Guinea-Bissau"}, new WorldCountries { CountryCode = "GY", CountryName = "Guyana"}, new WorldCountries { CountryCode = "HT", CountryName = "Haiti"}, new WorldCountries { CountryCode = "HM", CountryName = "Heard Island and McDonald Islands"}, new WorldCountries { CountryCode = "VA", CountryName = "Holy See (Vatican City State)"}, new WorldCountries { CountryCode = "HN", CountryName = "Honduras"}, new WorldCountries { CountryCode = "HK", CountryName = "Hong Kong"}, new WorldCountries { CountryCode = "HU", CountryName = "Hungary"}, new WorldCountries { CountryCode = "IS", CountryName = "Iceland"}, new WorldCountries { CountryCode = "IN", CountryName = "India"}, new WorldCountries { CountryCode = "ID", CountryName = "Indonesia"}, new WorldCountries { CountryCode = "IR", CountryName = "Iran"}, new WorldCountries { CountryCode = "IQ", CountryName = "Iraq"}, new WorldCountries { CountryCode = "IE", CountryName = "Ireland"}, new WorldCountries { CountryCode = "IM", CountryName = "Isle of Man"}, new WorldCountries { CountryCode = "IL", CountryName = "Israel"}, new WorldCountries { CountryCode = "IT", CountryName = "Italy"}, new WorldCountries { CountryCode = "JM", CountryName = "Jamaica"}, new WorldCountries { CountryCode = "JP", CountryName = "Japan"}, new WorldCountries { CountryCode = "JE", CountryName = "Jersey"}, new WorldCountries { CountryCode = "JO", CountryName = "Jordan"}, new WorldCountries { CountryCode = "KZ", CountryName = "Kazakhstan"}, new WorldCountries { CountryCode = "KE", CountryName = "Kenya"}, new WorldCountries { CountryCode = "KI", CountryName = "Kiribati"}, new WorldCountries { CountryCode = "KP", CountryName = "Korea"}, new WorldCountries { CountryCode = "KW", CountryName = "Kuwait"}, new WorldCountries { CountryCode = "KG", CountryName = "Kyrgyzstan"}, new WorldCountries { CountryCode = "LV", CountryName = "Latvia"}, new WorldCountries { CountryCode = "LB", CountryName = "Lebanon"}, new WorldCountries { CountryCode = "LS", CountryName = "Lesotho"}, new WorldCountries { CountryCode = "LR", CountryName = "Liberia"}, new WorldCountries { CountryCode = "LY", CountryName = "Libya"}, new WorldCountries { CountryCode = "LI", CountryName = "Liechtenstein"}, new WorldCountries { CountryCode = "LT", CountryName = "Lithuania"}, new WorldCountries { CountryCode = "LU", CountryName = "Luxembourg"}, new WorldCountries { CountryCode = "MO", CountryName = "Macao"}, new WorldCountries { CountryCode = "MK", CountryName = "Macedonia"}, new WorldCountries { CountryCode = "MG", CountryName = "Madagascar"}, new WorldCountries { CountryCode = "MW", CountryName = "Malawi"}, new WorldCountries { CountryCode = "MY", CountryName = "Malaysia"}, new WorldCountries { CountryCode = "MV", CountryName = "Maldives"}, new WorldCountries { CountryCode = "ML", CountryName = "Mali"}, new WorldCountries { CountryCode = "MT", CountryName = "Malta"}, new WorldCountries { CountryCode = "MH", CountryName = "Marshall Islands"}, new WorldCountries { CountryCode = "MQ", CountryName = "Martinique"}, new WorldCountries { CountryCode = "MR", CountryName = "Mauritania"}, new WorldCountries { CountryCode = "MU", CountryName = "Mauritius"}, new WorldCountries { CountryCode = "YT", CountryName = "Mayotte"}, new WorldCountries { CountryCode = "MX", CountryName = "Mexico"}, new WorldCountries { CountryCode = "FM", CountryName = "Micronesia"}, new WorldCountries { CountryCode = "MD", CountryName = "Moldova"}, new WorldCountries { CountryCode = "MC", CountryName = "Monaco"}, new WorldCountries { CountryCode = "MN", CountryName = "Mongolia"}, new WorldCountries { CountryCode = "ME", CountryName = "Montenegro"}, new WorldCountries { CountryCode = "MS", CountryName = "Montserrat"}, new WorldCountries { CountryCode = "MA", CountryName = "Morocco"}, new WorldCountries { CountryCode = "MZ", CountryName = "Mozambique"}, new WorldCountries { CountryCode = "MM", CountryName = "Myanmar"}, new WorldCountries { CountryCode = "NA", CountryName = "Namibia"}, new WorldCountries { CountryCode = "NR", CountryName = "Nauru"}, new WorldCountries { CountryCode = "NP", CountryName = "Nepal"}, new WorldCountries { CountryCode = "NL", CountryName = "Netherlands"}, new WorldCountries { CountryCode = "NC", CountryName = "New Caledonia"}, new WorldCountries { CountryCode = "NZ", CountryName = "New Zealand"}, new WorldCountries { CountryCode = "NI", CountryName = "Nicaragua"}, new WorldCountries { CountryCode = "NE", CountryName = "Niger"}, new WorldCountries { CountryCode = "NG", CountryName = "Nigeria"}, new WorldCountries { CountryCode = "NU", CountryName = "Niue"}, new WorldCountries { CountryCode = "NF", CountryName = "Norfolk Island"}, new WorldCountries { CountryCode = "MP", CountryName = "Northern Mariana Islands"}, new WorldCountries { CountryCode = "NO", CountryName = "Norway"}, new WorldCountries { CountryCode = "OM", CountryName = "Oman"}, new WorldCountries { CountryCode = "PK", CountryName = "Pakistan"}, new WorldCountries { CountryCode = "PW", CountryName = "Palau"}, new WorldCountries { CountryCode = "PS", CountryName = "Palestine"}, new WorldCountries { CountryCode = "PA", CountryName = "Panama"}, new WorldCountries { CountryCode = "PG", CountryName = "Papua New Guinea"}, new WorldCountries { CountryCode = "PY", CountryName = "Paraguay"}, new WorldCountries { CountryCode = "PE", CountryName = "Peru"}, new WorldCountries { CountryCode = "PH", CountryName = "Philippines"}, new WorldCountries { CountryCode = "PN", CountryName = "Pitcairn"}, new WorldCountries { CountryCode = "PL", CountryName = "Poland"}, new WorldCountries { CountryCode = "PT", CountryName = "Portugal"}, new WorldCountries { CountryCode = "PR", CountryName = "Puerto Rico"}, new WorldCountries { CountryCode = "QA", CountryName = "Qatar"}, new WorldCountries { CountryCode = "RE", CountryName = "Réunion"}, new WorldCountries { CountryCode = "RO", CountryName = "Romania"}, new WorldCountries { CountryCode = "RU", CountryName = "Russian Federation"}, new WorldCountries { CountryCode = "RW", CountryName = "Rwanda"}, new WorldCountries { CountryCode = "BL", CountryName = "Saint Barthélemy"}, new WorldCountries { CountryCode = "KN", CountryName = "Saint Kitts and Nevis"}, new WorldCountries { CountryCode = "LC", CountryName = "Saint Lucia"}, new WorldCountries { CountryCode = "MF", CountryName = "Saint Martin (French part)"}, new WorldCountries { CountryCode = "PM", CountryName = "Saint Pierre and Miquelon"}, new WorldCountries { CountryCode = "VC", CountryName = "Saint Vincent and the Grenadines"}, new WorldCountries { CountryCode = "WS", CountryName = "Samoa"}, new WorldCountries { CountryCode = "SM", CountryName = "San Marino"}, new WorldCountries { CountryCode = "ST", CountryName = "Sao Tome and Principe"}, new WorldCountries { CountryCode = "SA", CountryName = "Saudi Arabia"}, new WorldCountries { CountryCode = "SN", CountryName = "Senegal"}, new WorldCountries { CountryCode = "RS", CountryName = "Serbia"}, new WorldCountries { CountryCode = "SC", CountryName = "Seychelles"}, new WorldCountries { CountryCode = "SL", CountryName = "Sierra Leone"}, new WorldCountries { CountryCode = "SG", CountryName = "Singapore"}, new WorldCountries { CountryCode = "SX", CountryName = "Sint Maarten (Dutch part)"}, new WorldCountries { CountryCode = "SK", CountryName = "Slovakia"}, new WorldCountries { CountryCode = "SI", CountryName = "Slovenia"}, new WorldCountries { CountryCode = "SB", CountryName = "Solomon Islands"}, new WorldCountries { CountryCode = "SO", CountryName = "Somalia"}, new WorldCountries { CountryCode = "ZA", CountryName = "South Africa"}, new WorldCountries { CountryCode = "GS", CountryName = "South Georgia and the South Sandwich Islands"}, new WorldCountries { CountryCode = "SS", CountryName = "South Sudan"}, new WorldCountries { CountryCode = "ES", CountryName = "Spain"}, new WorldCountries { CountryCode = "LK", CountryName = "Sri Lanka"}, new WorldCountries { CountryCode = "SD", CountryName = "Sudan"}, new WorldCountries { CountryCode = "SR", CountryName = "Suriname"}, new WorldCountries { CountryCode = "SJ", CountryName = "Svalbard and Jan Mayen"}, new WorldCountries { CountryCode = "SZ", CountryName = "Swaziland"}, new WorldCountries { CountryCode = "SE", CountryName = "Sweden"}, new WorldCountries { CountryCode = "CH", CountryName = "Switzerland"}, new WorldCountries { CountryCode = "SY", CountryName = "Syrian Arab Republic"}, new WorldCountries { CountryCode = "TW", CountryName = "Taiwan"}, new WorldCountries { CountryCode = "TJ", CountryName = "Tajikistan"}, new WorldCountries { CountryCode = "TZ", CountryName = "Tanzania"}, new WorldCountries { CountryCode = "TH", CountryName = "Thailand"}, new WorldCountries { CountryCode = "TL", CountryName = "Timor-Leste"}, new WorldCountries { CountryCode = "TG", CountryName = "Togo"}, new WorldCountries { CountryCode = "TK", CountryName = "Tokelau"}, new WorldCountries { CountryCode = "TO", CountryName = "Tonga"}, new WorldCountries { CountryCode = "TT", CountryName = "Trinidad and Tobago"}, new WorldCountries { CountryCode = "TN", CountryName = "Tunisia"}, new WorldCountries { CountryCode = "TR", CountryName = "Turkey"}, new WorldCountries { CountryCode = "TM", CountryName = "Turkmenistan"}, new WorldCountries { CountryCode = "TC", CountryName = "Turks and Caicos Islands"}, new WorldCountries { CountryCode = "TV", CountryName = "Tuvalu"}, new WorldCountries { CountryCode = "UG", CountryName = "Uganda"}, new WorldCountries { CountryCode = "UA", CountryName = "Ukraine"}, new WorldCountries { CountryCode = "AE", CountryName = "United Arab Emirates"}, new WorldCountries { CountryCode = "GB", CountryName = "United Kingdom"}, new WorldCountries { CountryCode = "US", CountryName = "United States"}, new WorldCountries { CountryCode = "UM", CountryName = "United States Minor Outlying Islands"}, new WorldCountries { CountryCode = "UY", CountryName = "Uruguay"}, new WorldCountries { CountryCode = "UZ", CountryName = "Uzbekistan"}, new WorldCountries { CountryCode = "VU", CountryName = "Vanuatu"}, new WorldCountries { CountryCode = "VE", CountryName = "Venezuela"}, new WorldCountries { CountryCode = "VN", CountryName = "Viet Nam"}, new WorldCountries { CountryCode = "VG", CountryName = "British Virgin Islands"}, new WorldCountries { CountryCode = "VI", CountryName = "US Virgin Islands"}, new WorldCountries { CountryCode = "WF", CountryName = "Wallis and Futuna"}, new WorldCountries { CountryCode = "EH", CountryName = "Western Sahara"}, new WorldCountries { CountryCode = "YE", CountryName = "Yemen"}, new WorldCountries { CountryCode = "ZM", CountryName = "Zambia"}, new WorldCountries { CountryCode = "ZW", CountryName = "Zimbabwe"}, }; } }
دریافت کد کامل این پروژه
using (var ctx = new MyContext()) { InteractiveViews .SetViewCacheFactory( ctx, new FileViewCacheFactory(@"C:\MyViews.xml")); }
|
درخواست همزمان گزارش
.Generate(data => data.AsPdfStream(new MemoryStream()));
var reportData = new StudentPreRegistrationByInstitute().CreatePdfReport(model.InstituteId, fromDateTime, toDateTime); var streamOutput = reportData.PdfStreamOutput;
Cannot access a closed Stream.
public async Task<IHttpActionResult> LoginUserAsync(LoginUserBindingModel model) { var requestParams = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", model.Username), new KeyValuePair<string, string>("password", model.Password) }; var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams); using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:9577/"); client.DefaultRequestHeaders.Accept.Clear(); // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.PostAsync("/login", requestParamsFormUrlEncoded); if (response.StatusCode == HttpStatusCode.OK) { var responseString = await response.Content.ReadAsStringAsync(); var jsSerializer = new JavaScriptSerializer(); var responseData = jsSerializer.Deserialize<Dictionary<string, string>>(responseString); return Content(HttpStatusCode.OK, responseData); } else { return BadRequest(response.ToString()); } } }
ایجاد یک کانال و بات
بعد از ایجاد یک کانال public نیاز است یک بات ایجاد کنید. سپس این بات را به عنوان Administrator به کانال خود اضافه کنید.
ارسال پیام به کانال
var token="175287941:AAFcpXIIj1HuFlC5aB0QDBdWQBsTHqflkna"; // توکن خود را جایگزین کنید var channelId ="@ChannelName"; var message ="تست ارسال"; var uri = String.Format("https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}", Token, channelId, message); using (WebClient client = new WebClient()) { dynamic s = client.DownloadString(uri); }
ارسال فایل به کانال
public bool SendFileToChannel(byte[] file, string fileName) { var token="175287941:AAFcpXIIj1HuFlC5aB0QDBdWQBsTHqflkna"; // توکن خود را جایگزین کنید var channelId ="@ChannelName"; using (var client = new HttpClient()) { var uri = String.Format("https://api.telegram.org/bot{0}/sendDocument?chat_id={1}", Token, channelId ); using (var multipartFormDataContent = new MultipartFormDataContent()) { var streamContent = new StreamContent(new MemoryStream(file)); streamContent.Headers.Add("Content-Type", "application/octet-stream"); streamContent.Headers.Add("Content-Disposition", "form-data; name=\"document\"; filename=\"" + fileName + "\""); multipartFormDataContent.Add(streamContent, "file", fileName); using (var message = client.PostAsync(uri, multipartFormDataContent)) { var contentString = message.Result.Content.ReadAsStringAsync(); } } } return true; }
طریقه فراخوانی تابع ارسال فایل
string path = @"c:\myFile.txt"; // All File Allowed : pdf, mp3, jpg ,... string fileName = Path.GetFileName(path); byte[] file = System.IO.File.ReadAllBytes(path); SendFileToChannel(file, fileName);
ارسال پیام به یک کانال private
برای ارسال پیام به یک کانال خصوصی ابتدا باید کانال عمومی داشته باشید. در تابع ارسال پیام به یک کانال تلگرام، متغیر uri هنگام اجرا دارای مقدار شده و شما میتوانید این آدرس را در مرورگر وارد کنید. اتفاقی که میافتد این است که ارسال به کانال انجام شده و نتیجهی آن روی صفحه ظاهر میگردد.
var uri = String.Format("https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}", Token, channelId, message);
استفاده از DataAnnotations , dynamic column
public IPdfReportData CreatePdfReport(string title) { if (title=="" || title==null) { title = "گذارش"; } return new PdfReport().DocumentPreferences(doc => { doc.RunDirection(PdfRunDirection.RightToLeft); doc.Orientation(PageOrientation.Portrait); doc.PageSize(PdfPageSize.A4); doc.DocumentMetadata(new DocumentMetadata { Author = "Vahid", Application = "PdfRpt", Keywords = "Test", Subject = "Test Rpt", Title = "Test" }); }) .DefaultFonts(fonts => { fonts.Path(AppPath.ApplicationPath + "\\fonts\\BNazanin.ttf", Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\verdana.ttf"); }) .PagesFooter(footer => { footer.DefaultFooter(printDate: DateTime.Now.ToString("MM/dd/yyyy")); }) .PagesHeader(header => { header.DefaultHeader(defaultHeader => { // defaultHeader.ImagePath(AppPath.ApplicationPath + "\\Images\\01.png"); defaultHeader.Message(title); }); }) .MainTableTemplate(template => { template.BasicTemplate(BasicTemplate.SilverTemplate); }) .MainTablePreferences(table => { table.ColumnsWidthsType(TableColumnWidthType.Relative); }) .MainTableDataSource(dataSource => { Cash.Models.ApplicationDbContext db = new Models.ApplicationDbContext(); var listOfRows = db.Users.Join( db.CheckOuts, u => u.Id, c => c.ApplicationUserID, (u, c) => new { u.FName, u.Lname, u.NationalCode, c.Creditor, c.Debtor, c.Decsription } ).Where(x => x.Creditor != 0).ToList(); dataSource.AnonymousTypeList(listOfRows); }) .MainTableSummarySettings(summary => { summary.OverallSummarySettings("جمع کل"); summary.PreviousPageSummarySettings("نقل از صفحه قبل"); summary.PageSummarySettings("جمع صفحه"); }) .MainTableAdHocColumnsConventions(adHocColumns => { //We want sum of the int columns adHocColumns.AddTypeAggregateFunction( typeof(Int64), new AggregateProvider(AggregateFunction.Sum) { DisplayFormatFormula = obj => obj == null ? string.Empty : string.Format("{0:n0}", obj) }); adHocColumns.AddTypeAggregateFunction( typeof(Decimal), new AggregateProvider(AggregateFunction.Sum) { DisplayFormatFormula = obj => obj == null ? string.Empty : string.Format("{0:n0}", obj) }); //We want to dispaly all of the dateTimes as ShamsiDateTime adHocColumns.AddTypeDisplayFormatFormula( typeof(DateTime), data => { return PersianDate.ToPersianDateTime((DateTime)data); } ); adHocColumns.ShowRowNumberColumn(true); adHocColumns.RowNumberColumnCaption("ردیف"); }) .MainTableEvents(events => { events.DataSourceIsEmpty(message: "هیچ اطلاعاتی موجود نیست"); }) .Export(export => { export.ToExcel(); export.ToXml(); }) .Generate(data => data.AsPdfFile(AppPath.ApplicationPath + "\\Pdf\\AdHocColumnsSampleRpt.pdf")); }
مدل برنامه و نیازمندیهای اعتبارسنجی آن
namespace jqGrid08.Models { public class User { public int Id { set; get; } public string Name { set; get; } public string Email { set; get; } public string Password { set; get; } public string SiteUrl { set; get; } } }
- نام کاربر به صورت اجباری وارد شود و همچنین بین 3 تا 40 حرف باشد.
- همچنین نام کاربر نباید بر اساس اطلاعات موجود در بانک اطلاعاتی، تکراری وارد شود.
- ورود ایمیل شخص اجباری است؛ به علاوه فرمت آن نیز باید با یک ایمیل واقعی تطابق داشته باشد.
- ایمیل وارد شدهی یک کاربر جدید نیز نباید تکراری بوده و پیشتر توسط کاربر دیگری وارد شده باشد.
- ورود کلمهی عبور در حالت ثبت اطلاعات اجباری است؛ اما در حالت ویرایش اطلاعات خیر (از کلمهی عبور موجود در این حالت استفاده خواهد شد).
- ورود آدرس سایت کاربر اجباری بوده و همچنین فرمت آدرس وارد شده نیز باید معتبر باشد.
اعتبار سنجی سمت سرور و سمت کلاینت نام کاربر
colModel: [ { name: '@(StronglyTyped.PropertyName<User>(x => x.Name))', index: '@(StronglyTyped.PropertyName<User>(x => x.Name))', align: 'right', width: 150, editable: true, edittype: 'text', editoptions: { maxlength: 40 }, editrules: { required: true, custom: true, custom_func: function (value, colname) { if (!value) return [false, "لطفا نامی را وارد کنید"]; if (value.length < 3 || value.length > 40) return [false, colname + " باید بین 3 تا 40 حرف باشد"]; else return [true, ""]; } } }, ],
خروجی این متد یک آرایه دو عضوی است. اگر عضو اول آن true باشد، یعنی اعتبارسنجی موفقیت آمیز بودهاست؛ اگر خیر، عضو دوم آرایه، پیامی است که به کاربر نمایش داده خواهد شد.
تا اینجا کار اعتبارسنجی سمت کاربر به پایان میرسد. اما نیاز است در سمت سرور نیز بررسی شود که آیا نام وارد شده تکراری است یا خیر. برای این منظور تنها کافی است رویداد afterSubmit حالتهای Add و Edit را بررسی کنیم:
$('#list').jqGrid({ // ... }).navGrid( '#pager', //enabling buttons { add: true, del: true, edit: true, search: false }, //edit option { afterSubmit: showServerSideErrors }, //add options { afterSubmit: showServerSideErrors }, //delete options { }); }); function showServerSideErrors(response, postdata) { var result = $.parseJSON(response.responseText); if (result.success === false) { //نمایش خطای اعتبار سنجی سمت سرور پس از ویرایش یا افزودن //و همچنین جلوگیری از ثبت نهایی فرم return [false, result.message, result.id]; } return [true, "", result.id]; }
[HttpPost] public ActionResult AddUser(User postData) { //todo: Add user to repository if (postData == null) return Json(new { success = false, message = "اطلاعات دریافتی خالی است" }, JsonRequestBehavior.AllowGet); if (_usersInMemoryDataSource.Any( user => user.Name.Equals(postData.Name, StringComparison.InvariantCultureIgnoreCase))) { return Json(new { success = false, message = "نام کاربر تکراری است" }, JsonRequestBehavior.AllowGet); } if (_usersInMemoryDataSource.Any( user => user.Email.Equals(postData.Email, StringComparison.InvariantCultureIgnoreCase))) { return Json(new { success = false, message = "آدرس ایمیل کاربر تکراری است" }, JsonRequestBehavior.AllowGet); } postData.Id = _usersInMemoryDataSource.LastOrDefault() == null ? 1 : _usersInMemoryDataSource.Last().Id + 1; _usersInMemoryDataSource.Add(postData); return Json(new { id = postData.Id, success = true }, JsonRequestBehavior.AllowGet); }
خروجی روال رویدادگردان afterSubmit نیز بسیار شبیه است به حالت اعتبارسنجی سفارشی یک ستون. اگر عضو اول آرایه بازگشت داده شده توسط آن false باشد، یعنی اعتبارسنجی سمت سرور، با شکست مواجه شده و در این حالت از عضو دوم آرایه برای نمایش پیام خطای بازگشت داده شده از طرف سرور استفاده خواهد شد.
اعتبار سنجی ایمیل کاربر
colModel: [ { name: '@(StronglyTyped.PropertyName<User>(x => x.Email))', index: '@(StronglyTyped.PropertyName<User>(x => x.Email))', align: 'center', width: 150, editable: true, edittype: 'text', editoptions: { maxlength: 250, dir: 'ltr' }, editrules: { required: true, email: true }, formatter: 'email' }, ],
مطابق نیازمندیهای اعتبارسنجی پروژه، ایمیل وارد شده نیز نباید تکراری باشد. این مورد نیز توسط خروجی روال رویدادگردان afterSubmit که پیشتر توضیح داده شده، مدیریت میشود.
اعتبار سنجی کلمه عبور کاربر
colModel: [ { name: '@(StronglyTyped.PropertyName<User>(x => x.Password))', index: '@(StronglyTyped.PropertyName<User>(x => x.Password))', align: 'center', width: 70, editable: true, edittype: 'password', editoptions: { maxlength: 10, dir: 'ltr' }, editrules: { //required: true ---> در این حالت خاص قابل استفاده نیست //در حالت ویرایش رکورد، ورود کلمه عبور اختیاری است //در حالت افزودن رکورد، ورود کلمه عبور اجباری است } }, ],
برای این منظور تنها کافی است از روال رویدادگردان beforeSubmit استفاده کرد:
$('#list').jqGrid({ // ... }).navGrid( '#pager', //enabling buttons { add: true, del: true, edit: true, search: false }, //edit option { /*, beforeSubmit: function (posdata, obj) { //در حالت ویرایش رکورد، ورود کلمه عبور اختیاری است return [true, ""]; }*/ }, //add options { beforeSubmit: function (postdata, obj) { //در حالت افزودن رکورد، ورود کلمه عبور اجباری است if (postdata.Password == null || postdata.Password == "" || postdata.Password == undefined) return [false, "لطفا کلمه عبور را وارد کنید"]; return [true, ""]; } }, //delete options { }); });
اعتبار سنجی آدرس سایت کاربر
colModel: [ { name: '@(StronglyTyped.PropertyName<User>(x => x.SiteUrl))', index: '@(StronglyTyped.PropertyName<User>(x => x.SiteUrl))', align: 'center', width: 150, editable: true, edittype: 'text', editoptions: { maxlength: 1000, dir: 'ltr' }, editrules: { required: true, url: true }, formatter: function (cellvalue, options, rowObject) { return "<a href='" + cellvalue + "' >" + cellvalue + "</a>"; }, unformat: function (cellvalue, options, cell) { return $('a', cell).attr('href'); } }, ],
کدهای کامل این مثال را از اینجا میتوانید دریافت کنید
jqGrid08.zip