Friday, 26 December 2014

How to Enforce HTTPS on your Azure website

URL Rewrite rules are defined in a web.config file stored in the root of your application. The following example contains a basic URL Rewrite rule that forces all incoming traffic to use HTTPS.
URL Rewrite Example Web.Config











This rule works by returning an HTTP status code of 301 (permanent redirect) when the user requests a page using HTTP. The 301 redirects the request to the same URL as the visitor requested, but replaces the HTTP portion of the request with HTTPS. For example, http://testwebsite.com would be redirected to https://testwebsite.com.

How to create ssl certificate for Azure website using Godaddy

SSL Certificate For Azure Website using Godaddy .

OR
Step By Step Guide for Implementing Godaddy SSL Certificate on Windows Azure Website.


Today I got a task of implementing an SSL for a sub domain of one of our client .So i Did the Implementation so i am sharing my effort and knowledge.

Step 01: First Generate a Certificate Request i.e CSR.

Open the IIS Manager(Type IIS in Windows Search and click on IIS )





















When you will click on IIS then this screen will come.In that Screen just click on Server Certificate.




















On the Server Certificates Screen , click Create Certificate Request .












Fill all the details for the certificate. 

Make sure that the common name matches your domain name. In my case If you are using a Godaddy 
wild card certificate for a subdomain. Then used common name something like *.mydomain.com.




Choose Cryptographic Service Provider

This step is quite important to note, and this is where you follow the Azure guideline for certificate to be 
at least 2048.




















Choose the file path to generate the CSR. This file contains the message code that is used by SSL provider for generating digital identity Certificate.



















The File Will Be Something like this.

-----BEGIN NEW CERTIFICATE REQUEST-----
MIIEaDCCA1ACAQAwezELMAkGA1UEBhMCSU4xEjAQBgNVBAgMCUthcm5hdGFrYTES
MBAGA1UEBwwJQmFuZ2Fsb3JlMR0wGwYDVQQKDBRMb3ZlIFdpdGggVGVjaG5vbG9n
eTELMAkGA1UECwwCSVQxGDAWBgNVBAMMD2xvdmV3aXRodGVjaC5pbjCCASIwDQYJ
KoZIhvcNAQEBBQADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXBZQMEAQIwCwYJYIZIAWUDBAEFMAcGBSsOAwIHMAoGXXXXXXXX
CCqGSIb3DQMHMB0GA1UdDgQWBBQ0hA5sL7ClGR9/Bj0YiO/tn9M3PTANBgkqhkiG
9w0BAQUFAAOCAQEAp9duVMU8+8/8XUsrALIoRnDW0mOwDQRhnpJCYVDqHZqztRrO
ZRKMz788+qqtUrO5yVsRx4pbUg752f+/UBeTM+Z0Yg4FiWQpMAr+59/9/m0Fw/W7
bjocnzx0nizy/Uw8BVhFFQwH4rWOpjxWeftbXGx+YLa7QrhQMJzLYG3LSljjFz+c
Usv1KPsmF+DTZPYIEk64eYUcchP19QXKb162i62TAEferhb71+412pJb0zltj2Uw
e7cvZ1xdascdQG5MXLqzsXZ0yiLP/6/i4X9IgUl3xp/mU1w4HSC1IS7zq56IWTJR
NTyBIJV8CP+K8M1DQmtJek0clhlwMV9ek9nwBA==
-----END NEW CERTIFICATE REQUEST-----



Logon to your Godaddy account, and from product tab click SSL Certificates. 
Note that you need the entire text of the CSR file to submit the request. I won’t include all
the sub steps here since it’s a relatively simple process and it’s very well documented by Godaddy at this link. Requesting a standard or a wildcard certificate


Download the certificate Zip file after you’ve submitted the request. 




















After the download, you’ll observe that there are two files in the zip, one is a *.crt (Server Certificate) file and other is of type PKCS #7. Ignore the PKCS #7 Certificate file, and instead use the *.crt file. Go to Server Certificate option in IIS 7 and click Complete Certificate Request.












Provide the path of the *.crt file, and fill out the details on the form. Note make sure you change the file types to *.* Once completed you will see a row entry with name of your certificate.

Some time it will give error , so just close the iis and open it again, now you can see the certificate.



















 Right click the certificate and click export to convert it into *.pfx file for uploading it on 
Azure. Note that this conversion of crt to pfx is required since *.crt alone only contains the 
public key but the azure would also need private key to do end to end encryption. Make sure
 you note the password since while uploading it on Azure Account you’d need this.

Now We have to import PFX file into Azure.For that Go to Azure Portal for the website in which you want SSL.

Click on Domains and SSL and then on the Upload button. You’ll then be able to browse to
 your pfx file and to enter your password. Click on Save when done.














Last : Bind configured domain names to the certificate


The final step is to link each configured domain to the certificate. This step I had to do in the
 old portal. The reason was that Azure needed to ask me if I was aware of the potential 
extra costs of using a certificate, before it could be approved, and that dialog box never 
showed up in the new portal. But the steps are the same on the old and the new so no 
problems.



Now, it should all be up and running for all your configured domains.








Tuesday, 23 December 2014

Conflicting versions of ASP.NET Web Pages detected: specified version is "1.0.0.0", but the version in bin is "2.0.0.0". To continue, remove files from the application's bin directory or remove the version specification in web.config.

I am trying to run my application and it is showing an error like this..

Conflicting versions of ASP.NET Web Pages detected: specified version is "1.0.0.0", but the version in bin is "2.0.0.0". To continue, remove files from the application's bin directory or remove the version specification in web.config.





Answer :

You need to set webpages:Version appSettings with appropriate value. In your case it has to be 2.0.0.0... For this just go in Web config file and write / Change ....

<add key="webpages:Version" value="1.0.0.0"/> 

to 

 <appSettings>
    <add key="webpages:Version" value="2.0.0.0"/>
 </appSettings>


Done :)

Tuesday, 18 November 2014

Wednesday, 15 October 2014

How to Use Log4net with ASP.NET MVC 5 for Logging

Log4net is an open source library that allows .NET applications to log output to a variety of sources.

Log4net provides a simple mechanism for logging information to a variety of sources. 
Information is logged via one or more loggers. These loggers provide 5 levels of logging:
  1. Debug
  2. Information
  3. Warnings
  4. Error
  5. Fatal
Here I will be walking through the step by step in implementing logging functionality using log4net framework in an ASP.NET MVC 5 application.

I am using Visual Studio Express 2013 for Web as my development environment targeting .NET framework 4.5.1

Step 1:

Open Visual Studio 2013 for Web and create a new ASP.NET Web application selecting MVC template.

Step 2: 

Now We need to add reference of log4net DLL using NuGet package manager.






Step 3:

Next, we need to configure our application to use log4net logging framework. Add the below line in yourstartup.cs file in ASP.NET MVC5 Solution folder. The below line of code provides information about log4net configuration file.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]




Step 4:

Next, add the below section to web.config file.

<configSections>
    <!-- Add log4net config section-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,     log4net" />
  </configSections>

  <log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

Step 5:

Next modify Global.asax.cs and add the below code inside Application_Start() method.

readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Step 6:

Use the logger.Error() method to log messages when needed.


Step 7:

Run an application and we can see the log file generated under the logs folder under the application root directory as configured in the web config file.




DONE :)


Tuesday, 9 September 2014

instance failure' error while connection string is correct



If you got the error "instance failure", that might be the error with your SQL Server instance..


Make sure your SQL Server instance(i.e MS SQLSERVER) is running, where you can check in Services list. to get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter.

That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS.

For Example

 

Monday, 4 August 2014

HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace


HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).


Solution:
If You all are Getting This error in WCF, then just closed Visual studio and reopened it by right clicking on the Visual Studio icon and saying "Run as Administrator", Then it will Work !!!


 <system.serviceModel>
    <services>
      <service name="CompanyService.CompanyService" behaviorConfiguration="mexBehavior">
        <endpoint address="CompanyService" binding="basicHttpBinding" contract="CompanyService.ICompanyPublicService"></endpoint>
      <endpoint address="CompanyService" binding="netTcpBinding" contract="CompanyService.ICompanyConfidentialService"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/"/>
          <add baseAddress="net.tcp://localhost:8090/"/>
          </baseAddresses>
        </host>
    </service>
    </services>
  <behaviors>
    <serviceBehaviors>
      <behavior name="mexBehavior">
        <serviceMetadata httpGetEnabled="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  </system.serviceModel>

Friday, 1 August 2014

Full page video background with HTML5 and CSS in MVC5

View

<video id="video" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0">
     <source src="movie.mp4" type="video/mp4">
    Sorry, your browser does not support HTML5 video.
</video>
 
 
CSS
 
#video {
     position: absolute;
     top: 0px;
     left: 0px;
     min-width: 100%;
     min-height: 100%;
     width: auto;
     height: auto;
     z-index: -1000;
     overflow: hidden;
}
 
Thats it ;) 

Remove Auto-Generated advertisement script appended to the results returned by ajax requests (Web hosting by Somee.com)

Remove Auto-Generated advertisement script appended to the results returned by ajax requests


OR

Removing or hiding javascript from a page using Javascript

Or
How to Remove Generated Script from somee.com

I have hosted my Site on somee.com.
I have used JQuery to send ajax requests.
On every ajax request the returned result is appended with the below text.
"<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE--> 
<center><a href="http://somee.com">Web hosting by Somee.com</a></center> </textarea>
</xml></script></noframes></noscript></object></layer></style></title></applet> 
<script language="JavaScript" 
src="http://ads.mgmt.somee.com/serveimages/ad2/WholeInsert4.js"></script>
<!--SCRIPT GENERATED BY SERVER! PLEASE REMOVE-->"
SO How to Resolve it .....

To Resolve Just Write the following Script

    <script>
        $(document).ready(function () {
            $("div[style='opacity: 0.9; z-index: 2147483647; position: fixed; left: 0px; bottom: 0px; height: 65px; right: 0px; display: block; width: 100%; background-color: #202020; margin: 0px; padding: 0px;']").remove();
            $("div[style='margin: 0px; padding: 0px; left: 0px; width: 100%; height: 65px; right: 0px; bottom: 0px; display: block; position: fixed; z-index: 2147483647; opacity: 0.9; background-color: rgb(32, 32, 32);']").remove();
            $("div[onmouseover='S_ssac();']").remove();
            $("center").remove();
        });
</script>


Thats It ;)



Tuesday, 29 July 2014

How to Post JSON Data to an MVC5 Controller via Ajax

It's just a simple form where you enter your first name and last name, and then use a multiselect dropdown to pick your favorite bands.

Home













and enter your First name, Last name and select your favorite Car.














Step 1: First Create PersonController.css

 [HttpGet]
        public ActionResult Index()
        {
            return View(new PersonModel());
        }

        [HttpPost]
        public JsonResult BadSave(string first, string last, List<string> favoriteBands)
        {
            Console.WriteLine(first);
            Console.WriteLine(last);
            Console.WriteLine(String.Join(" ",favoriteBands));

            return Json(new { result = "saved the bad way" });
        }

        [HttpPost]
        public JsonResult GoodSave(PersonModel model)
        {
            Console.WriteLine(model.First);
            Console.WriteLine(model.Last);
            Console.WriteLine(String.Join(" ", model.FavoriteBands));

            return Json(new { result = "saved the good way" });

        }


Step 2 : Create PersonModel.css Model

public class PersonModel
    {
        [DisplayName("First Name")]
        public string First { get; set; }

        [DisplayName("Last Name ")]
        public string Last { get; set; }

        [DisplayName("Favorite Car")]
        public List<string> FavoriteBands { get; set; }
    }

Step 3 : Create the View ie Index.cshtml

@model MVCJsonPost.Models.PersonModel
@{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Home</h2>

<div>
    @Html.LabelFor(m => m.First)
    @Html.EditorFor(m => m.First)
</div>

<div>
    @Html.LabelFor(m => m.Last)
    @Html.EditorFor(m => m.Last)
</div>

<div>
    @Html.LabelFor(m => m.FavoriteBands)
    @Html.DropDownListFor(m => m.FavoriteBands, new SelectList(
                  new List<Object>{ 
                       new { value = 0 , text = "Honda City"  },
                       new { value = 1 , text = "Renault fluence" },
                       new { value = 2 , text = "Hyundai xcent"}
                    },
                  "value",
                  "text",
                   Model.FavoriteBands),
                    new { multiple = "multiple" })


</div>

<div>
    <input type="button" value="Bad Submit" id="bad" />
    <input type="button" value="Good Submit" id="good" />
</div>

<label id="result"></label>

Step 4: Create the js file i.e person.js in Script Folder

$(document).ready(function () {
    $('#good').click(function () {
        var request = new PersonModel();
        debugger;
        $.ajax({
            url: "Person/GoodSave",
            dataType: 'json',
            contentType: "application/json",
            type: "POST",
            data: JSON.stringify(request), //Ahhh, much better
            success: function (response) {
                $("#result").text(response.result);
            }
        });
    });

    $('#bad').click(function () {
        var request = new PersonModel();
        debugger;
        $.ajax({
            url: "Person/BadSave",
            dataType: 'json',
            type: "POST",
            data: "first=" + request.First + "&last=" + request.Last + "&favoriteBands=" + request.FavoriteBands, //How do you encode an array?? This doesn't even work right
            success: function (response) {
                $("#result").text(response.result);
            }
        });
    });
});

function PersonModel() {
    var self = this;
    self.First = $("#First").val();
    self.Last = $("#Last").val();

    self.FavoriteBands = $.map($('#FavoriteBands option:selected'),
                      function (e) { return $(e).val(); });
}


Run The Application  and fill the form and place some breakpoint to test and debug line by line















Done :)




Friday, 25 July 2014

How to Creating or Deleting a Profile in Another Language in LinkedIn

You can Create your profile in any number of language(to create you should visit http://www.linkedin.com/profile/edit-profile-in-another-language )  from the View Profile page.
While you can't change the language of your primary profile, you can create as many other language profiles as there are languages available.
So Now Question is How to create your profile in another language:
So For that :
  1. Click Profile at the top of your homepage.
  2. Click the  down arrow next to the Edit Profile button and select "Create profile in another language".
  3. Choose a language from the dropdown list and update your first name and last name if they're different in the new profile's language.
  4. Translate your existing Professional Headline.
    • Translations aren't done for you. You'll need to translate your own personal content.
  5. Click Create Profile to go to the Edit Profile page of your new language profile.
  6. Click any  Edit icon and translate the open fields.
  7. Click Save and continue editing other sections.
And How to delete a secondary language profile:
  1. Move your cursor over Profile at the top of your homepage and select Edit Profile.
  2. Select the language from the Profile dropdown list in the upper right.
  3. Click the Delete this profile link. If this link doesn't appear, the profile you're viewing is your primary profile. You can't change your primary profile's language setting.
  4. Click Delete.
Notes:
  • It is not possible to make another language profile as your default profile.