Showing posts with label asp.net. Show all posts
Showing posts with label asp.net. Show all posts

Monday 7 September 2020

Unit test c#: Create Fake Httpcontext to bypass Null exception for User object

 Microsoft Visual studio Test Framework


Requirement: Nuget package Moq 4.13.0.0 (or later)

Settings in visual studio: Menu->Tools->Options ->Debugging->General
Tick "Use Managed Compatibility Mode"

Code: (copied from stackoverflow)
Step 1: 
Create a new class FakeHttpContext and paste the below code. Change the Returns value to whatever user name you need.

public static class FakeHttpContext
    {
        public static void SetFakeContext(this Controller controller)
        {

            var httpContext = MakeFakeContext();
            ControllerContext context =
            new ControllerContext(
            new RequestContext(httpContext,
            new RouteData()), controller);
            controller.ControllerContext = context;
        }


        private static HttpContextBase MakeFakeContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();
            var user = new Mock<IPrincipal>();
            var identity = new Mock<IIdentity>();

            context.Setup(c => c.Request).Returns(request.Object);
            context.Setup(c => c.Response).Returns(response.Object);
            context.Setup(c => c.Session).Returns(session.Object);
            context.Setup(c => c.Server).Returns(server.Object);
            context.Setup(c => c.User).Returns(user.Object);
            user.Setup(c => c.Identity).Returns(identity.Object);
            identity.Setup(i => i.IsAuthenticated).Returns(true);
            identity.Setup(i => i.Name).Returns("sanjeeb");

            return context.Object;
        }
    }


Step 2: 
Initialize the Fakehttpcontext in test initialize function. 

FakeHttpContext.SetFakeContext(usersController);



Wednesday 5 August 2020

TFS -GIT CertGetCertificateChain trust error CERT_TRUST_IS_UNTRUSTED_ROOT


Problem 1)

2019-07-02T14:19:12.5157398Z fatal: unable to access 'https://tfssite.company.com/tfs/UK_ProjectCollection/SalesPortal/_git/SalesPortalWeb/': SSL certificate problem: unable to get local issuer certificate
2019-07-02T14:19:12.9764145Z ##[error]Git fetch failed with exit code: 128
2019-07-02T14:19:12.9861630Z ##[section]Finishing: Get Sources













In the TFS_Build Server or App server(if build and app server is in the same machine) >

run the script from this url: https://blog.sanjeebojha.com.np/2019/06/git-ssl-certificate-problem-unable-to.html

Once this is done, you should get another problem:

Problem 2)  CertGetCertificateChain trust error CERT_TRUST_IS_UNTRUSTED_ROOT

2019-07-02T14:24:57.1800199Z ##[command]git -c http.extraheader="AUTHORIZATION: bearer ***" fetch --tags --prune --progress --no-recurse-submodules origin
2019-07-02T14:24:57.4540146Z fatal: unable to access 'https://tfssite.company.com/tfs/UK_ProjectCollection/SalesPortal/_git/SalesPortalWeb/': schannel: CertGetCertificateChain trust error CERT_TRUST_IS_UNTRUSTED_ROOT
2019-07-02T14:24:57.5198064Z ##[error]Git fetch failed with exit code: 128

2019-07-02T14:24:57.5288511Z ##[section]Finishing: Get Sources


  











  1. Export the certificate public key to a file. The file is later required.
  2. Open the url "https://tfssite.company.com/tfs/projectcollection" in IE
  3. Click on the Lock icon in the browser address bar
  4. Select The Root level Certificate and Click View Certificate

Now Find the certificate file from GIT folder. 
normally it's inside GIT\usr\ssl\certs folder

  1. Copy the file to User folder
copy ca-bundle.trust.crt c:\Users\svc_tfs17_app

  1. Config Git to use trusted certificate using the crt file.  
    git config --global http.sslCAInfo c:\Users\svc_tfs17_app\ca-bundle.crt
  2. Convert the \n (Unix) to \r\n (Windows) so that it can be displayed by notepad editor correctly.
  3. Use the unix2dos open source software to convert \n to \r\n, or other notepad editor to replace \n to \r\n.
  1. Copy the content of tfs.cer from step o to ca-bundle.crt at the bottom of the file.

Done!

Output :


Entity Framework Core with Existing Database

Entity Framework Core only supports code first database aproach. 
To use existing database, we'll need to reverse Engineer Model from existing Database. 
  • Open Visual studio.
  • Menu > tools >Nuget Package Manager >
  • open PM Console
Note: All the tables in the database must have Primary key defined. else you'll get error like:
Unable to generate entity type for table 'dbo.xOrdersMBS'.
Unable to identify the primary key for table 'dbo.xActivePricesEPB'.
Unable to generate entity type for table 'dbo.xActivePricesEPB'.
Unable to identify the primary key for table 'dbo.xLeadTimePBOM'.
Unable to generate entity type for table 'dbo.xLeadTimePBOM'.


 In the console, run the below power shell commands:

Using Windows Authentication:
Scaffold-DbContext "Server=DatabaseServerAddress;Database=DatabaseName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f

Using SQL Account:
Scaffold-DbContext "data source=DatabaseServerAddress;initial catalog=DatabaseName;uid=UserName;pwd=Password;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f

Note: -f force create the files if the file exist in the folder Models.

Thursday 16 July 2020

Add nuget packages to Artifacts in Azure devops

download latest nuget.exe from the nuget site. (google it)

copy the nuget.exe in d: (any location is fine)

Use visual studio -> Package manager console. 
run the below command
D:\nuget.exe push -Source "IGTelerikFeed" -ApiKey az D:\Telerik.UI.for.AspNet.Core.2020.2.617.nupkg

[Note: It will ask Credential to connect to the devops when you press enter. ]

Thursday 2 July 2020

EntityFramework Insert error due to PrimaryKey



MyProject.Controllers.CurrencyCodesController Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
System.Data.Entity.Infrastructure.DbUpdateException: Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation. ---> System.Data.Entity.Core.UpdateException: Unable to update the EntitySet 'CurrencyCodes' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.


Scenario: 
The error occured while trying to insert the currencycodes entity to the database. 
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "cucCurrencyCode,cucDescription,cucMultiplier,cucRate,cucInUse")] CurrencyCode currencyCode)
{ if (ModelState.IsValid)
{ try
{ db.CurrencyCodes.Add(currencyCode);
db.SaveChanges();
}
 catch (Exception ex) {
log.Error(ex.Message, ex);
}
 return RedirectToAction("Index");
} return View(currencyCode);

}



Solution: 
1) Check Primary key in .edmx file.  In my case cucInUse was set as Entity key. I removed it.
2) Now Right click the .edmx file and click "Open with...". Select XML (text) Editor
3)  Find the element <EntitySet name = "CurrencyCodes"...>
4) Change store:Schema="dbo" => Schema="dbo"
5) delete element <DefiningQuery>
6) Clean the project. 
7) close Visual studio.
8) Open visual studio. Open the project. 
9) Clean and build the project. 
10) Run the application.

Friday 26 June 2020

Use log4net for all logging in c# application

Exception logging is hugely important within an application, not just to ensure we know when an error has occured but also to help use trace back the thread to help investigate where the error originated.
Our strategy is to use log4net for all our logging needs.
This page helps cover the follow areas
1. Setting up logging across the entire applications
2. Including 2 appenders so we can be notified when they occur and ensure a tracable debug log file is available.
Setting up your Applications for Logging
Reference log4net in your applications
in Global.asax under the start_application method include the following
    void Application_Start(object sender, EventArgs e)
    {
        // link up log4net configuration
        log4net.Config.XmlConfigurator.Configure();
    }
On the page where you wish to log information declare a new static variable in the class header
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Whenever you wish to now log an event in this class run one of the follow commands, ensure you include the exception when needed
log.Error("An unhandled exception occured", ex);
To ensure you catch all unhandled exceptions include the following in your Global.asax file. Remember to declare the log variable in the class too.
    void Application_Error(object sender, EventArgs e) 
    {
        // Code that runs when an unhandled error occurs
        // get last exception
        Exception ex = Server.GetLastError().GetBaseException();
        // log it
        log.Error("An unhandled exception occured", ex);
    }
Web.Config Settings
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
<log4net>
    <!-- The DebugFileAppender writes all messages to a log file-->
    <appender name="DebugFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="L:\[APPNAME]\Log.txt" /> <!-- These should be located on the "L" drive (if available) and stored under a folder named for the specific application -->      <datePattern value="'ApplicationLog.'yyyy-MM-dd'.txt'" />
      <staticLogFileName value="false" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>    <!-- The EmailAppender sends an email when something matches the filters-->
    <appender name="EmailAppender" type="log4net.Appender.SmtpAppender">
      <evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="DEBUG"/>
      </evaluator>
      <!--  The filters are processed in order:
            1) match the Inserted New User message
            2) match any WARN or higher messages
            3) reject everything else -->
      <filter type="log4net.Filter.StringMatchFilter">
        <stringToMatch value="Inserted a new user" />
        <acceptOnMatch value="true" />
      </filter>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="WARN" />
        <acceptOnMatch value="true" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />
      <!--  The SmtpAppender authenticates against the mail server, the buffersize of 10 provides 10 lines
            of context when an error happens. -->
      <subject value="[SEVERITY] [ENV] [APPNAME] - [EXCP_MSG]" />
      <to value="itteam@site.com" />
      <from value="noreply@site.com" />
      <smtpHost value="smtpmail.lu.sii.com" />
      <bufferSize value="10" />
      <lossy value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
      <applicationName value="MyApp" />


     <layout type="log4net.Layout.PatternLayout">


        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />


      </layout>


    </appender>

    <root>
      <!-- add other appenders here and the log messages will be sent to every listed appender -->
      <appender-ref ref="DebugFileAppender" />
      <appender-ref ref="EmailAppender" />
    </root>
  </log4net>

Generate SQL script from entity framework using powershell/visual studio

to run the below command , start PowerShell in visual studio. Select the database project. In PowerShell:   Script-Migration this command wi...