Create Forms in Symfony2 the easy way

8 05 2013

1: Create a New Bundle using Console

php app/console generate:bundle

It will ask for Namespace. Enter something like Test\AspXBundle.The Namespace should have a \ in it and should have a Bundle at the end

2: Create Entity using command below
php app/console doctrine:generate:entity

This command will ask for Shortcut Name, Entity and the Fields. Please enter the fields without adding the primary key columns in the field. It adds that automatically

3: Create CRUD using commandphp app/console doctrine:generate:crud
It will ask for the entity name like the previous command and will ask for annotation and other autogenerate options. When asked if you want to add to routing file automatically. type yes.

If the command does not add the lines to your routing.yml file. Just copy them from the console and add to the routing.yml file manually.

Now you can browse to your newly created form. Enjoy 🙂





Add JqueryUI DatePicker to Symfony twig

8 05 2013

1: Get Jquery-Ui from website
   http://jqueryui.com/download/
2: Unzip the files
3: Copy the file jquery-ui-1.10.3.custom.js to your bundle suppose I copy to MyBundle at the path
   Resources/public/js
4: Add the line below to your base.html.twig file in the javascripts block
   ‘@MyBundle/Resources/public/js/jquery-ui-1.10.3.custom.js’
5: Copy the file jquery-ui-1.10.3.custom.min.css to your bundle at the path Resources/public/css
6: Add the line below to your base.html.twig file in the stylesheets block
7: Copy the image files to images directory in the css folder
8: Run the commands
   app/console assets:install
   app/console assetic:dump
9: Add the line to your Form
   ->add(‘myDate’,’date’,array(
            ‘widget’ => ‘single_text’,
            ‘format’ => ‘dd-MM-yyyy’,
            ‘attr’ => array(‘class’ => ‘date’)
            ))
   These line will help the form to create the myDate with class “date”
10: Add the lines below to your html.twig file
    <script type=”text/javascript”>
    $(document).ready(function() {
            $(‘.date’).datepicker({ dateFormat: ‘dd-mm-yy’ })
    });
    </script>
   These lines will create a datepicker for every input control with the class date





Reset Password – ASP.Net Forms Authentication with hashed password enabled?

18 01 2013

If you are stuck in trying to reset password in asp.net with hashed password enabled. and
You want to change the password then you can use the same MemberShipUser object to do that using the function ChangePassword().

Below is the code that can be used:

muser.ChangePassword(muser.ResetPassword(), Model.Password);





RDLC SSRS Reports Error “Failed to enable constraints. One or more rows contain values…”

19 12 2012

I Encountered  the error below while creating a report using RDLC reports.

Failed to enable constraints. One or more rows contain values

While searching for the error on the web I found out that RDLC reports will not show unless the Primary Key in the dataset has unique values.

Sometimes this error comes when one is using a view and not a Table. The best way is to figure out what’s the unique key in your view. If you cannot fix that from there then open the DataSet and change the primary key.

There will be a key which will be unique in the view. If not combine one or more columns to create a key. Select the columns in the DataSet and right click then select “Set Primary Key” option. Now reload your report you will be able to view your report. 

How to find what is your primary key can be done by opening the DataSet File. You can preview the data in the DataSet to view the rows identifying whether the key is duplicating any values or not.





JQuery Set Current Date for DatePicker

4 12 2012

To set the current date in DatePicker you have to set the setDate option with new Date. But here is a trick which normally one would ignore:

Normally you would write the below code:

$(“#My_Control_ID”).datepicker(‘setDate’, new Date());

or

var currentDate = new Date();
$(“#My_Control_ID”).datepicker(‘setDate’, currentDate);

But this won’t work since the datepicker for my_control_id is not set. so you have to set the datepicker first. Just adding an extra datepicker() to initialize the datepicker before setting the options will work. 

So the above code if correctly written should be:

$(“#My_Control_ID”).datepicker().datepicker(‘setDate’, new Date());

or

var currentDate = new Date();
$(“#My_Control_ID”).datepicker().datepicker(‘setDate’, currentDate);





How to Get Full page Url

29 08 2012

Ways to get full page Urls
1: ASP Classic:
dim currentURL

if request.serverVariables(“HTTPS”) = “ON” then
currentURL = “https://&#8221;
else
currentURL = “http://&#8221;
end if

currentURL = currentURL & request.serverVariables(“SERVER_NAME”) & request.serverVariables(“URL”)

if len(request.serverVariables(“QUERY_STRING”)) > 0 then
currentURL = currentURL & “?” & request.serverVariables(“QUERY_STRING”)
end if

2: Javascript
document.URL

3: php
$url=”http://&#8221;.$_SERVER[‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’];

4: Asp.Net
Request.Url.AbsoluteUri

5: DotNetNuke
DotNetNuke.Entities.Tabs.TabController.CurrentPage.FullUrl

6: SharePoint

SPContext.Current.Web.Url +”/”+ SPContext.Current.File.Url
Note: If you use Web, please keep in mind that it gives you the web application information not the current file information, where as the File represents a file in a SharePoint Web site that can be a Web Parts page or a file in folder or library that you want to upload





gtalk:chat VS Gtalk Badge

29 08 2012

Some days ago I was asked if there is a better way to place a gtalk hyperlink on website than gtalk:chat.
My first answer was why you want to change it. This opens up the gtalk on your system so its good to use this. Apparently I was not aware that if you dont have gtalk installed on your system, you browser would give you an Unknown Protocol message.
So if you want that your browser does not give you that error and people can also see if you are online or offline use Gtalk badge on your website instead.
Login to the account you want to use. Go to the link
http://www.google.com/talk/service/badge/New
and create a badge for yourself and post the code in any page on your website.





Implementing Loading gif on a page

24 06 2012

I have been trying to Implement Loading Gif without using the update panel in ASP.Net.

While researching on how to do this. I came across multiple ways to do this.

1: Using JQuery 

use the ajaxStart and ajaxStop function

If you put these functions to a div on a page like shown below the div will show automatically when an Ajax event starts and will hide when the event ends. loading is the div’s id in the below function.
 $("#loading").ajaxStart(function(){
  $(this).show();  }).ajaxStop(function(){
    $(this).hide();  
});

You can use the same method shown above to implement css classes for the div showing the loading gif and an opaque div on top of the elements on the form so that the user does not click anything until the event has executed.

2: Using JQuery with your own code while there is no Ajax or Partial Postback

ASPX code:

<div id="divSiteFrame" style="background-color: #777777; display: none; left: 0px;
 position: absolute; top: 0px;">
 </div>
 <div id="divProgress" style="display: none; height: 130px; left: 0px; position: absolute;
 top: 0px; width: 281px;">
 <img src="/images/loading.gif">
 </div>

Javascript Code

function displayProgress() {
 $('#divProgress').show();
 $('#divProgress').css('z-index', 2);
// this takes the id name as a parameter
 Move2Center('divProgress'); }
function Move2Center(id) {
 var obj = document.getElementById(id);var w1 = GetWidth(obj);
 var h1 = GetHeight(obj);
 var w = getWindowSize();
var scr = getScrollXY();
 var left = scr[0] + parseInt(w[0] / 2) - parseInt(w1 / 2);
 var top = scr[1] + parseInt(h1 / 2);
 obj.style.left = left + 'px';
 obj.style.top = top + 'px';
}
function getWindowSize() {
 var myWidth = 0, myHeight = 0;
 if (typeof (window.innerWidth) == 'number') {
 //Non-IE
 myWidth = window.innerWidth;
 myHeight = window.innerHeight;
 } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
 //IE 6+ in 'standards compliant mode'
 myWidth = document.documentElement.clientWidth;
 myHeight = document.documentElement.clientHeight;
 } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
 //IE 4 compatible
 myWidth = document.body.clientWidth;
 myHeight = document.body.clientHeight;
 }
 return [myWidth, myHeight];
}
GetWidth = function (elem) {
 function _Convert(val) {
 if (!val) { return; }
 val = val.replace("px", "");
 if (isNaN(val)) { return 0; }
 return parseInt(val);
 }
 var currentStyle;
 if (elem.currentStyle) { currentStyle = elem.currentStyle; }
 else if (window.getComputedStyle) { currentStyle = document.defaultView.getComputedStyle(elem, null); }
 else { currentStyle = elem.style; }
 return (elem.offsetWidth -
 _Convert(currentStyle.marginLeft) -
 _Convert(currentStyle.marginRight) -
 _Convert(currentStyle.borderLeftWidth) -
 _Convert(currentStyle.borderRightWidth));
}
GetHeight = function (elem) {
 function _Convert(val) {
 if (!val) { return; }
 val = val.replace("px", "");
 if (isNaN(val)) { return 0; }
 return parseInt(val);
 }
 var currentStyle;
 if (elem.currentStyle) { currentStyle = elem.currentStyle; }
 else if (window.getComputedStyle) { currentStyle = document.defaultView.getComputedStyle(elem, null); }
 else { currentStyle = elem.style; }
 return (elem.offsetHeight -
 _Convert(currentStyle.marginTop) -
 _Convert(currentStyle.marginBottom) -
 _Convert(currentStyle.borderTopWidth) -
 _Convert(currentStyle.borderBottomWidth));
}
function getScrollXY() {
 var scrOfX = 0, scrOfY = 0;
 if (typeof (window.pageYOffset) == 'number') {
 //Netscape compliant
 scrOfY = window.pageYOffset;
 scrOfX = window.pageXOffset;
 } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
 //DOM compliant
 scrOfY = document.body.scrollTop;
 scrOfX = document.body.scrollLeft;
 } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
 //IE6 standards compliant mode
 scrOfY = document.documentElement.scrollTop;
 scrOfX = document.documentElement.scrollLeft;
 }
 return [scrOfX, scrOfY];
}
function displaySiteBlockFrame() {
 divsiteframe = $("[id$=divSiteFrame]");
 $(divsiteframe).show();
 $(divsiteframe).css('z-index', 1);
 var size = getWindowSize();
 $(divsiteframe).css('width', 1000);
 $(divsiteframe).css('height', $(document).height()-225);
 $(divsiteframe).css('opacity', 0.7);
}
function ShowProgressBar() {
 displayProgress();
 displaySiteBlockFrame();
}

ASPX.CS Code:

btnfirstSearch.Attributes("onclick") = "return ShowProgressBar();




List of selected items seperated by comma in listbox

24 06 2012

Over the years I have come across multiple styles of getting a string with the selected items from a list box.

in VB you can do it like this

If Me!NamesList.ItemsSelected.Count <> 0 Then
For Each oItem In Me!NamesList.ItemsSelected
If iCount = 0 Then
sTemp = sTemp & Me!NamesList.ItemData(oItem)
iCount = iCount + 1
Else
sTemp = sTemp & “,” & Me!NamesList.ItemData(oItem)
iCount = iCount + 1
End If
Next oItem
Else
MsgBox “Nothing was selected from the list”, vbInformation
Exit Sub ‘Nothing was selected
End If
In JavaScript you can do it like this

listBox1 = document.getElementById(listBox);
var options=[],opt;
for (var i=0, l=listBox.options.length; i < l; ++i) {
opt = listBox.options[i];
if (all || opt.selected ) {
options.push(opt.value);
}
}
return options.join(“,”);

The best of all using LINQ One liner code in VB is given below.

Dim values As String = [String].Join(“, “, ListBox1.Items.Cast(Of ListItem)().Where(Function(i) i.Selected).[Select](Function(i) i.Text).ToArray())





Counting the characters in a String VS actual no of bytes in a string

18 06 2012

Some time ago i came across a code where the developer used regular expressions to count the characters in the code using ^[\S\s]{0,n}
I had used it before also but this time I had to used Page.IsValid in the code for some reason.

Now what happened was that When I pasted the text from some word document. In some cases It would give error saying the number of characters have exceeded. In other cases not.

The first one is not an issue but the second one when it goes to the code behind where the Page.IsValid is. It will not say that the page is valid and if you have a ValidatorSummary on the page. It will show that the string is of more characters than the limit. Please notice that it will not show error unless you have a Page.IsValid in the code behind.

When I did some research I found out that if the text you pasted is UTF-8 then a character can take from 1 upto 4 bytes. That means that some characters can be of more than 1 in length. If you check using Javascript function String.Length it will show you that the string has length n but in the code behind it will show you that the strin has n+m length (m is any variable).

So to solve this issue you either have to use code behind so that if you are inserting the string in the DB it does not give error that the text will be truncated.
or you use Javascript encodeURI()
you can check this at http://www.w3schools.com/jsref/jsref_encodeuri.asp

function checkLength() {
var countMe = document.getElementById(‘<%=txtBox1.ClientId%>’).value
var escapedStr = encodeURI(countMe)
if (escapedStr.indexOf(“%”) != -1) {
var count = escapedStr.split(“%”).length – 1
if (count == 0) count++
var tmp = escapedStr.length – (count * 3)
count = count + tmp
} else {
count = escapedStr.length
}
alert(“Actual size of string is ” + count);
alert(“Displayed Characters in the string are ” + countMe.Length;
}

To Sumarize use URLEncoding and then remove the strings with % and then give the length.

There might be drawbacks of the above methods. If anyone has better Ideas please post them in the comments so that It can help me also.