Sunday, October 29, 2017

Unable to update the EntitySet - because it has a DefiningQuery and no element exist

When you come across the above error while inserting into the database table using LINQ the reason for that is your Database table doesn't have a primary key I was trying to insert the data into the table which does not have any primary key created on it the solution is to create the primary key on that table.

No 'Access-Control-Allow-Origin' header is present on the requested resource.

When we create a web API and it works fine in our local application or the same application but if we want that same API to use in the different application then we come across an error known as the 'Access-Control-Allow-Origin'

Please look at the below image


Failed to load http://localhost:4815/api/v1/user/hello: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

To solve that error we need to do the following thing.By setting the cors we are allowing the other users to access our web API we can set the restriction also on the controllers or on the methods of our web API so that users can only access the content which we want them to access. Please find the ways how to enable cors in your application.

First, install the library  Nuget Package Link


Then add the below namespace in your application

using System.Web.Http.Cors;

After adding the namespace you will able to access the EnableCors attribute

[RoutePrefix("API/v1/user")]
    [EnableCors("*", "*", "GET,POST")] //add this line
    public class UserController : ApiController
    {
        [HttpGet]
        [Route("Hello")]
        public HttpResponseMessage Hello()
        {

            return Request.CreateResponse(HttpStatusCode.OK,"I'm from WebAPI");
        }

    }


Also, go to the web API config and add this lines

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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


            EnableCorsAttribute co = new EnableCorsAttribute("*", "*", "GET,POST"); //add this line
            config.EnableCors(co); //add this line

        }
    }

Class Files inside the App_Code Folder not accessible

Just click on the properties of the class and change it's Build Action from content to compile.Please see the below images for clear idea.




Change to


Friday, October 27, 2017

The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.

When you get the above exception after running your WebAPI follow the below steps to resolve the error
method write the below line of code.

just open the Global.asax.cs class and under the Application_Start()

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            GlobalConfiguration.Configuration.EnsureInitialized();  //add this line
        }
    } 

.CS file not visible in Visual Studio


None of the .cs files are opening in the visual studio the solution for that is locate to the below folder at the location
C:\Users\My PC\AppData\Local\Microsoft\VisualStudio\12.0
Folder Name: -
ComponentModelCache
and delete the folder.If the message comes access is denied then check if any instance of the visual studio is running close it then delete the folder and check it worked for me.
  

Friday, July 7, 2017

How to add Multiple validation group to the same control ?



In some conditions we may need to validate a controls based on the different conditions consider the below example in which we are validating the same dropdown list from two different validation group Here we are using the  Page_ClientValidate('your validation group name') method which will accept the validation group name as input
  

Example:- 

 
<form id="form1" runat="server">
        <asp:Button Text="First" runat="server" ValidationGroup="firstVG" />
        <asp:Button Text="Second" runat="server" ValidationGroup="secondVG"  OnClientClick="return Check(); " />

        <asp:DropDownList runat="server" ValidationGroup="first" ID="ddl">
            <asp:ListItem Text="--Select--" Value="-1" />
            <asp:ListItem Text="A" />
            <asp:ListItem Text="B" />
        </asp:DropDownList>
        <asp:RequiredFieldValidator ErrorMessage="*" Display="Dynamic" ForeColor="Red" ControlToValidate="ddl" runat="server"  InitialValue="-1" ValidationGroup="firstVG"/>

    </form>

JavaScript File :- 

 

    <script type="text/javascript">
        function Check() {

            var isValid = false;
            isValid = Page_ClientValidate('secondVG');
            if (isValid) {
                isValid = Page_ClientValidate('firstVG');
            }

            return isValid;

        }
    </script>

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).



After adding the built in validating controls like required field validator in my case I added a new web form and then after adding the required field validator controller in the form the form got compiled but after running we can see the above error on the browser. The solution is that  we need to add  a new key into to the web.config file under the <appSettings> section

In Web.config



  <appSettings>

    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

  </appSettings>

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...