Convert Json to Class in C#

Convert Json to Class in C#


Here it is a sample code to convert json data into Class object.


namespace JsonToClass
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonInput = "{ username:'myName',password:'myPass'}";
 
            var data = JsonConvert.DeserializeObject<demo>(jsonInput);
        }
    }
 
    class demo
    {
        public string username { getset; }
        public string password { getset; }
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)

The transaction log for database 'dbname' is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

The transaction log for database 'dbname' is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases


Issue:
InnerException: System.Data.SqlClient.SqlException (0x80131904): The transaction log for database 'dbname' is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases


Analysys:

The issue says that the transaction log has reached its configured size or disk does not have sufficient space. , so we need to make space.


Solution 1:


Clear the log file and freeing disk space

Use [dbname]

Find log file name using below query and pass it in DBCC SHRINKFILE query 
Select * from sys.database_files

ALTER DATABASE [dbname] SET RECOVERY SIMPLE

DBCC SHRINKFILE ('dbname_Log', 1)

Solution 2:

Move log file on another drive

Please follow steps mentioned in below article,
http://anrorathod.blogspot.com/2018/02/how-to-move-or-change-datamdf-file-or.html


For more information you can refer, 

Troubleshoot a Full Transaction Log (SQL Server Error 9002)


https://docs.microsoft.com/en-us/sql/relational-databases/logs/troubleshoot-a-full-transaction-log-sql-server-error-9002?view=sql-server-2017

Hope this will help you and save your time.

Enjoy !!!

:)

GitExtension Settings

GitExtension Settings


 Many times I faced issue with git extensions setting, due to not proper settings it was not working properly. 

So I have listed out setting for git extension.


Editor = C:/Program Files (x86)/GitExtensions/GitExtensions.exe fileeditor
Mergetool = TortoiseMerge
Path to mergetool =  C:/Program Files/TortoiseSVN/bin/TortoiseMerge.exe
Mergetool
 command = 
C:/Program Files/TortoiseSVN/bin/TortoiseMerge.exe /base:"$BASE" /mine:"$LOCAL" /theirs:"$REMOTE" /merged:"$MERGED"
Difftool =  tmerge
Path to difftool =  C:/Program Files/TortoiseSVN/bin/TortoiseMerge.exe
Difftool command =  C:/Program Files/TortoiseSVN/bin/TortoiseMerge.exe "$LOCAL" "$REMOTE"


Hope this will help you and save your time.


Enjoy !!!

:)

Read Event Viewer logs using C#

Read Event Viewer logs using C#


 Below demonstrated code helps to read logs data from event viewer and stores in database using entity framework.

Database table

CREATE TABLE [dbo].[EventLogData](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [EventId] [nvarchar](10) NULL,
 [EventType] [nvarchar](50) NULL,
 [Site] [nvarchar](200) NULL,
 [Source] [nvarchar](500) NULL,
 [TimeGenerated] [datetime] NULL,
 [Message] [ntext] NULL,
 CONSTRAINT [PK__EventLog__3214EC07A20289BA] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Code


namespace EventLogsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            EventLog log = new EventLog("Application");
            var entries = log.Entries.Cast<EventLogEntry>()
                                     // .Where(x => x.InstanceId == 4624)
                                     .Select(x => new
                                     {
                                         x.EventID,
                                         x.EntryType,
                                         x.Site,
                                         x.Source,
                                         x.TimeGenerated,
                                         x.Message
                                     })
                                      .ToList();

            List<EventLogData> eventLogDatas = new List<EventLogData>();
            EventLogData eventLogData;

            Console.WriteLine("Total Entries : " + entries.Count.ToString());
            foreach (var item in entries)
            {
                eventLogData = new EventLogData()
                {
                    EventId = Convert.ToString(item.EventID),
                    EventType = Convert.ToString(item.EntryType),
                    Site = Convert.ToString(item.Site),
                    Source = item.Source,
                    TimeGenerated = item.TimeGenerated,
                    Message = item.Message
                };
                eventLogDatas.Add(eventLogData);
            }

            using (var db = new EventsEntities())
            {
                db.Database.ExecuteSqlCommand("TRUNCATE TABLE EventLogData");

                db.EventLogDatas.AddRange(eventLogDatas);
                db.SaveChanges();
            }


            Console.WriteLine("Process completed. Press any key to continue...");
            Console.Read();
        }
    }
}

Hope this will help you and save your time.

Enjoy !!!

:)

Mock unit testing

Mock unit testing 



Mock unit testing is very useful for developer, but my point of view its fake unit testing, its making us foolish.
Lets see how it is...

I have created on console application in visual studio and try to explain two cases as below...

Case1

Case1: I have created Case1 folder in "UnitTestCaseProject" and write below two classes. 

namespace UnitTestCaseProject.Case1
{
    public class checkEmployee
    {
        public virtual Boolean checkEmp()
        {
            throw new NotImplementedException();
            //return true;
        }
    }
}

namespace UnitTestCaseProject.Case1
{
    public class processEmployee
    {
        public bool insertEmployee(checkEmployee objtmp)
        {
            objtmp.checkEmp();
            return true;
        }
    }
}

Case2

I have created Case2 folder in "UnitTestCaseProject" and write below three classes.

namespace UnitTestCaseProject.Case2
{
    public interface IGetDataRepository
    {
        string GetNameById(int id);
    }
}

namespace UnitTestCaseProject.Case2
{
    public class EmployeeRepository : IGetDataRepository
    {
        public string GetNameById(int id)
        {
            string name;
            if (id == 1)
            {
                name = "Excellent";
            }
            else if (id == 2)
            {
                name = "Expert";
            }
            else
            {
                name = "Not Found";
            }
            return name;
        }
    }
}

namespace UnitTestCaseProject.Case2
{
    public class Implementation1
    {
        private readonly IGetDataRepository _data;
        public Implementation1(IGetDataRepository data)
        {
            _data = data;
        }

        public string GetNameById(int id)
        {
            return _data.GetNameById(id);
        }
    }
}


Test Project

Now, I have added new test project in solution with name "UnitTestCaseProject.Test" and write unit test cases for above two cases.


I have installed "Moq" packages using manage nuget packages...

namespace UnitTestCaseProject.Test
{
    [TestClass]
    public class Case1Test
    {
        [TestMethod]
        public void insertEmployeeTestSuccess()
        {
            Mock<checkEmployee> chk = new Mock<checkEmployee>();
            chk.Setup(x => x.checkEmp()).Returns(true);

            processEmployee obje = new processEmployee();
            Assert.AreEqual(obje.insertEmployee(chk.Object), true);
        }
    }
}


namespace UnitTestCaseProject.Test
{
    [TestClass]
    public class Cast2Test
    {
        [TestMethod]
        public void TestMethod2()
        {
            var mock = new Mock<IGetDataRepository>();
            mock.Setup(p => p.GetNameById(1)).Returns("demo");
            Implementation1 home = new Implementation1(mock.Object);
            string result = home.GetNameById(1);
            Assert.AreEqual("demo", result);
        }
    }
}


While I run the above two unit test cases, it gives me success result.


Real Implementation and usage

Now, below code is actual implementation in our project "UnitTestCaseProject".

namespace UnitTestCaseProject
{
    class Program
    {
        static void Main(string[] args)
        {
            processEmployee processEmployee = new processEmployee();
            checkEmployee checkEmployee = new checkEmployee();
            var result = processEmployee.insertEmployee(checkEmployee);
            Console.WriteLine(result);
        }
    }
}



Now, if I run the project it gives me an error in actual usage, that should not give me any error while I already tested with unit test cases. So, you can see that it is not useful in our real project or application.

I suggest while you deploy project or application in Live environment, then we should write test cases with test environment.


Hope this will help you and save your time.

Enjoy !!!

:)

Enable CORS on Web API project

Enable CORS on Web API project 



Error:



Access to XMLHttpRequest at 'http://local-corsapi.com/api/demo' from origin 'http://local-corsweb.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

To resolve, above issue we need to implement and enable CORS in api project.


Enable CORS

In webapi project, install below package using nuget, 

install-Package Microsoft.AspNet.WebApi.Cors

Different Scopes to EnableCors


1. Action

2. Controller

3. Global





1. Action - We can enable CORS on specific action only, for example as below





 [EnableCors(origins: "http://local-corsweb.com", headers: "*", methods: "*")]
        public HttpResponseMessage Post()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("POST Response : " + DateTime.Now)
            };
        }

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //Write below code line
             config.EnableCors();

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

2. Controller - We can enable CORS on controller basis as well, so it will aplicable for all action methods in that controller.

[EnableCors(origins: "http://local-corsweb.com", headers: "*", methods: "*")]
public class DemoController : ApiController
{
 public HttpResponseMessage Get()
 {
  return new HttpResponseMessage()
  {
   Content = new StringContent("GET Response : " + DateTime.Now)
  };
 }

 [DisableCors]
 public HttpResponseMessage Post()
 {
  return new HttpResponseMessage()
  {
   Content = new StringContent("POST Response : " + DateTime.Now)
  };
 }

 public HttpResponseMessage Put()
 {
  return new HttpResponseMessage()
  {
   Content = new StringContent("PUT: Test message")
  };
 }
}

But if you don't want to implement for specific action method then you can decorate that action method using [DisableCors]


3. Globally : To enable CORS on application level, we can write below code in WebApiConfig file

public static void Register(HttpConfiguration config)
{
 //Below two lines set CORS globally 
 var cors = new EnableCorsAttribute("http://local-corsweb.com", "*", "*");
 config.EnableCors(cors);
  
  
 config.MapHttpAttributeRoutes();

 config.Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
 );
}


MVC Application or client side application

HTML

<style>
    .rowheight {
        padding: 10px;
    }
</style>


<div class="row">
    <div class="col-md-12 rowheight">
        <input type="button" value="Get Method" onclick="GetRequest()" class="btn btn-default" />
        <span id='getResult'></span>        
    </div>
 
    <div class="col-md-12 rowheight">
        <div>
            <input type="button" value="Post Method" onclick="PostRequest()" class="btn btn-default" />
            <span id='postResult'></span>
        </div>
    </div>
</div>

Java Script

<script>
    
    var serviceUrl = 'http://local-corsapi.com/api/demo';

    function GetRequest() {
       $('#getResult').text("");
            $.ajax({ 
                headers: { 
                    'Accept': 'application/json',
                    'Content-Type': 'application/json' ,
                    "cache-control": "no-cache"
                },
                url: serviceUrl,
                type: 'POST',    
               // data:  ApiRequest ,
                data:  JSON.stringify( {
                    "PageSize": 10,
                    "PageNumber": 0,
                    "Search": ""
                }),
                 
                success: function (data) {
    $('#getResult').text("");
                   $.each(data, function (i, data) {
                    $("#getResult").append( data.categoryName+ '  '  );
                });
                    
                },
                error: function (request, status, error) {
                    if (request.responseText == null) {
                        $('#getResult').text(error.text);
                    }
                    else {
                        $('#getResult').text(request.responseText);
                    }
                }
            });
    }

    function PostRequest() {
        $.ajax({
            type: "post",
            url: serviceUrl,
            success: function (data) {               
                $('#postResult').text(data);
            },
            error: function (request, status, error) {
                if (request.responseText == null) {
                    alert("There is something wrong");
                }
                else {
                    alert(request.responseText);
                } 
            }
        });
    }

</script>

Another way:

Web.config in API project, add below setting in <system.webServer>
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>


in global.asax of webAPI project
protected void Application_BeginRequest(Object sender, EventArgs e)
{
 // Preflight request comes with HttpMethod OPTIONS
 if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
 {
  HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
  // The following line solves the error message
  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
  // If any http headers are shown in preflight error in browser console add them below
  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
  HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
  HttpContext.Current.Response.End();
 }
}


API controller method, use IHttpActionResult
public class UsersController : ApiController
{
 public IHttpActionResult Get()
 {
  return Ok("done dona done ");
 }
}


API web.config sample
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings></appSettings>
  <connectionStrings>
    <add name="DbConnectionString" connectionString="Data Source=localhost;Initial Catalog=databasename;User ID=sa; Password=password" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" />
    <customErrors mode="Off"></customErrors>
  </system.web>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.8.1.0" newVersion="4.8.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Ninject" publicKeyToken="c7192dc5380945e7" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.3.4.0" newVersion="3.3.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Ninject.Web.Common" publicKeyToken="c7192dc5380945e7" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.3.1.0" newVersion="3.3.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>
    
  


Another way:

you can install IIS CORS Module using below link and then enable the CORS in web.config

Install CORS on server and update web.cofig of API project

<system.webServer> 
    ....
<cors enabled="true" failUnlistedOrigins="true">
         <add origin="http://yourfrontenddomain.com"
                 allowCredentials="true"
                 maxAge="120">                  

            </add> <!-- this is for specific domain only -->
        <add origin="http://*" allowed="true" />  <!-- this is for all domain -->

    </cors>
  </system.webServer>


Hope this will help you and save your time.

Enjoy !!!

:)

Git remote: HTTP Basic: Access denied and fatal Authentication

Git remote: HTTP Basic: Access denied and fatal Authentication



Sometimes, I am facing issue with Git and getting error that - "Git remote: HTTP Basic: Access denied and fatal Authentication".

Problem occurs while I change my password of Git. 

So, we need to update git password in Windows system.


Solution 1

Go to Windows Credential Manager (press Windows Key and type 'credential') to edit the git entry under Windows Credentials. Replace old password with the new one.

Solution 2

1. Run below command from cmd

git config --system --unset credential.helper

And when I execute the above command, I got another error

error: could not lock config file C:\Program Files\Git\mingw64/etc/gitconfig: Permission denied

2. And then I removed gitconfig file from C:\Program Files\Git\mingw64/etc/ location

3. After that use git command like git pull or git push, it asked me for username and password. applying valid username and password and git command working.


Hope this will help you and save your time.

Enjoy !!!

:)