Friday, 28 September 2018

Call an ASP.NET Web API service in a cross domain using jQuery ajax (using Jsonp or by enabling CORS)

Browsers allow a web page to make AJAX requests only within the same domain. Browser security prevents a web page from making AJAX requests to another domain.

When you are doing so,  you get the following error. To see the error launch browser tools and click on the console tab.
XMLHttpRequest cannot load http://localhost:23258/api/Employees. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:6293' is therefore not allowed access.

So this proves, browsers do not allow cross-domain ajax requests. There are 2 ways to get around this problem
Method 1: Using JSONP (JSON with Padding)

Method 2: Enabling CORS (Cross-Origin Resource Sharing)

Method 1: Using JSONP (JSON with Padding) 

Step1: To support JSONP format, execute the following command using NuGet Package Manager Console which installs WebApiContrib.Formatting.Jsonp package.
Install-Package WebApiContrib.Formatting.Jsonp

Step 2: Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder

var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);

config.Formatters.Insert(0, jsonpFormatter);

Step 3: In the Application, set the dataType option of the jQuery ajax function to jsonp
dataType: 'jsonp'


Method 2: Enabling CORS (Cross-Origin Resource Sharing)

Step 1: Install Microsoft.AspNet.WebApi.Cors package. Execute the following command using NuGet Package Manager Console. Make sure to select your API project from "Default project" dropdown.

Install-Package Microsoft.AspNet.WebApi.Cors 

Step 2: Include the following 2 lines of code in Register() method of WebApiConfig class in WebApiConfig.cs file in App_Start folder

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");

config.EnableCors();

The Three Parameters means:
1. origins: Comma-separated list of origins that are allowed to access the resource. For example "http://www.pragimtech.com,http://www.mywebsite.com" will only allow ajax calls from these 2 websites. All the others will be blocked. Use "*" to allow all

2. headers: Comma-separated list of headers that are supported by the resource. For example "accept,content-type,origin" will only allow these 3 headers. Use "*" to allow all. Use null or empty string to allow none

3.methods: Comma-separated list of methods that are supported by the resource. For example "GET,POST" only allows Get and Post and blocks the rest of the methods. Use "*" to allow all. Use null or empty string to allow none

Step 3: In the Application, set the dataType option of the jQuery ajax function to json
dataType: 'json'


-----------------------------------------------------------------

EnableCors attribute can be applied on a specific controller or controller method. 

Then in WebApiconfig, you need only:
config.EnableCors();

 Apply the  EnableCorsAttribute on the controller class
[EnableCorsAttribute("*", "*", "*")]
public class EmployeesController : ApiController
{
}

To disable CORS for a specific action apply [DisableCors] on that specific action

Happy Coding !!!

Thursday, 27 September 2018

ERROR : The provider did not return a ProviderManifest instance. Could not determine storage version; a valid storage connection or a version hint is required. ../path/SampleDB.edmx Project Name - usinessObject

While using Entity framework, for the above error you had to open your .edmx file with Notepad and edit <Scheme> tag inside <edmx:StorageModels>.
You need to edit ProviderManifestToken="2012" to ProviderManifestToken="2008"

Happy Coding !!!

Wednesday, 26 September 2018

ERROR : WEBAPI : The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

If Running a WebApi(also using Entity Framework) generates an Error with :

Exception Message:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

ExceptionMessage Of Inner Exception: //It may Change in your Case
Type 'System.Data.Entity.DynamicProxies.Employee_24CA4E4B0F13FE40CFB3C932CBDA6A7A95E177B491C366CE6314ABBF16ACDF1D' with data contract name 'Employee_24CA4E4B0F13FE40CFB3C932CBDA6A7A95E177B491C366CE6314ABBF16ACDF1D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.

Solution:
You need to Disable Dynamic Proxy Creation by following Command:

sampleDBEntities.Configuration.ProxyCreationEnabled = false;

Happy Coding !!!

Start Text To Speech Functionality in Microsoft Word 2007

By Default, There is no Feature in Word To Start Text to Speech In Microsoft Word 2007. You have to make a Macro to enable TTS.The macros here use the Microsoft Speech Object Library from within Word to speak either the full document or a selected block of text.

From Word - Start the VBA Editor (Alt+F11)

Add a reference in the normal project to Microsoft Speech Object Library (Tools > References...)

Open Visual Basic From Word Document inside Developer Tab. On the Normal Project, Add a Module and write following code to it:


Option Explicit
Dim speech As SpVoice
Dim i As Integer

Sub SpeakText()
On Error Resume Next
If i = 0 Then
  Set speech = New SpVoice
  If Len(Selection.Text) > 1 Then 'speak selection
  speech.Speak Selection.Text, _
  SVSFlagsAsync + SVSFPurgeBeforeSpeak
  Else 'speak whole document
  speech.Speak ActiveDocument.Range(0, _
    ActiveDocument.Characters.Count).Text, _
    SVSFlagsAsync + SVSFPurgeBeforeSpeak
  End If
Else
  If i = 1 Then
  speech.Resume
  i = 0
  End If
End If
End Sub

Sub StopSpeaking()
On Error Resume Next
speech.Speak vbNullString, SVSFPurgeBeforeSpeak
Set speech = Nothing
i = 0
End Sub

Sub PauseSpeaking()
On Error Resume Next
If i = 0 Then
  speech.pause
  i = 1
Else
  If i = 1 Then
  speech.Resume
  i = 0
  End If
End If
End Sub


You will see these options in View > Macros..


Happy Coding !!!

Sunday, 23 September 2018

Difference Between Typeof and GetType() Methods

typeof keyword takes the Type itself as an argument and returns the underline Type of the argument whereas GetType() can only be invoked on the instance of the type.

typeof

System.Type t1= typeof(Employee); // Employee is a Type

GetType()

Employee employee= new Employee();
System.Type t2= employee.GetType(); // employee is an instance of the type Employee.


Happy Coding!!!

Saturday, 22 September 2018

Difference between Output (out) and Reference (ref) Parameter Modifier

1. Output parameters do not need to be initialized before they passed to the method.
The reason for this is that the method must assign output parameters before
exiting otherwise it will produce compile time error.
2. Reference parameters must be initialized before they are passed to the method.
The reason for this is that you are passing a reference to an existing variable. If you
don’t assign it to an initial value, that would be the equivalent of operating on an
unassigned local variable.

Happy Coding!!!

Wednesday, 19 September 2018

Sample Stored procedure with Try - Catch, Transaction

Here is the ready reference of the sample Stored procedure with Try - Catch, Transaction. It will boost your speed on writing stored procedures:

create procedure Sample_sp
(
@Error int out  
)
as
Begin
declare @trancount int;
set @trancount = @@trancount;
if @trancount = 0
Begin TRY
Begin Tran


if @trancount = 0
Begin
Set @Error = 1;  
commit Tran  
End
END TRY
BEGIN CATCH

Set @Error = 0;  
declare @error1 int, @message varchar(4000), @xstate int;
select @error1 = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback;
if @xstate = 1 and @trancount > 0
rollback ;

select 'ERROR:' +  cast(@error1 as nvarchar(10)) + ' ' + @message as ErrorMessage;

       
END CATCH
End

Happy Coding !!!

Script to Find and Update Extra Spaces in String / Column

There come to some scenarios when you need to find out and update Extra Spaces within your Data

Here is the Script to Find Extra Spaces in Column:

SELECT
[Rno]
,[Name] AS StringWithSpace
,LTRIM(RTRIM(REPLACE(REPLACE(REPLACE([Name],CHAR(32),'()'),')(',''),'()',CHAR(32)))) AS StringWithoutSpace
FROM tbl_RemoveExtraSpaces


Here is the Script to Update Extra Spaces in Column:

UPDATE tbl_RemoveExtraSpaces SET Name = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE([Name],CHAR(32),'()'),')(',''),'()',CHAR(32))))

Happy Coding !!!

Print Gridview from c#

Here are the Two events for Printing Gridview on Button Click Event. First One is for printing current page of Gridview and Second One is for printing all pages of Gridview. Here we are executing some Javascript to print Gridview after allowing or disallowing Gridview


protected void PrintCurrentPage(object sender, EventArgs e)
{
      GridView1.PagerSettings.Visible = false;
      GridView1.DataBind();
      StringWriter sw = new StringWriter();
      HtmlTextWriter hw = new HtmlTextWriter(sw);
      GridView1.RenderControl(hw);
      string gridHTML = sw.ToString().Replace("\"",   "'")
      .Replace(System.Environment.NewLine, "");           
      StringBuilder sb = new StringBuilder();
      sb.Append("<script type = 'text/javascript'>");
      sb.Append("window.onload = new function(){");
      sb.Append("var printWin = window.open('', '', 'left=0");
      sb.Append(",top=0,width=1000,height=600,status=0');");
      sb.Append("printWin.document.write(\"");
      sb.Append(gridHTML);
      sb.Append("\");");
      sb.Append("printWin.document.close();");
      sb.Append("printWin.focus();");
      sb.Append("printWin.print();");
      sb.Append("printWin.close();};");
      sb.Append("</script>");
      ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
      GridView1.PagerSettings.Visible = true;
      GridView1.DataBind();
}


protected void PrintAllPages(object sender, EventArgs e)
{
      GridView1.AllowPaging = false;
      GridView1.DataBind();
      StringWriter sw = new StringWriter();
      HtmlTextWriter hw = new HtmlTextWriter(sw);
      GridView1.RenderControl(hw);
      string gridHTML = sw.ToString().Replace("\"", "'")
      .Replace(System.Environment.NewLine, "");
      StringBuilder sb = new StringBuilder();
      sb.Append("<script type = 'text/javascript'>");
      sb.Append("window.onload = new function(){");
      sb.Append("var printWin = window.open('', '', 'left=0");
      sb.Append(",top=0,width=1000,height=600,status=0');");
      sb.Append("printWin.document.write(\"");
      sb.Append(gridHTML);
      sb.Append("\");");
      sb.Append("printWin.document.close();");
      sb.Append("printWin.focus();");
      sb.Append("printWin.print();");
      sb.Append("printWin.close();};");
      sb.Append("</script>");
     ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
     GridView1.AllowPaging = true;
     GridView1.DataBind();
}



Happy Coding !!!














Monday, 10 September 2018

Script to find sql edition, server type, version information, etc

Here is the Script to Find Machine, Sql Server Information:


SELECT
SERVERPROPERTY('MachineName') as Host,
SERVERPROPERTY('InstanceName') as Instance,
SERVERPROPERTY('Edition') as Edition, /*shows 32 bit or 64 bit*/
SERVERPROPERTY('ProductLevel') as ProductLevel, /* RTM or SP1 etc*/
Case SERVERPROPERTY('IsClustered') when 1 then 'CLUSTERED' else
'STANDALONE' end as ServerType,
@@VERSION as VersionNumber


Happy Coding!!!

Query to Count Tables, Stored Procedures, Triggers, Views and other objects in Sql Sever DataBase

Here is the Script to find User Defined Tables, System Tables, Internal Tables,, Stored Procedures, CLR Stored Procedures, Extended Stored Procedures:

SELECT 
    CASE TYPE 
        WHEN 'U' 
            THEN 'User Defined Tables' 
        WHEN 'S'
            THEN 'System Tables'
        WHEN 'IT'
            THEN 'Internal Tables'
        WHEN 'P'
            THEN 'Stored Procedures'
        WHEN 'PC'
            THEN 'CLR Stored Procedures'
        WHEN 'X'
            THEN 'Extended Stored Procedures'
    END, 
    COUNT(*)     
FROM SYS.OBJECTS
WHERE TYPE IN ('U', 'P', 'PC', 'S', 'IT', 'X')
GROUP BY TYPE



The following are all the types of entities in the sysobjects view:




AF = Aggregate function (CLR)
C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
FN = SQL scalar function
FS = Assembly (CLR) scalar-function
FT = Assembly (CLR) table-valued function
IF = SQL inline table-valued function
IT = Internal table
P = SQL Stored Procedure
PC = Assembly (CLR) stored-procedure
PG = Plan guide
PK = PRIMARY KEY constraint
R = Rule (old-style, stand-alone)
RF = Replication-filter-procedure
S = System base table
SN = Synonym
SO = Sequence object
SQ = Service queue
TA = Assembly (CLR) DML trigger
TF = SQL table-valued-function
TR = SQL DML trigger
TT = Table type
U = Table (user-defined)
UQ = UNIQUE constraint
V = View
X = Extended stored procedure


Happy Coding !!!

Friday, 7 September 2018

Allow only Numbers / Numerics in Textbox

Here is the script to make sure that user will only enter numbers:


<script type="text/javascript">
 var specialKeys = new Array();
 specialKeys.push(8); //Backspace
 function IsNumeric(e) 
 {
    var keyCode = e.which ? e.which : e.keyCode
    var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
    //document.getElementById("format").style.display = ret ? "none" : "inline";
    return ret;
 }
</script>

Call this script on your Textbox onkeypress Event

<asp:TextBox ID="mytxtbox" runat="server" onkeypress="return IsNumeric(event);"></asp:TextBox>

Happy Coding !!!

Remove Trailing Characters from a Number Column

There may be times when you got data from Third Source, which may be junk in some context as Suppose in Distance Column there could be a value of 8.5 km or in weight there may be a value of 444.90 kg. As these columns should be in number format. You should segregate those records and update them.,

Here is the script to find them:


SELECT Rno, Value, LEFT(Value,DATALENGTH(Value)-(PATINDEX('%[0-9]%',REVERSE(Value))-1)) AS ValueWithoutTrailChar
FROM tbl_RemoveCharacter



Script to remove trailing characters from Number column:

UPDATE tbl_RemoveCharacter
SET Value = LEFT(Value,DATALENGTH(Value)-(PATINDEX('%[0-9]%',REVERSE(Value))-1))




Happy Coding !!!

Check for special characters in column of a SQL Table

When we work with raw data, there may be chances of raw data in any column. As a DBA you had to check for any special / junk characters in you your table. You just had to check whether your column contains any non-alphanumeric characters. Just return that rows. If you want to allow any more characters to your column, you can alter your query accordingly.

Here is the script to find  non-alphanumeric characters in the column:

SELECT *
FROM YourTableName
WHERE ColumnName like '%[^a-Z0-9 ]%'

From this query, you will get that particular rows of non-alphanumeric characters. For removing those special characters from the column, replace special character with nothing ''.

UPDATE TableName
SET ColumnName =
(
CASE
WHEN [Name] LIKE '%[^a-zA-Z0-9 ]%'
THEN Replace(REPLACE( Name, SUBSTRING( Name, PATINDEX('%[~,@,#,$,%,&,*,^,&,%,!,'',",*,(,)]%', Name), 1 ),'') ,'-',' ')
--THEN REPLACE( Name, SUBSTRING( Name, PATINDEX('%[~,@,#,$,%,&,*,^,&,%,!,'',",*,(,)]%', Name), 1 ),'')
ELSE [Name]
END
)

Happy Coding !!!

Wednesday, 5 September 2018

ERROR : Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.

"Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed." in Console Window

When you are using UpdatePanel and want to download something(either Excel or anything). You will not get error in binding Gridiview or on any other thing. To rectify it you add these lines in either Page_Load Event or on that Button Click Event:


ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
  scriptManager.RegisterPostBackControl(this.YourButtonNameHere);
OR,

Use Trigger in Update Panel:

<Triggers>
                <asp:PostBackTrigger ControlID="YourButtonNameHere" />
</Triggers>

Happy Coding !!!

SQL Audits

1. sys.server_audits What it is: Lists all server-level audit objects . An audit is the top-level object that defines: Where to wri...