Wednesday, December 6, 2017

Public JSON APIs for use in web Development



https://github.com/toddmotto/public-apis      -->> (Thanks, Toddmotto :))

https://github.com/abhishekbanthia/Public-APIs

I love this one for demos: https://jsonplaceholder.typicode.com/

Thursday, November 16, 2017

SQL Server, Add New Login as sysadmin without Management Studio (SSMS)

How to Control MS SQL Server  without Management Studio (SSMS) :
For E.g:
We need to create new user account and we do not have SSMS installed on the server, for a quick Solution we did the following :

1- Prepare our SQL script in txt file :
--------------- Script.txt --------------------
USE [master]
GO
CREATE LOGIN [nady] WITH PASSWORD=N'123', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
EXEC master..sp_addsrvrolemember @loginame = N'nady', @rolename = N'sysadmin'
GO
------------------------------------------------

2- Prepare Command :
--------------- CMD.txt --------------------
sqlcmd -S dpqdevecom01 -i C:\nady\Script.txt -o C:\nady\Exec_Output.txt
------------------------------------------------

3- Open Windows command line, CMD ( Windows + R) then Paste your Command Script :) .




Tuesday, October 10, 2017

.net Core HTTP Error 405.0 - Method Not Allowed

When you try to do PUT and DELETE request using .net Core you get  "HTTP Error 405.0 - Method Not Allowed",

The solution is :
The WebDAVModule set PUT and DELETE request methods disabled by default. so you should disable it.

inside your Web.config :

  <system.webServer>   
    <modules runAllManagedModulesForAllRequests="false">
          <remove name="WebDAVModule" />
    </modules>
  </system.webServer>

Thursday, October 5, 2017

.Net Core 2 How to Send an Email using HTML Physical File System as a Template & SmtpClient.

.Net Core 2 How to Send an Email using HTML Physical File System as a Template & SmtpClient.

From .NET Core V2.0 you can use your old famous friend "SmtpClient", However, this example will Show you: How to send an email using HTML physical file system as a template.

You can find the project Github rep here: https://github.com/naadydev/Dotnet_Core_HTML_File_EMail_Template 

hope you find it useful for you (: naadydev@gmail.com 

Tuesday, October 3, 2017

.net Core application path & Information

Try your self the following Code to get the physical Application Directory path and the assembly information:



Monday, September 25, 2017

VS 2017 Detected package downgrade: NETStandard.Library from 1.6.1 to 1.6.0.

Problem :
VS 2017 Detected package downgrade: NETStandard.Library from 1.6.1 to 1.6.0.
And when you try to change the target framework using UI, you can't,
Simply :
Edit the ".csproj" file by changing the package version, then recompile the project:
<PropertyGroup>
  <NetStandardImplicitPackageVersion>1.6.1</NetStandardImplicitPackageVersion>
</PropertyGroup>

Wednesday, August 16, 2017

.Net SHA256 Hash Algorithm

The following function enables you to return SHA256 Hashed string with/without salt key :

public string GetSHA256String(string stringTobeHashed, string salt = null)
        {
            stringTobeHashed = !string.IsNullOrEmpty(salt) ? string.Format("{0}{1}", stringTobeHashed, salt) : stringTobeHashed;
            // ----------------- Encoding --------------------           
            byte[] sha256Bytes = Encoding.Default.GetBytes(stringTobeHashed);
            // -----------------------------------------------

            // ----------------- Create SHA256 ---------------
            SHA256 sha256 = SHA256Managed.Create();
            byte[] hashValue = sha256.ComputeHash(sha256Bytes);
            // -----------------------------------------------

            // ----------------- Hash Value String -----------
            var sha256Str = BitConverter.ToString(hashValue).Replace("-", "");

            // OR -> Convert.ToBase64String(sha256Str); 
            // OR: 
            //string sha256Str = string.Empty;
            //for (int i = 0; i < hashValue.Length; i++)
            //{
            // sha256Str += hashValue[i].ToString("X"); // X -> mean format output to Hexadecimal                                                         
            //}
            // -----------------------------------------------           
            return sha256Str;
        }

Tuesday, August 15, 2017

.Net Core Web App hang on Startup ( IIS Express in Visual Studio 2017 )

.Net Core Web App hang on Startup  ( IIS Express in Visual Studio 2017 )

Solution :
1- Installing "Microsoft.AspNetCore.Server.IISIntegration package"
2- In "Program.cs" file Add :

var host = new WebHostBuilder() .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration() // <<<===== Our line 
    .UseStartup<Startup>()
    .Build();

Monday, June 26, 2017

WPF How To Print & Preview DataTable (Open Source Utility Class)

Lately, we encounter a situation that we develop WPF App and we need to print datatable that come from SQLite database.
So, I develop WPF generic utility class that can help to Print & Print Preview Datatable.

https://github.com/naadydev/WPF-Print-Preview-DataTable

Happy Coding,
NADY

Monday, May 1, 2017

How to : Asp.Net Core Resource Files in Separate Project / DLL

About the Post:
In this post, we will show how to consume Asp.Net Core Resource Files from a Separate Project / DLL, We will use Web API Core as an example.

Why :
 I love software design "Separation Of Concerns" concept. and recently we develop a web API contains many resources so I tried to decouple the resources files into a separate project.
Unfortunately, I can't found much resources talking about this matter at the moment, I guess because the .Net Core still in earlier stages. However, I'm writing this post to let you know how to do it.

Solution Steps:
1- Create New .Net Core Class Library project Call it "MyApp.Resources.cs".
2- From Nuget console install package: > Install-Package Microsoft.Extensions.Localization
3- Add New Folder named "Resources".
4- Inside "Resources" Folder add the following resources files from VS Add new item resources file:
     - Add All supported Language you need, here we will support Arabic & English,
                - SharedResources.resx
                - SharedResources.ar-SA.resx
                - SharedResources.en-US.resx


5- Create New Interface named "AppResource.cs": 

namespace MyApp.Resources
{
    public interface IAppResource
    {
        string GetResource(string key);
    }
}
--------------------------------------------------------------------

6- Create New Class library file, named "SharedResources.cs" that implement  our IAppResource interface:

namespace MyApp.Resources
{
    public class SharedResources : IAppResource
    {
        private IStringLocalizer<SharedResources> _localizer;
        public SharedResources(IStringLocalizer<SharedResources> localizer)
        {
            _localizer = localizer;
        }

        public string GetResource(string key)
        {
            return _localizer[key];
        }
    }
}
--------------------------------------------------------------------

7- Create New Web API Core Project From VS.

8- In the Project Startup.cs file inside  -> ConfigureServices :

// Firstly: Configure our Localisation middleware
services.AddLocalization(
                opts =>
                {
                    opts.ResourcesPath = "Resources";
                }
                );

            services.Configure<RequestLocalizationOptions>(
           opts =>
           {
               var supportedCultures = new List<CultureInfo>
               {
                new CultureInfo("en-US"),
                new CultureInfo("en"),
                new CultureInfo("ar-SA"),
                new CultureInfo("ar")                
               };
               opts.DefaultRequestCulture = new RequestCulture("ar-SA");             
               opts.SupportedCultures = supportedCultures;              
               opts.SupportedUICultures = supportedCultures;
           });
            // --------------
// Secondly: register our shared resources service for DI 
            services.AddSingleton<IAppResource, SharedResources>();
--------------------------------------------------------------------

9- Inside web API project Add new Controller named "LocalizationTestController":

       private readonly IAppResource _sharedLocalizer;
        public LocalizationTestController(IAppResource sharedLocalizer)
        {
            _sharedLocalizer = sharedLocalizer;
        }
       
        [HttpGet]
        public string Get()
        {
            string result = _sharedLocalizer.GetResource("Hi");
            return result;
        }


--------------------------------------------------------------------

10-  now try your API request:
api/LocalizationTest 
api/LocalizationTest/?culture=ar-SA




Wednesday, April 12, 2017

How to install VS 2017 offline Or create VS 2017 Iso

How to make an offline installer for VS 2017 and update it in the future:

Download VS.exe the edition of Visual Studio that you want from :
https://www.visualstudio.com/downloads/

Install Offline Command:
vs_community.exe --layout C:\VS2017Offline --lang en-US

Update Offline files:
vs_community.exe --update

Reference :
https://docs.microsoft.com/en-us/visualstudio/install/create-an-offline-installation-of-visual-studio

Wednesday, February 22, 2017

Check out my jTLine jQuery plugin, that create Horizontal Timeline


jTLine

jQuery plugin, that create Horizontal Timeline,
Build upon the fantastic "codyhouse" article : https://codyhouse.co/gem/horizontal-timeline.

https://naadydev.github.io/jTLine/ 

Tuesday, February 14, 2017

Our feedback after using : Angular 2, Typescript, .Net Core Web Api V 1.0.1, Entity framework Core 1.1.0 (Code First)

Intro:
This blog post will enplane our feedback and lesson learned after completing our latest project (First Stage) using:
Angular 2 , Typescript , .Net Core Web API V 1.0.1 And Entity framework Core 1.1.0 (Code First)



The First ChapterFlashback & Fears:
- The situation before the project few months ago,
- No one in the team have any experience in that technologies.
- .Net Core still in earlier stage and not mature enough “As we thought”.

Chapter 2: Taking the Risk Decision
As most of IT people we like to know and follow the new technologies, so we did self-study as preparation without our manager know J .
After we got some self-confidence we encouraged to take the decision and speak to the manager After short negotiation with our manager we got the approval to do the next project using the new awesome tech.

Chapter 3: Technical Challenges
We encountered many challenges during the project specially the kickoff initial stages like:
- How to implement JWT using mixed mode Active directory & Forms authentication.
- How we will set our Solution Architecture.
- Because Our UI/UX team decided to use payed template that uses Many jQuery Plugins So:
o   How we will use jQuery plugins inside Angular 2 App and fixing the problems, I think I will write separated post regarding this because we encountered many problems for each plugin
o   “don’t worry after we get know how we deal with jQuery inside Ng2 app it’s fun now”.

- IIS hosting NG2 app and routing.
- Other Usual problems here and there no fancy things.

Chapter 4: Our Solution Architecture & Tools

- We are using our customized DDD “Domain-Driven Design” As following images:


























- Visual Studio Team Services as source control and project management.
- Our Front-end Just Angular 2 App talking to .Net Core Web API.
o   We use “Webpack Angular Starter kit “by Angular class team @AngularClass    
https://twitter.com/angularclass , you can found it here https://github.com/AngularClass/angular2-webpack-starter

- Using Visual Studio Code for frontend solution
- Typescript 
- WebPack as module bundler included in the starter Kit @AngularClass you can read more here https://angular.io/docs/ts/latest/guide/webpack.html .

- Using some awesome vs code extensions:


Chapter 5: Our feedback/feelings after finish the first stage:
-        We fall in love with this awesome technology combination,
-         Hmm but why?
o   Angular 2 Side:
§  It’s totally framework not just another js frontend library “its good choice for large projects”, Everyone know what to do in specific steps and architecture defined by angular e.g. inject service, routing, etc.
§  Single page App is totally amazing “CoOoool”.
§  Using Typescript make you feel strong J in frontend development.   
§   Love using VS Code with angular 2.
§  Angular 2 lifecycle-hooks help a lot specially in solving jQuery issues.
§  We like angular 2 Observables and async pipes concepts.

o    .Net Core Side:
§  We like .Net Core remarkable performance.
§  Entity framework core “Code First”: no much changes that makes you spend long time to learn
§  With .Net Core you feel control over everything, inject what you need only not all framework, control lifecycle, add middleware interceptors etc...


 Finally I hope this will help someone. 
@naadydev
naadydev@gmail.com

Thursday, February 2, 2017

Angular 2 , Web API Core & Entity Framework Core Disable Cache / json Caching

Scenario :
We encounter problem that when we edit entity and try to view its details or edit it again we get the old values.
So the response json result is cached !!!

We are using  Awesome .net Web API Core + Entity Framework Core + Angular 2 :) "Amazing right"
So how we disable the caching / response json result !!!

- First i think about response header Cache related headers :
So i modified my Web API Core Service to disable Cache like the following:













- You can achieve this by adding this to your Controller action or over all Controller:
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]







- Guess what :) !!! Still not working hahaa

- After that i think from Angular perspective ,So i added timestamp to the current http request like this :








- Guess what :) !!! Also Still not working hmmm ok nice try.

- So i tried to think again from the perspective of EF Core , And add the ".AsNoTracking()" at the end of my query to disable EF cacheing .









- Guess what :) !!! WOrrrrrking Yaaaaaaaaaa :)


Thanks and i hope this will help someone over the univers


naadydev@gmail.com
blog.mohnady.com






Wednesday, February 1, 2017

Angular 2 Change Date Format using code, from .ts code file.

Scenario :
I need to change the date format from my .ts code file .

Solution :
We take advantage of , already exists angular 2 "DatePipe" , like the following :

// ----------- Inside My Component Controller .ts file ----------------------

import {  DatePipe } from '@angular/common';

@Component({
   .....
    providers: [DatePipe]
})


constructor(
        private _datePipe: DatePipe,
.....

myTestFunc(){
           let datePipeTest = this._datePipe.transform(this.task.scheduledStart, 'dd/MM/yyyy');
       consol.log(datePipeTest);
}




Tuesday, January 10, 2017

Angular 2 Router On Windows IIS 404 - File or directory not found Solution


Scenario:
When we try to host our Angular 2 on windows IIS , we encounter problem in Angular 2 Routing,
If you try to refresh the same page, or navigate directly to the page using the direct URL ,

You get the error: “ 404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable. “

Resolution Steps:
        -  Install IIS URL Rewrite Module on your server from here:                          

2      - Configure your Web App:
-  Add Web.config if you don’t have one: 
-        Note: If you use .net or .net core app as angular app you can skip this step (because you already have one).
-        Create Web.config file then add the following,

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>



Finally Test your App And happy coding J .