کدهای یک دایرکتیو سفارشی نمایش و یا مخفی سازی قسمتهای مختلف صفحه را بر اساس سطوح دسترسی کاربر جاری، در IsVisibleForAuthUserDirective مشاهده کردید. روش دیگر انجام اینکار، نوشتن یک دایرکتیو ساختاری شبیه به ngIf توکار خود Angular است. کاری که ngIf انجام میدهد، مخفی کردن یک المان در صفحه نیست؛ بلکه کل آنرا از DOM حذف میکند.
نکتهی اصلی پیاده سازی یک دایرکتیو ساختاری
اگر به سازندهی IsVisibleForAuthUserDirective دقت کنید، تزریق وابستگی ElementRef را داریم:
@Directive({ selector: "[isVisibleForAuthUser]" }) export class IsVisibleForAuthUserDirective implements OnInit, OnDestroy { constructor(private elem: ElementRef, private authService: AuthService) { }
برای ایجاد یک دایرکتیور ساختاری، نیاز است از تزریق TemplateRef و ViewContainerRef استفاده کرد:
@Directive({ selector: "[hasAuthUserViewPermission]" }) export class HasAuthUserViewPermissionDirective implements OnInit, OnDestroy { constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private authService: AuthService ) { }
<div *hasAuthUserViewPermission="['Admin','User']"> *hasAuthUserViewPermission="['Admin','User']" </div>
this.viewContainer.createEmbeddedView(this.templateRef);
this.viewContainer.clear();
اگر این نکات را کنار هم قرار دهیم و کدهای IsVisibleForAuthUserDirective فوق را بر این اساس اصلاح کنیم، به قطعه کد زیر میرسیم:
import { Directive, Input, OnDestroy, OnInit, TemplateRef, ViewContainerRef } from "@angular/core"; import { Subscription } from "rxjs/Subscription"; import { AuthService } from "./../../core/services/auth.service"; @Directive({ selector: "[hasAuthUserViewPermission]" }) export class HasAuthUserViewPermissionDirective implements OnInit, OnDestroy { private isVisible = false; private requiredRoles: string[] | null = null; private subscription: Subscription | null = null; @Input() set hasAuthUserViewPermission(roles: string[] | null) { this.requiredRoles = roles; } // Note, if you don't place the * in front, you won't be able to inject the TemplateRef<any> or ViewContainerRef into your directive. constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef, private authService: AuthService ) { } ngOnInit() { this.subscription = this.authService.authStatus$.subscribe(status => this.changeVisibility(status)); this.changeVisibility(this.authService.isAuthUserLoggedIn()); } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } private changeVisibility(status: boolean) { const isInRoles = !this.requiredRoles ? true : this.authService.isAuthUserInRoles(this.requiredRoles); if (isInRoles && status) { if (!this.isVisible) { this.viewContainer.createEmbeddedView(this.templateRef); this.isVisible = true; } } else { this.isVisible = false; this.viewContainer.clear(); } } }
سپس تعریف آنرا به قسمتهای declarations و exports مربوط به SharedModule اضافه میکنیم:
import { HasAuthUserViewPermissionDirective } from "./directives/has-auth-user-view-permission.directive"; @NgModule({ declarations: [ HasAuthUserViewPermissionDirective ], exports: [ HasAuthUserViewPermissionDirective ] }) export class SharedModule {}
اکنون ماژول Dashboard برای استفادهی از این امکانات تنها کافی است SharedModule را دریافت کند (یا هر ماژول دیگری نیز به همین ترتیب است):
import { SharedModule } from "../shared/shared.module"; @NgModule({ imports: [ SharedModule ] }) export class DashboardModule { }
پس از آن برای مخفی سازی یک المان از دید کاربران وارد نشدهی به سیستم، فقط کافی است دایرکتیو ساختاری hasAuthUserViewPermission را به المان اعمال کنیم:
<div *hasAuthUserViewPermission=""> *hasAuthUserViewPermission="" </div>
<div *hasAuthUserViewPermission="['Admin','User']"> *hasAuthUserViewPermission="['Admin','User']" </div>
خلاصهی این تغییرات به کدهای نهایی این سری اعمال شدهاند.
سری آموزشی Blazor C# Tutorials
Blazor C# Tutorials
30 videos
In this playlist, I am going through all the fundamentals and sharing my journey to be a full stack Blazor developer. This is the future of web development in ASP.NET world. If you want to learn Blazor this is the best place to start.
1. Build Your First App - EP01
2. Getting Started - EP02
3. #Routing - EP03
4. Dependency #Injection - EP04
5. Forms & #Validations - EP05
6. JavaScript #Interop - EP06
7. #Razor #Components | Re-usability - EP07
8. Razor Components | #Lifecycle Methods - EP08
9. Razor Component #Libraries - EP09
10. Call #REST #API - #CRUD Methods - EP10
11. #Authentication | Out of the box- EP11
12. Custom AuthenticationStateProvider - EP12
13. Layouts | Login Pages - EP13
14. HttpClient | Login User
15. IHttpClientFactory | Login User
16. Sending JWT token & Request Middleware
17. Handling Exceptions
public void MsInteropReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText) { object matchCase = false; object matchWholeWord = true; object matchWildCards = false; object matchSoundsLike = false; object matchAllWordForms = false; object forward = true; object format = false; object matchKashida = false; object matchDiacritics = false; object matchAlefHamza = false; object matchControl = false; object read_only = false; object visible = true; object replace = 2; object wrap = 1; //execute find and replace doc.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl); }
private static void MsInteropReplace2() { var doc = new Microsoft.Office.Interop.Word.Application().Documents.Open(@"D:\temp\te1.docx"); doc.Content.Find.Execute("@levelOrder", false, true, false, false, false, true, 1, false, "12345", 2, false, false, false, false); object missing = System.Reflection.Missing.Value; doc.SaveAs(@"D:\temp\out.docx", ref missing, ref missing, ref missing, ref missing , ref missing, ref missing, ref missing, ref missing, ref missing, ref missing , ref missing, ref missing, ref missing, ref missing, ref missing); }
که هر دو مورد را در stackoverflow میتوانید پیدا کنید. به شخصه از این مورد برای replace کردن مقادیر در یک فایل template.docx استفاده میکردم؛ ولی بعد از مدتی فهمیدم که Footerها و Header را نمیتواند پردازش کند. کد زیر در تمامی قسمتهایی که در یک فایل word میتوان متغیر تعریف کرد را گشته و عمل پر کردن مقادیر را بر روی فایل نمونه، انجام میدهد و شامل سه متد ذیل است:
private static void repAll() { object Missing = System.Reflection.Missing.Value; Application app = null; Microsoft.Office.Interop.Word.Document doc = null; try { app = new Microsoft.Office.Interop.Word.Application(); doc = app.Documents.Open(@"D:\temp\te1.docx", Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing); FindReplaceAnywhere(app, "@levelOrder", "محرمانه"); doc.SaveAs(@"D:\temp\out.docx", Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing); } finally { try { if (doc != null) ((Microsoft.Office.Interop.Word._Document)doc).Close(true, Missing, Missing); } finally { } if (app != null) ((Microsoft.Office.Interop.Word._Application)app).Quit(true, Missing, Missing); } } private static void searchAndReplaceInStory(Microsoft.Office.Interop.Word.Range rngStory, string strSearch, string strReplace) { rngStory.Find.ClearFormatting(); rngStory.Find.Replacement.ClearFormatting(); rngStory.Find.Text = strSearch; rngStory.Find.Replacement.Text = strReplace; rngStory.Find.Wrap = WdFindWrap.wdFindContinue; object Missing = System.Reflection.Missing.Value; object arg1 = Missing; // Find Pattern object arg2 = Missing; //MatchCase object arg3 = Missing; //MatchWholeWord object arg4 = Missing; //MatchWildcards object arg5 = Missing; //MatchSoundsLike object arg6 = Missing; //MatchAllWordForms object arg7 = Missing; //Forward object arg8 = Missing; //Wrap object arg9 = Missing; //Format object arg10 = Missing; //ReplaceWith object arg11 = WdReplace.wdReplaceAll; //Replace object arg12 = Missing; //MatchKashida object arg13 = Missing; //MatchDiacritics object arg14 = Missing; //MatchAlefHamza object arg15 = Missing; //MatchControl rngStory.Find.Execute(ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7, ref arg8, ref arg9, ref arg10, ref arg11, ref arg12, ref arg13, ref arg14, ref arg15); } // Main routine to find text and replace it, // var app = new Microsoft.Office.Interop.Word.Application(); public static void FindReplaceAnywhere(Microsoft.Office.Interop.Word.Application app, string findText, string replaceText) { // http://forums.asp.net/p/1501791/3739871.aspx var doc = app.ActiveDocument; // Fix the skipped blank Header/Footer problem // http://msdn.microsoft.com/en-us/library/aa211923(office.11).aspx Microsoft.Office.Interop.Word.WdStoryType lngJunk = doc.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.StoryType; // Iterate through all story types in the current document foreach (Microsoft.Office.Interop.Word.Range rngStory in doc.StoryRanges) { // Iterate through all linked stories var internalRangeStory = rngStory; do { searchAndReplaceInStory(internalRangeStory, findText, replaceText); try { // 6 , 7 , 8 , 9 , 10 , 11 -- http://msdn.microsoft.com/en-us/library/aa211923(office.11).aspx switch (internalRangeStory.StoryType) { case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesHeaderStory: // 6 case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory: // 7 case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesFooterStory: // 8 case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryFooterStory: // 9 case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageHeaderStory: // 10 case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageFooterStory: // 11 if (internalRangeStory.ShapeRange.Count > 0) { foreach (Microsoft.Office.Interop.Word.Shape oShp in internalRangeStory.ShapeRange) { if (oShp.TextFrame.HasText != 0) { searchAndReplaceInStory(oShp.TextFrame.TextRange, findText, replaceText); } } } break; default: break; } } catch { // On Error Resume Next } // ON ERROR GOTO 0 -- http://www.harding.edu/fmccown/vbnet_csharp_comparison.html // Get next linked story (if any) internalRangeStory = internalRangeStory.NextStoryRange; } while (internalRangeStory != null); // http://www.harding.edu/fmccown/vbnet_csharp_comparison.html } }
برای تهیه pdf نیز میتوانید به کد زیر مراجعه کنید:
public static void getFileDocxInPdf() { // Create a new Microsoft Word application object Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); // C# doesn't have optional arguments so we'll need a dummy value object oMissing = System.Reflection.Missing.Value; // Get list of Word files in specified directory DirectoryInfo dirInfo = new DirectoryInfo(@"D:\temp"); FileInfo[] wordFiles = dirInfo.GetFiles("*.docx"); word.Visible = false; word.ScreenUpdating = false; foreach (FileInfo wordFile in wordFiles) { // Cast as Object for word Open method Object filename = (Object)wordFile.FullName; // Use the dummy value as a placeholder for optional arguments Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); object outputFileName = wordFile.FullName.Replace(".docx", ".pdf"); object fileFormat = WdSaveFormat.wdFormatPDF; // Save document into PDF Format doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Close the Word document, but leave the Word application open. // doc has to be cast to type _Document so that it will find the // correct Close method. object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } // word has to be cast to type _Application so that it will find // the correct Quit method. ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null; }
استفاده از WebSocket در دات نت
تزریق وابستگیهای رایج ASP.NET MVC به برنامه
ioc.For<IIdentity>() .Use( () => (HttpContext.Current != null && HttpContext.Current.User != null) ? HttpContext.Current.User.Identity : null);