Wednesday, November 7, 2018

DotNetCor2.1 Api CORS (Enable Cross Origin request)


The cross origin request are sometimes dreadful. This needs to be addressed at the api level

In Dotnet Core 2.1 we can handle it elegantly.


1) Install NuGet package Microsoft.AspNetCore.Cors from NuGet Package Manager.

2) Call AddCors in Startup.ConfigureServices to add CORS services to the app's service container

public void ConfigureServices(IServiceCollection services) { services.AddCors( O => O.AddPolicy("MyPolicy" , builder =>

{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();

}
));


}


3) My project is WebApi so i will use Enable CORS with CORS Middleware

approach.


public void Configure(IApplicationBuilder app, IHostingEnvironment env,

ILoggerFactory loggerFactory)

{ loggerFactory.AddConsole(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Shows UseCors with CorsPolicyBuilder. app.UseCors("MyPolicy");
}

4) Add the attribute [EnableCors("MyPolicy")]

on the controller or on the method if you need to be more specific

Tuesday, November 7, 2017

Retreiving field value in XML using cross apply

1)  First we will cast the field data in a table to type xml from type text

2) you need to use with operator if namespace is defined ;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/Psv.Domain.Models.PexaNoa')

3) consider ContentXML as 

     '<Name>

         <First>Jacob</First>

         <Last>Sebastian</Last>

     </Name>'

Begin

 SELECT ContentXML INTO #tab12
FROM 
 (Select  
 Cast(data as xml) AS ContentXML
 from ABC
 ) a



 ;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org')

 SELECT t.value('(./First)[1]','NVARCHAR(MAX)') as FirstName
  FROM #tab12
Cross Apply ContentXML.nodes('/Name') x(t) 

 Drop table #tab12
End






   

 


Friday, October 14, 2016

How to get a nested td value in Jquery


I have a difficult task at hand to get the value of a "td" which is generated by Keno Grid and its really driving me crazy due to time constraint at client end. Following is the solution.

Main div has id which gave me hope

the mock structure is below

 <div id="mainDiv">
        <div>
            <div class="div-class">
                <table>
                    <thead>
                        <tr>
                            <td>
                                header1
                            </td>
                            <td>
                                header 2
                            </td>
                        </tr>

                    </thead>
                </table>
            </div>
        </div>

        <div class="k-grid-content">
            <table border="1">
                <tbody>
                    <tr>
                        <td role="gridcell">column1</td>
                        <td role="gridcell">column2</td>
                    </tr>
                    <tr>
                        <td role="gridcell">columnn3</td>
                        <td role="gridcell">column4</td>
                    </tr>
                </tbody>
            </table>

        </div>
 
    </div>
<script>
 $('#mainDiv').on('click', '.div-class table tbody tr', function () {
                var value= $(this).find("td:first-child").text();
                });
</script>

1) First capture the click event of the div with id.
2) Access the div you require with class name "div-class".
3) Access the "table".
4) Access the "tbody"
5) Access the "tr"
then get the values you require. Our requirement was to have first column value.

Wednesday, September 7, 2016

How to access the MVC controller using Jquery to get things done.

I have to do a task using jquery and calling controller method. Following is the code to achieve it.

1) div click.
2) the value is take from the "td".
3) passed to the ajax method.
4) show result in another grid.

Jquery part

$('#mainDiv').on('click', '.child-class table tbody tr', function () {
                var Code = $(this).find("td:first-child").text();
                    $.ajax({
                        type: "POST",
                        async: true,
                        datatype: "json",

                        url: "/Controller/Method",
                        data: { "Code": "" + Code + "" },
                       
                        success: function (data) {

                            $("#ToolTipCode").text(data);
                        },
                        error: function (x) {

                            $("#ToolTipCode").text("Doesnot exist.");
                        }
                    });

                });

MVC controller

[HttpPost]
        public ActionResult Method(string Code)
        {
            // do your stuff
            return Json(codeWithDescription);
        }

Friday, May 1, 2015

SP 2013 Auto Hosted App Discontinued

Share Point 2013 App Model Auto Hosted App option was in Preview and it was discontinued on 30-June-2014,

Error: When you try to deploy AutoHosted App to your O365 it will give you following error
something went wrong error

CauseMicrosoft Announcement about AutoHosted App

Now you can covert the autohosted to Provider hosted app use the following MSDN link to convert your applications.

Solution:How to Convert AutoHosted App to ProviderHosted App

Friday, April 24, 2015

Starting the SharePoint Central Admin giving runtime Error


When Starting the Share point Central Administration I get Run-time Error.

Follow the steps below

1) Go to IIS
2) Expand the "Sites" folder and select "SharePoint Central Administration v4 " virtual directory
3) In the "Actions" section click Explore
4) The site physical folder will open and contains web.config file.
5) Open web.config file find the "CustomErrors" tag.
6) Set its mode attribute to mode="Remoteonly"
7) Refresh and Re-open the central Administration Site in browser
8) You will Get the following error now

Error: This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

Cause: SQL Server for SharePoint services stopped due to restart of my machine

9)  Now Open the Services.msc
10) Restart the "SQL Server(SHAREPOINT)" service
11) Also Enable and Restart the "SQL Server Agent (SHAREPOINT)"
12) Also Enable and Restart "SQL Server Browser" 

PS: I hope this helps. Please drop your comments.

Tuesday, April 14, 2015

how to use requiredfield validator with dropdownlist


Here is how we can use requiredfieldvalidator with dropdownlist.

Set the below property of the dropdownlist control

AppendDataBoundItems = true

Then Insert a default value in the Page_Load event

ddl.Items.Insert(0, new ListItem("<<-Select-->", "-1"));

Now define the required field validator and set its initialvalue attribute to "-1"

<asp:RequiredFieldValidator ID="reqddl" runat="server" Text="*" ControlToValidate="ddlRole" InitialValue="-1" SetFocusOnError="true" Display="Dynamic" ValidationGroup="Add"></asp:RequiredFieldValidator>

Happy coding :)

Monday, March 2, 2015

Hide and Show div using Jquery

We have a requirement to hide and show our Grid in a div. 

Following is the code to achieve this functionality

Define the first div which shows the caption Show/Hide. Whenever the mouse is over the div "divtoggle1" second div "divOrders" is either shown or hidden

The below <Div> is defined with caption Show/Hide

 <div id="divtoggle1" style="text-align:left;width:250px">
                 Show/Hide
  </div>

The below <Div> contains the GridView which we need to Show/Hide

<div id="divOrders">
 
<asp:GridView ID="grvOrders" runat="server" AutoGenerateColumns="False" >

     <Columns>
          <asp:TemplateField HeaderText="firstcolumn" >
                      <ItemTemplate>
                              <asp:LinkButton ID="lnkName" runat="server" Text='<%#
                                  DataBinder.Eval(Container.DataItem,"Names") %>'                                                                               CommandName="OrderDetail">
                            </asp:LinkButton>
                        </ItemTemplate>
            </asp:TemplateField>
        </Columns>
  </asp:GridView>
</div>  

The Jquery part which toggle the div

we are access the div "divtoggle" with "#" sign because in Jquery when you want to access any element by ID you have to use "#" sign before the name of element.

we call the "divtoggle1" mouseover event and in that event we are checking the second div "divOrders".

 if "#divOrders" visible then hide it or if it is hidden then make it visible. we also added delay function to make the Show/Hide smooth and we used hide argument "slow".

<script type="text/javascript">
    $(document).ready(function () {
        $("#divtoggle1").mouseover(function () {

            if ($('#divOrders').is(':visible')) {
                $("#divOrders").delay(100).hide('slow');
                $("#divtoggle1").text('Show Orders');
            }
            else {
                $("#divOrders").delay(100).show('slow');
                $("#divtoggle1").text('Hide Orders');
            }

        }); // end of mouse over
    });    // end of ready function
 

</script>

Monday, February 2, 2015

Passing-parameter-value-through-a-function-from-anchor-tag-in-a-gridview

We have a requirement where we have to pass Session values and DataBound values to Javascript function using Anchor tag in Gridview.

Following is the Anchor defined in the Gridview where we are passing Session and Eval values as parameter to the Javascript function

OpenAttachmentWindow(roomId,StudentId,Id).


Javascript function description

<script language="javascript" type="text/javascript">

       function OpenAttachmentWindow(roomId, StudentId, Id)
         {
             var ReadOnly = 0;

             window.open('UploadSupplierAttachments.aspx?roomId=' + roomId + '&studentId=' +
             StudentId + '&id=' + Id + '&ReadOnly=' + ReadOnly, '', 'width=700,height=500')
         
          }

   </script>


Gridview Template column

We have anchor html control which will pas the server side arguments to javascript function.

<asp:TemplateField HeaderText="view">

    <ItemTemplate>

           <a  onclick='<%# "OpenAttachmentWindow(" +Session["roomId"] + " , " +        
           Session["StudentId"] + ", " + Eval("Id") +" );" %>'  id="a1" runat="server" >Attachment </a>

    </ItemTemplate>

</asp:TemplateField>


Wednesday, January 21, 2015

Compare Validator DataTypeCheck


I have been using asp.net Validator controls for quite long. I have come across the unexplored property of Compare Validator which can check input against following types

1) Currency
2) Date
3) Double
4) Integer 
5) String

you can use the Validator by setting the following properties

Operator="DataTypeCheck"

Select any of the below types for data type check

Type= Currency
            Date
            Double
            Integer 
            String

Example:

<asp:CompareValidator ID="CompareValidatorNumber" runat="server" ControlToValidate="txtTelephone" Text="*" Display="Dynamic" ErrorMessage="Please enter numbers only" Operator="DataTypeCheck" Type="String"></asp:CompareValidator>


Wednesday, November 19, 2014

filling DataSet by calling oracle stored procedure

Use the below code as a reference.


public void GetDatainDataset()
{

 using (OracleConnection conn = new OracleConnection(strConnStr))            {                conn.Open();

                OracleCommand cmdABC = new OracleCommand();

                cmdABC.Connection = conn;

                cmdABC.CommandType = CommandType.StoredProcedure;

                cmdABC.CommandText = Stored Procedure Name;

                cmdABC.Parameters.Add("P_RC", OracleDbType.RefCursor).Direction                 = ParameterDirection.Output;

                DataSet ds = new DataSet();

                OracleDataAdapter adapter = new OracleDataAdapter(cmdPlants);

                adapter.Fill(ds);

                ddlABC.DataSource = ds.Tables[0];

                ddlABC.DataTextField = "A";

                ddlABC.DataValueField = "B";

                ddlABC.DataBind();

                conn.Close();

                conn.Dispose();}

Monday, October 20, 2014

Wednesday, October 1, 2014

Generate c# code from *.wsdl file using WSDL Tool

Web Service Descriptor Language Tool

is used to generate the c# code from the *.wsdl file and you can use it as proxy class for prototyping

We have been assigned a small integration project. It is in inception stage so many things are not clear and we have been given one *.wsdl file to study and we tried to generate c# code from it to work on our application prototype

wsdl.exe can be found in Visual Studio 2005 at the following location

C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

you can use following command to generate the proxy class from command prompt

wsdl /out:C:\Test\out:myProxyClass.cs C:\Test\MyWsdlfile.wsdl

Now you can add the myProcyClass.cs in your project and use its methods. Please don't modify the myProcyClass.cs file as it auto generated.

Wednesday, September 10, 2014

SQL Query Column values as comma separated



Introduction


I have a table as shown below, which has Country_Code and Cities of the a country.

 I need to retrieve distinct cities in a country based on the Country_Code
column as a comma separated string.



SQL Statement


The following SQL Statement shows how it can be achieved

Begin
declare @str varchar(1000)

SELECT @str= coalesce(@str + ',' , '') + a.CountryLang_Desc 
FROM (SELECT DISTINCT CountryLang_Desc from CountryLanguages where Country_Code='IN') a

print @str 
End

Wednesday, August 13, 2014

_doPostBack and Browser back button behavior



The odd behavior of Browser Back Button on _doPostBack()



 In one of application developed in Asp.net page is not behaving as desired when browser back button is pressed.

The steps performed in the following order

1) Go to the page
2) Click a link which causes _doPostBack and navigate to new page
3) Press the browser back button
4)click on any button 

This will end up re-executing the _doPostBack() action instead of firing Button click event.

The reason or behavior is as follows
  • Back button goes back to the previous page - page is not reloaded from server!
  • Browser assigns __EVENTxxx etc. with the previous POST back values
  • The server detects the __EVENTxxxx form vars and routes events accordingly (incorrect behavior)
To overcome this behavior i had a simple solution in my mind to expire the page and empty the secure page cache.
It worked for me by introducing following code in page load event and use is at the top not in any checks like IsPostback etc.


Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);


Wednesday, July 16, 2014

Disable Secure Page Cache or Expire Web Page on browser button


Expire Web Page on Browser Back/Forward Button click

Why we need to expire the web page when browser back/forward button 
is clicked. It is one of the security concern that if any user using any 
public shared computer and left the browsed page open the bad guy 
can sneak peak in to your information by using browser back/ forward buttons.

There are lot of solution available but the solution is little tricky lets start

Part 1

First of all add following response properties in you Page_Load function
and don't put this code in if(!IsPostback) code block in Page_Load function 
see sample code as below

 protected void Page_Load(object sender, System.EventArgs e)
  {                    
            if (!Page.IsPostBack)
            {
                // you Logic here
               
            }
           
            Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Page.Response.Cache.SetNoStore();
            Page.Response.Cache.AppendCacheExtension("no-cache");
            Page.Response.Expires = 0;
          
  }

 If there is any action or postback then the below mentioned lines will work and expire the page

 Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Page.Response.Cache.SetNoStore();
 Page.Response.Cache.AppendCacheExtension("no-cache");
 Page.Response.Expires = 0;

Part 2

Now to add your own logic to cater pages where we don't have any postback.

Add the following code in you Page_Load function if(!IsPostBack) check 
as below

We have taken one Session variable "TimeStamp" and one ViewState variable "TimeStamp".
when the web page is loaded with any navigation link inside the application we have Session["TimeStamp"] and ViewState["TimeStamp"] variable value "null" and that means browser buttons are not clicked and we don't have to expire the Page.

Whenever the user click the browser back/forward button the ViewState will become null for that page and Session will contain the "TimeStamp" so we infer that browser button is clicked and we need to expire the page and redirect it to a page in our case we redirect to WebPageExpire.aspx .

 protected void Page_Load(object sender, System.EventArgs e)
  {                    
            if (!Page.IsPostBack)
            {
                // you Logic here
                if (isPageExpired())
                   {
                        Response.Redirect("WebPageExpire.aspx");
                   }
               else
                  {
                       string strNow = DateTime.Now.ToString();
                       Session["TimeStamp"] = strNow;
                      ViewState["TimeStamp"] = strNow;
                  }

            }
           
            Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Page.Response.Cache.SetNoStore();
            Page.Response.Cache.AppendCacheExtension("no-cache");
            Page.Response.Expires = 0;
          
  }



Now add the function isPageExpired() which compares the Session["TimeStamp"] and ViewState["TimeStamp"].

private bool isPageExpired()
   {
            if (Session["TimeStamp"] == ViewState["TimeStamp"])
                return false;
            else
                return true;

   }

One more thing from where ever you are navigating either asp:Button , asp:Link etc 
we have to initialize the Session["TimeStamp"]= null so that every time when we navigate legitimately our  Session and Viewstate have same value.

    protected void BtnRegister_ServerClick(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            Session["TimeStamp"] = null;
            Response.Redirect("Register.aspx", false);
        }


The same logic we have to add in every page where we need secure cache disable functionality plus you have to design a page in my case i have designed the page WebPageExpire.aspx and show message to user WebPage has expired please login again.

I hope this will solve the problem and looking forward to hear from you guys.

Monday, May 19, 2014

Microsoft Anti Cross Site Scripting Library a tool to defend yourself against Cross Site Scripting XSS



To prevent cross site scripting use Microsoft Anti Cross Site Scripting Library its free and need of time following is the link from where you can download.

Microsoft Anti Cross Site Scripting Library

Wednesday, February 12, 2014

Encrypt View State Data for ASP.net Application



Encrypting view state is used to reduce the chance of information disclosure and some one getting information to cause harm to the user.

In Asp.net 2.0 the support for encryption has been enhanced. Now you can define encryption of view state on Page level. Following is the implementation in the Page tag of the aspx file.

<%@ page language="c#" masterpagefile="~/MasterPage.master" inherits="Abc.Default, App_Web_Default.aspx.cdcab7d2" validaterequest="false" theme="ABC" viewstateencryptionmode="Always" enableEventValidation="false" %>

The attribute ViewStateEncryptionMode  has three values.
1) Auto
2) Always
3) Never

The default for ViewStateEncryptionMode is Auto.

We can also set its value in the web.config file as 

<configuration>   
   <system.web>
      <pages ViewStateEncryptionMode="Always" />
   </system.web>

</configuration>

Sunday, January 12, 2014

How to access a radio button selected Boundfield value from a GridView in javascript


function RefreshParent()
{
//get the gridview object
var gv = document.getElementById("grdViewBrand");
//get the gridview input object collection
var rbs = gv.getElementsByTagName("input");
//Traverse the input object collection
for (var i = 0; i < rbs.length; i++)
{
//Check for the checked radio button
if (rbs[i].type == "radio")
{
if (rbs[i].checked)
{
//get the bound field value from the position where check box is checked
// [i+1] is due to gridview dataBoundField includes header
row also which is not present in input collection
var brandName = gv.rows[i+1].cells[0].innerText;
break;
}
}
}

Description

Get the gridview object and its inputs elements.
Traverse through the (input)collection and get the
selected Radio Button row.

Now from the griview object get the rows position and the cell
and call its inner text property

Tuesday, December 31, 2013

Enforce Secure flag for session cookies in ASP.net



To avoid disclosure of sensitive information in transit from the server to the browser,
many applications use HTTP over SSL (HTTPS).
However, because it may be possible to navigate away from the HTTPS protected transport settings of the site,
either by someone specifically providing a link to a non https:// resource or via the application using a absolute reference and mistakenly using http://,
users may subject to their communications being "sniffed" between the browser and server.
Not only is the user data posted to a web server important to protect using HTTPS -
if an attacker were able to see session identifiers passing in plain sight they could reuse
them and masquerade as another user while the session was active (i.e. The user hadn't logged off).
To avoid this from happening, cookies can be set to be "secure" - that is,
they are only to be transmitted when a secure channel is available.

Add the following tag in the webConfig

<System.web>
<httpCookies requireSSL="true"/>
</System.web>