The request body did not contain the specified number of bytes. Got 0, expected xxx – Internet Explorer Issue

When you try to re-POST subsequent requests from Internet Explorer browser it only sends only the header data is posted. As a result you will receive error in response – The request body did not contain the specified number of bytes. Got 0, expected xxx. There is already a Hotfix available at Microsoft Knowledge Base https://support.microsoft.com/en-gb/kb/895954.

General Repro Steps –

  1. For every first XMLHttpRequest, a keep alive connection (TCP Connection) is created which is used by any subsequent request. If the connection is forcibly closed by the browser, then browsers will try to create a new connection by resubmitting the request.
  2. For GET Requests it will work without any issues. But for POST it will only send Request Headers and not the body in Internet Explorer. That’s why you will receive error – The request body did not contain the specified number of bytes. Got 0, expected xxx.
  3. As a solution either install above mentioned Hotfix or Use NEW unique URL by adding TimeStamp to URL to avoid any re-POST request.

For e.g.

var urlToPost = "ajaxUrlToPost.svc?stamp=' + new Date().getTime();

SharePoint 2010/2013 Date Comparison in different Time Zones

Working with DateTime in SharePoint is always tricky since it stores values internally in UTC and when we tried to access it in CSOM or SOM in different Time zone we have to be very careful while filtering on Created, Modified Date columns.

Time Zone plays very crucial roles in any Date Time difference calculation. When we do difference in two date times, it must be in same Time Zone offset otherwise the result will never be correct. Here, TimeZoneInfo class plays main role. To get specific time zone details we have to use TimeZoneInfo.FindSystemTimeZoneById method which will take input of Zone Id. All available Time Zone Id’s can be found at MSDN https://msdn.microsoft.com/en-us/library/gg154758.aspx.

To explain this problem lets take a example that we need to find all SharePoint List items which was created in last 5 minutes.

First we will retrieve all Items from a List which is created Today. We will use CAML Query to get these items.
[csharp]

// Store result in temporary Table
DataTable dataResult = new DataTable();
dataResult.Columns.Add(“ID”);
dataResult.Columns.Add(“Title”);

//Get List Data
SPWeb sbWeb = SPContext.Current.Site.RootWeb;
SPList list = sbWeb.GetList(“MyCustomList”);
SPQuery listQuery = new SPQuery();

// Get items for todays date
listQuery.Query = “<Where><Eq><FieldRef Name=’Created’ /><Value Type=’DateTime’><Today /></Value></Eq></Where>”;
SPListItemCollection items = list.GetItems(listQuery);

[/csharp]

Iterate through each list item and perform Date time conversion.

[csharp]

foreach (SPListItem item in items)
{
if (item[“Title”] != null && item[“ID”] != null)
{

// Get UTC Now Date Time
DateTime utcNowDate = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Utc);

// Find the Server Time Zone Info which is configured under Central Administration -> Web Application -> General Settings
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(“Pacific Standard Time”);

// Convert UTC Now Date Time to server’s Time Zone i.e. into Pacific Standard Time in our example.
DateTime convertedUtcNowDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcNowDate , timeZoneInfo);

// Find the Date time difference into TimeSpan
TimeSpan diffResult = convertedUtcNowDateTime – Convert.ToDateTime(item[“Created”]);

// Create 5 Minutes Time Span object
TimeSpan fiveMinutesSpan = new TimeSpan(0, 5, 0);

// Compare method will return -1 if first time interval is shorter than second and return 0 if both time interval are equal. Read more about this at https://msdn.microsoft.com/en-us/library/system.timespan.compare(v=vs.110).aspx
int result = TimeSpan.Compare(diffResult, fiveMinutesSpan);

// If result is 0 Or -1 it means items is created in last five minutes.
if (a < 1) { DataRow row = dataResult.NewRow(); row["Title"] = item[SPBuiltInFieldId.EncodedAbsUrl].ToString(); row["ID"] = item[ColumnName.ReportUrl].ToString(); data.Rows.Add(dr); } } } [/csharp] Resulting DataTable will have the filtered result. Sharing is Caring 🙂

jQuery based Resource Localization

Create client side (JavaScript) based Resource Localization in any web application. Extremely light-weight library, just 3KB (Minified) and 8KB(Debug) version.

Implementing client side localization into any web application is always challenge. Most of web technologies provide localization using server-side technologies. For e.g. .Net application uses Resources Files(.resx) to implement localization into globalization application.

Nowadays world is extensively moving towards Asynchronous development models like AJAX / SPA. Several frameworks, libraries are already available on the web. To access these server side resources requires custom REST services / handlers to be additionally implemented into the host application.

This plugin makes life easier where you can manage all your localized resources into plain Text or JavaScript file. Based on current culture provided to this plugin, it loads associated resource entries for use. To enhance performance it Cache data for subsequent Initialization calls. So now no more server side development required for managing localization. It can be used in any web applications like SharePoint On-Premise / Online, Php, ASP.Net MVC, JAVA and many more as long as these technologies supports JavaScript.

Download Pugin from Github Github.

Install via Nuget Package.

JQuery Culture Information Plugin

Accessing Culture Information for all available cultures in JavaScript is always difficult and most of the web developer has to search on internet for this information. There may be several options available to fetch this information into Server-side technologies like ASP.Net, JAVA, PHP, and etc. But in JavaScript it is very difficult to find this information at one place.

To solve this problem, I have created small jQuery plugin which will give you this information at one place. You can search for Culture information by LCID (for e.g. 1033) or by Culture Name (for e.g. en-US), which will return you JSON Object. This plugin can be used in any of your favorite application which supports JavaScript.

  1. Refer to the Github Project JQuery Culture Information Plugin
  2. Install via the NuGet Package Install-Package PritamBaldota.JqueryCultureInfo

Sharing is Caring 🙂

Associate Custom Content Type with SharePoint 2010/2013 List Or Library using PowerShell

To automate deployment in SharePoint 2010/2013 on-premise solution, we have to use PowerShell. One of the deployment activity is creating SharePoint Custom Lists/Libraries and associating them with custom created content types. In this article we will be focusing only how to add/remove content types from the List/Library.

To add content type follow below steps –

  • Get Reference to Site collection and root web to get the content types.

[shell]

$siteRef = Get-SPSite http://domain/site
$rootWebRef = $siteRef.RootWeb

[/shell]

  • Get the target web reference to which content type will be added for List/Library.

[shell]
$web = Get-SPWeb http://domain/site/web
[/shell]

  • Get the reference to target list / library

[shell]
$listRef = $web.Lists[“List Title”]
[/shell]

  • Enable the management of content type for this list/library.

[shell]

$listRef.ContentTypesEnabled  = $true
$listRef.Update()

[/shell]

  • Get the deployed Content Type reference from root web which will be added to the target list.

[shell]
$targetContentType= $rootWebRef.ContentTypes[“CustomContentType”]
[/shell]

  • Check if Content is already exists from ContentTypes collection of a List. If not found then add the content type to the list.

[shell]
$contentTypeExist = $listRef.ContentTypes[$contentType.Name]
if($contentTypeExist -ne $null)
{
$listRef.ContentTypes.Add($targetContentType)
$listRef.Update()
}
[/shell]

To delete content type follow below steps –

To delete content type association from list, we have to get the reference of associated content type and pass the Id of content type to Delete method on ContentTypes collection.

[shell]

$contentTypeExist = $listRef.ContentTypes[$contentType.Name]

$listRef.ContentTypes.Delete($contentTypeExist.Id)

[/shell]

This is how the complete code will look like –

[shell]

$siteRef = Get-SPSite http://domain/site
$rootWebRef = $siteRef.RootWeb
$web = Get-SPWeb http://domain/site/web

$listRef = $web.Lists[“List Title”]
if ($listRef -ne $null)
{
$listRef.ContentTypesEnabled  = $true
$listRef.Update()
$targetContentType = $rootWebRef.ContentTypes[$contentType.Name]
if($targetContentType -ne $null)
{
$contentTypeExist = $listRef.ContentTypes[$contentType.Name]
if($contentTypeExist -ne $null)
{
Write-Host “Adding Content Type – ” $targetContentType.Name -ForegroundColor Green
$listRef.ContentTypes.Add($targetContentType)
}
else
{
Write-Host ”  Content Type already exists – ” $targetContentType.Name -ForegroundColor Green
}
}
$listRef.Update()
}

[/shell]

Happy Coding 🙂

SQL Server Database Triggers

  • A trigger is an object contained within an SQL Server database that is used to execute a batch of SQL code whenever a specific event occurs.
  • A trigger is “fired” whenever an INSERT, UPDATE, or DELETE SQL command is executed against a specific table.
  • A Trigger is associated with Database Table

There are three types of Database Triggers –

  1. INSERT TRIGGER
  2. UPDATE TRIGGER
  3. DELETE TRIGGER

INSERT TRIGGER

  • Body of trigger can have any block which a Stored Procedure can have
  • Body can call SP using Exec
  • When SQL server processes this “INSERT” command, it creates a new virtual table, which contains all nine of the fields in the “INSERT” command. This table is named “Inserted”, and is passed to the trig_addAuthor trigger.
  • At any one time, each trigger only deals with one row.
  • So for INSERT Trigger only hold reference of Inserted virtual Table

CREATE TRIGGER trig_addAuthor
ON authors
FOR INSERT
AS
— Get the first and last name of new author
DECLARE @newName VARCHAR(100)
SELECT @newName = (SELECT au_fName + ‘ ‘ + au_lName FROM
Inserted)
— Print the name of the new author
PRINT ‘New author “‘ + @newName + ‘” added.’

UPDATE TRIGGER

  • The “UPDATE” function is used to check whether or not the “au_fName” and “au_lName” fields have been updated by the “UPDATE” Query
  • “UPDATE” triggers have access to two virtual tables: Deleted (which contains all of the fields and values for the records before they were updated), and Inserted (which contains all of the fields and values for the records after they have been updated)
  • Update triggers can also be used to check field constraints and relationships

CREATE TRIGGER trig_updateAuthor
ON authors
FOR UPDATE
AS
DECLARE @oldName VARCHAR(100)
DECLARE @newName VARCHAR(100)
IF NOT UPDATE(au_fName) AND NOT UPDATE(au_lName)
BEGIN
RETURN
END
SELECT @oldName = (SELECT au_fName + ‘ ‘ + au_lName FROM Deleted)
SELECT @newName = (SELECT au_fName + ‘ ‘ + au_lName FROM Inserted)
PRINT ‘Name changed from “‘ + @oldName + ‘” to “‘ + @newName + ‘”‘

DELETE TRIGGER

  • It has only access to the virtual table “Deleted”
  • Same as INSERT, UPDATE

ADVANTAGES Of TRIGGERS

  1. When triggers are used correctly, they can save a lot of development work. One of the main benefits of using triggers is that they are stored in a central repository (the database), meaning that they are accessible from all client applications / web pages that can connect to the database.
  2. Before triggers came along, if we had a table that needed to be updated and we wanted to perform some actions after that update, then we would have to “hard code” the extra SQL into our application. This meant that if we wanted to change the code later down the track, then each client would need the updated version of our application. This is both annoying and time consuming.

Happy Coding 🙂

ActionScript for Designers Part 1- Basics of ActionScript

Hi Guys,

Generally Flash comes with two meanings – 1) Flash for Designer & 2) Flash for Developers (ActionScript). Designer always threaten about ActionScripting. It is not that complicated at basic level where Designer can levarage the benefits of ActionScripting to their Creative Work without having Programming knowledge.

If you already know the Flash, using tools and creating animations, you may want to add some interactivity to your skills.

Actionscript is written as a series of statements within a Flash movie, and is placed either in a frame or in an external class file. In the Flash intro class, we also put actionscript on buttons and movieclips, but that was done for the sake of easier learning.

ActionScript, an object oriented programming (OOP) language built for Flash/Flex developement. There are versions of actionscript like Flash (7/8/ cs2 etc..), these are ActionScript 1.0, 1.1, 2.0, 3.0.  Based on the Flash version, adobe provides default scripting version which is located at Publish Settings in Flash IDE (Integrated Development Environment).

 1. TRACE

Trace function allows you to print information to your output window in Flash. This is not visible to those who view the SWF on the web. Trace is especially useful for debugging, if something goes wrong and you want to figure out why. You can trace simple text or the contents of variables.

trace(”Text or variables can go here”);

2. FUNCTIONS

Functions are basically reusable chunks of code that you don’t want to rewrite over and over again.  It saves your coding time and add scalability layer to your code.

function myFuncationName(inputValue)
{
 trace(inputValue);
}

3. TIMELINES

Flash Timeline refers to the sequence of frames and keyframes in either a movieclip or on the Stage or main movie. The stage’s timeline can be treated in actionscript as an instance of a movieclip. It is represented either as _root (from any timeline in the movie which is deeply nested to N-level), or as _parent from a movieclip placed on main timeline frames. It is often referred to as the main timeline.

 

5. PLAYHEAD CONTROL

Using simple playhead control, you can take control of your timeline. A lot of animations you can place on timeline which can be easily played using playhead functions. These include:

gotoAndStop(frameVariable);
gotoAndPlay (frameVariable);
stop();
 
 
 6. ASSIGNING ATTRIBUTES

  

Assigning attributes allows you to dynamically store or update items in your variables(Container) using Actionscript. This includes visibily, scale, alpha, position etc… Some examples:

myMovieClip_mc._visible=false;
myMovieClip_mc. _alpha=35;
myMovieClip_mc._x=50;
myMovieClip_mc._y=50;

7. IF STATEMENTS

 
if statements are used to take decisions inside code. It is straightforward.
if (myVariable==myOtherVariable)
{
trace(myVariable);
}
for e.g.
if(mc_MyMovieCliep._alpha==50)
{
   trace(“Alpha is 50”);
   //do something
}
else
{
 //do alternative
}

8. FOR LOOP & WHILE LOOP


Loops are used to perform specific tasks to certain number of times or until a condition satifies. There are two kind of loops – FOR loop, & WHILE loop.
for (var startCounter=0; startCounter<5; startCounter++)
{
trace(startCounter);
}

var startCounter=0;
while (startCounter != 10)
{
trace(“Count “+ startCounter);
startCounter++;
}

9. BUTTONS

Buttons can be used to control movies. To accomplish this, you need to attach action to the button or movie clip with the on() function. You could write actions in the Timeline using event handler functions with instance names of button or movie clips or you can write actions on button or movie clips, for this you need to select button or movie clip and Press F9 to open Action window.
on(release)
{
 mc_myMovieClip._visible=false;
}

 

Hope you like this tutorials. I am working on it to proceed further with more detailed one.

Happy Coding 🙂

Generate Page URL Name for CMS, Blogs Application

Hi All,

To give the Name to the Page can be handeled by many ways like

Using GUID (Issue- Cant identify exactly while browsing through pages)
Using Session (Issue-Same as above)
Using Page Title provided in Text Field (We will see this)
We are going to implement the scenario 3. We will first see what are our constraints for page url name.

It should be only Alphanumeric enabled like – About-Us.aspx
No other character should include in the page name like – %,@,$ etc
Its just about Regular Expression to identify the alphanumeric characters. The reqular expression is in System.Text.RegularExpressions namespace.

Regex.Replace(strInput, “[^\\w]”, “”);

If you give the page Title to – About % US #$ output will be AboutUs.aspx

Happy Coding 🙂

Optimizing SQL Server Database Design Tips & Tricks – Part 1

Database design is most crucial part in application development. Database can be anything SQL Server, MySQL, Oracle, etc. I will consider SQL SERVER as a part of discussion.

Tunning the database depends upon various factors like whether one datatype is better depends on the context of it’s usage. Following are most common datatypes used in database.

Numbers Datatype (For storing Primary Keys, Foreign Keys, Status etc) 

An int requires 4 times the storage of a tinyint. More storage means more data and

index pages to read / write, more I/O and thus potentially more seek time. It also means more memory consumption.

For eg. Desigining User Role and Users Table. Generally application will not have more than 5-10 user roles like Admin, Manager, Employee, etc. Most of developers design the table like - 

Table – UserRole

RoleId – Integer (whole number) data from –2^31 (–2,147,483,648) through 2^31–1 (2,147,483,647). It takes 4 Bytes to store.

RoleName – Varchar (50)

Which is not suiting to our requirements. Instead of int we can use tinyint – Integer data from 0 to 255. Storage size is 1 byte. 

 

DateTime Datatype (For storing dates)

Most of the times database tables required date to be stored to maintain record creation date. 

DateTime data type are stored internally two 4-byte integers. The first 4 bytes store the number of days before or after the base date: January 1, 1900. The base date is the system reference date. The other 4 bytes store the time of day represented as the number of milliseconds after midnight.

The smalldatetime data type stores dates and times of day with less precision than datetime. The Database Engine stores smalldatetime values as two 2-byte integers. The first 2 bytes store the number of days after January 1, 1900. The other 2 bytes store the number of minutes since midnight.

So, instead of using datetime as datatype smalldatetime is more efficient in general development.

 

STRING DATATYPE (Storing text data)

All string data stored inside varchar, text, ntext, nvarchar, etc. 

For eg. FirstName data field developers used varchar or nvarchar with default size i.e. 50. We should know the scope of the filed in terms of maximum characters. Generally first name, last name etc.. won’t take more than 20 – 25 characters. So instead of 50 if we use 20 characters we can save half the storage, index size which will increase performance of queries. 

 These are the basics which needs to keep in mind while developing applications. 

Happy Coding … 🙂

GridView in ASP.Net

GridView plays very important component in ASP.Net Application. It covers most of the basic reports for which you do not need any reporting component like Crystal Report, Report Viewer etc.

Major concern with any data entry form is Add, Edit, Delete and View.


Assumptions-

We are using SQL Server Express editions as Database.

Table Name- Employees

Fields- EmpId, EmpName, Designation

Take GridView control on page and set the ID property to dgEmployees.

Go to property builder by right click on GridView -> Show Smart Tag -> Edit Columns. Uncheck Auto-Generate Field from the Property window.

Add three TemplateField Column for Employee Name, Designation, & Delete Button. Add Edit button from CommandField Group from Property Window.

TemplateField Colums have ItemTemplate, Alternating Item Template, Edit Template, Header Template, Footer Template.

Each template columns Item Template field contains Label Control & Edit Template contains TextBox control for Editing item. Set the Binding Field name to the Text Property of both controls for each template field to the respective Database Column Name i.e Eval(“EmpName”).

Set the DataKeyNames property of GridView to Primary Key Column of DataBase i.e. EmpId. This property binds the database column field value to each row of gridview as a Unique Identifier.

Set the data bindings for Delete Button for CommandArgument Eval(“EmpId”); for saving the ID column value from database for fetching the ID field value while Deleting the Record. Set the CommandName property to Delete Button to CMDDelete. The CommandName property can contain any string name which can be used to recognize the type of command invoked from gridview. Because when any of the event generated in GridVeiw it fires RowCommand Event. In this event we have to handle the Delete Button Code. Instead if you are using default Delete Button of GridView then register for RowDeleting event of GridView and for accessing Unique ID columnvalue from database you need to fetch the id from DataKeys collection of GridView. For e.g.

int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);

Place the Textbox control in the grids Footer template for Adding new record. Set the CommandName to CMDAdd for Add button.

Register events for Edit, Update, Cancel button of gridview ??” RowEditing, RowUpdating, RowCancelEditing.

View in GridView

To view data in gridview is very simple. Just create a DataSet using SqlDataAdapter??Ts Fill method and set the GridViews DataSource Property to DataSet.

Create a Method to Bind the GridView to DataSource named BindGrid. This method fetches data from the GetEmployees method which returns DataSet from Employees table.

Call the BindGrid on Page_Load in !IsPostBack block to fill the grid by default.

private void BindGrid()

{

dgEmployees.DataSource = GetEmployees();

dgEmployees.DataBind();

}



private DataSet GetEmployees()

{

DataSet ds = new DataSet();

SqlConnection conn = new SqlConnection();

conn.ConnectionString =ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;

SqlDataAdapter da = new SqlDataAdapter("Select * From Employees", conn);

try

{

da.Fill(ds);

return ds;

}

catch { }

finally

{

conn.Close();

conn.Dispose();

}

return null;

}

Edit in GridView

For Editing Register RowEditing event of GridView. To switch the normal mode to Edit mode of gridview EditIndex property plays important role. EditIndex specifies which row is in edit mode by setting RowIndex to it. By default EditIndex of gridview is -1 (Normal mode). If you want to edit 3rd Row then set the EditIndex to 2 (Row index starts from 0,1,2..).

After setting editindex refresh the grid by calling BinGrid. GridViewEditEventArgs object knows the current row index so getting row index of the selected row in gridveiw is not big deal; just e.NewEditIndex (e object of GridViewEditEventArgs).

protected void dgEmployees_RowEditing(object sender, GridViewEditEventArgs e)

{

dgEmployees.EditIndex = e.NewEditIndex;

BindGrid();

}


Cancel in GridView


For Cancel just reset the GridView editindex to default i.e. -1 and refresh the grid.

protected void dgEmployees_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

dgEmployees.EditIndex = -1;

BindGrid();

}


Update in GridView

For Update register RowUpdating event of the gridview. Find the Unique id for updating the row from DataKeys collection of gridview.

int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);

Find the controls in the selected row by using FindControl method of gridviews rows collection and collect data from the text boxes.

TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl(“txtEmpName”) as TextBox;

TextBox txtdesign = dgEmployees.Rows[e.RowIndex].FindControl(“txtDesignation”) as TextBox;

Finally update the row and refresh the grid.

if(txtname!=null && txtdesign!=null)

UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());

dgEmployees.EditIndex = -1;

BindGrid();


Complete code-

protected void dgEmployees_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

int empId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);

//Find Text boxex

TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl("txtEmpName") as TextBox;

TextBoxtxtdesign=dgEmployees.Rows[e.RowIndex].FindControl("txtDesignation") as TextBox;

if(txtname!=null && txtdesign!=null)

UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());

dgEmployees.EditIndex = -1;

BindGrid();

}


Custom Delete in GridView

For Delete register RowCommand event of the gridview. Find the Unique id for deleting the row from DataKeys collection of gridview. Check for CommanName and invoke delete method for the selected row.

protected void dgEmployees_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName.Equals("CMDDelete"))

{

int EmpId = Convert.ToInt32(e.CommandArgument);

DeleteEmployee(EmpId);

//Refresh Grid

BindGrid();

}

}


Add in GridView

Adding from GridView is just some trick with Footer Template. I added textboxes and a add button in the footer row of the gridview. When u are in Normal mode it is visible else it is invisible to synchronize between edit and add.

Like Updating find the Textbox and pass the values to Addemployee method like

else if (e.CommandName.Equals("CMDAdd"))

{

TextBox txtname = dgEmployees.FooterRow.FindControl("txtEmpName") asTextBox;

TextBox txtdesign = dgEmployees.FooterRow.FindControl("txtDesignation") as TextBox;

if (txtname != null && txtdesign != null)

{

AddEmployee(txtname.Text.Trim(), txtdesign.Text.Trim());

BindGrid();

}

}

The Complete code for EditEmployee, AddEmployee, UpdateEmployee, DeleteEmployee is in Source File.

The code should be in RowCommand event only. Due to this we use CommandName for different button control to differentiate between the type of code to be handled by gridview.