Friday, December 06, 2013

Chronicles on Migration From Entity Framework to Telerik OpenAccess - 1


I have to replace all the EntityDataSources to OpenAccessLinqDataSource's(or the old OpenAccessDataSource)
So this below:
<asp:EntityDataSource runat="server" ID="edsDegree" ConnectionString="name=Entities"  
DefaultContainerName="Entities" EnableFlattening="False"
    EntitySetName="Degrees" Include="College,DegreeType,MajorType"
    EntityTypeFilter="Degree" Where="it.UserID=@UserID">
    <WhereParameters>
        <asp:Parameter Name="UserID" DbType="Int32" />
    </WhereParameters>
</asp:EntityDataSource> 
will become :
<telerik:OpenAccessLinqDataSource runat="server" ID="edsDegree"
    ResourceSetName="Degrees" EntityTypeName="" 
ContextTypeName="DataModel.data"
  Select=" new (PlannedGraduationDate,GraduationDate, College,DegreeType,MajorType)"
    Where="it.UserID=@UserID">
    <WhereParameters>
        <asp:Parameter Name="UserID" DbType="Int32" />
    </WhereParameters>
</telerik:OpenAccessLinqDataSource>
 
 
Neither of the telerik data controls have the "Include" property. So if the EntityDataSource is using it ,
you can Include your related entities as Select="new (ID,Name, ChildEntity )".In the above examples related entities of Degree entity are:
College,DegreeType,MajorType

Monday, December 02, 2013

Telerik OpenAccess include equivalent

  IQueryable<Customer> query = from c in dbContext.Customers.Include(c => c.Orders)
                                       where c.Country == "Germany"
                                       select c;

Check valid email in SQL Server

The only working answer below:
   
select * from users 
WHERE NOT
(     CHARINDEX(' ',LTRIM(RTRIM([Email]))) = 0 
AND  LEFT(LTRIM([Email]),1) <> '@' 
AND  RIGHT(RTRIM([Email]),1) <> '.' 
AND  CHARINDEX('.',[Email],CHARINDEX('@',[Email])) - CHARINDEX('@',[Email]) > 1 
AND  LEN(LTRIM(RTRIM([Email]))) - LEN(REPLACE(LTRIM(RTRIM([Email])),'@','')) = 1 
AND  CHARINDEX('.',REVERSE(LTRIM(RTRIM([Email])))) >= 3 
AND  (CHARINDEX('.@',[Email]) = 0 AND CHARINDEX('..',[Email]) = 0) 

http://stackoverflow.com/questions/801166/sql-script-to-find-invalid-email-addresses

Thursday, October 24, 2013

Friday, October 04, 2013

Creating/Running Telerik Reports in Visual Studio , in Design Time

I m using entity framework and getting the data for my Telerik report from it.
To see the reports running in the Visual Designer and avoid the error: "The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.", you have to hard code your connection string into the code and use the connection string while opening the connection as below:
        public static List<Region> GetRegions()
        {
            using (Entities entities = new Entities(connStr))
            {
                entities.Connection.Open();
                return entities.Regions.ToList();
            }
        } 
This won't work:
   public static List<Region> GetRegions()
        {
            using (Entities entities = new Entities())
            {
                entities.Connection.Open();
                return entities.Regions.ToList();
            }
        } 

Its against the best practise of course but to to see your reports running from Visual Studio 
,it's worth !

Wednesday, August 21, 2013

Disable Radbutton postback w/ validation

       function ValidateLastName(button, args) {
            var txtLastName = $find('txtLastName');
            if ( txtLastName.get_value() == '') {
                alert('At least lastname should be entered');
                button.set_autoPostBack(false);
            }
            else { button.set_autoPostBack(true); }
        }
 
           <telerik:RadButton runat="server" ID="btnLookup" OnClick="btnLookup_Click"  
Text="Lookup"  OnClientClicking="ValidateLastName">
                            </telerik:RadButton> 

Tuesday, August 13, 2013

EF , how to query result of query again

           var schools = entities.Companies.OfType<School>();
                if (hasHSAlumni)
                {
                    schools = (ObjectQuery<School>)schools.Where(p => p.HSGraduateExist == true);
                }

Thursday, August 01, 2013

Issue:Forms authentication doesnt allow images to show in IIS

     You already defined correct authentication like this:  <allow users="?" /> 
and IIS still doesnt show the images css or other resources
Solution: Edit Anonymous Authentication  and set it to Application Pool Identity






RadAsyncUpload too big

<style type="text/css">
 .RadUpload .ruFakeInput
 {
  height: 12px!important;
  width:60px!important;
 }
</style>

Monday, July 08, 2013

Telerik Report doesnt see custom objects /class using objectDataSource

       public class EventTypeCompanysEvents
        {
            public EventType eventType ;
            public School school ;
            public Event _event ;
        }       
public static List<EventTypeCompanysEvents> GetEventsByType(List<int> eventTypeIDs, List<int> schoolIDs, DateTime startDate, DateTime endDate)
I was getting  "not defined in current context" error ,trying to call
 a method("GetEventsByType" in this case) inside an objectdataSource.
The method is fully working and tested ,yet Telerik Report was not seeing the fields of the
objectDataSource.
Here is the solution:
Convert  members of your custom class to properties:
 public class EventTypeCompanysEvents
        {
            public EventType eventType { getset; }
            public School school { getset; }
            public Event _event { getset; }
        }
 and now you can drag your fields to your report ! 

where in clause with Lambda expression

List<int> eventTypeIDs
 
   var ets =  entities.EventTypes.Where(p => eventTypeIDs.Contains(p.ID));

Wednesday, June 26, 2013

Fix to "Object must implement IConvertible" error when using objectdatasource withy multivalue parameter under Telerik Reports

If you want to pass multivalue parameters to an objectdatasource you have to make sure the argument type of the objectdatasource's method is object array. You cannot pass a List or array integer or etc.
In the method body convert the object [] to the needed array type  . You can do it this way:
parameter is:
(object[] eventTypes)
   
            int[] eventTypeIDs = eventTypes.Select( Convert.ToInt32).ToArray();

Tuesday, June 25, 2013

Telerik Report doesnt see referenced classes/methods

I have static classes which has the DAL methods which I want to use in my Telerik Report
To do that I drag an objectDataSource to my report and none of those classes I referenced show up in Configure Object Data Source wizard.
Here is a quick solution:
Just add a public struct like  this to each one of your static class , recompile DAL and Telerik now will see your methods
        public struct  ShowMyClass{};

Commit failed (details follow): Cannot commit 'D:\Users\Admin\AddUpdateContact.aspx.cs' because it was moved to 'D:\Users\Admin\AddContact.cs' which is not part of the commit; both sides of the move must be committed together

I recently started to getting this exception from SVN on my Windows
Commit failed (details follow):
Cannot commit 'D:\Users\Admin\AddUpdateContact.aspx.cs'
 because it was moved to 'D:\Users\Admin\AddContact.cs'
 which is not part of the commit; both sides of the move must be committed
 together

First solution:

Try to commit both folders together, the folder of  : 'D:\Users\Admin\AddUpdateContact.aspx.cs' and the folder of 'D:\Users\Admin\AddContact.cs' and if that doesnt work:

Select the new location(AddContact.cs) when committing and add the old one (AddUpdateContact.aspx.cs) to ignore list

RadGrid download attachment doesnt work inside Ajax panel

If your download button inside the RadGrid doesnt work if in an ajax panel:
 All you have to do is below( "btnDownload" is the id of the control
 which causes the download):
 
       function RequestStart(sender, args) {
            if (args.get_eventTarget().indexOf("btnDownload") >= 0) {
                args.set_enableAjax(false);
            }
        }
 
<telerik:RadAjaxPanel runat="server" LoadingPanelID="pnlLoading" 
ID="pnlMain" ClientEvents-OnRequestStart="RequestStart">
 

  <telerik:GridTemplateColumn HeaderText="Business Card" >
      <ItemTemplate>
    <asp:LinkButton runat="server" ID="btnDownload" Text="Download" 
CommandName="Download" CommandArgument='<%#Eval("ID"%>'    >
    </asp:LinkButton>
       </ItemTemplate>
 </telerik:GridTemplateColumn>

Radajaxpanel and RegisterStartupScript

If you want call javascript from server side while using RadAjaxPanel use 
ResponseScripts.Add method. 
 
//Doesnt work  :
   ScriptManager.RegisterStartupScript(this, GetType(), "RefreshDD", 
"RefreshDD();", true); 
 
//Works :
   pnlMain.ResponseScripts.Add("RefreshDD();"); 

Saturday, June 22, 2013

Thursday, June 20, 2013

Use Eval to run javascript method inside item template of radgrid

This works :
                <telerik:GridTemplateColumn HeaderText="Edit">
                        <ItemTemplate>
                            <asp:Button runat="server" Text="Edit" AutoPostBack="False"
 OnClientClick='<%# String.Format("openAddContact({0})",Eval("ID"))%> '></asp:Button>

                        </ItemTemplate>
                    </telerik:GridTemplateColumn>
 
This doesn't:
                <telerik:GridTemplateColumn HeaderText="Edit">
                        <ItemTemplate>                        
     <telerik:RadButton ID="Button1" runat="server" Text="Edit" 
 AutoPostBack="False" 
 OnClientClicked='<%# String.Format("openAddContact({0})",Eval("ID"))%> '>
            </telerik:RadButton>
                        </ItemTemplate>
                    </telerik:GridTemplateColumn>
intersting hah 

Fix to RadNumericTextBox declarative binding error "Specified cast is not valid"

 <telerik:GridTemplateColumn HeaderText="No of  Subscribers">
          <ItemTemplate>
               <%#Eval("SentToCount"%>
          </ItemTemplate>
          <EditItemTemplate>
              <telerik:RadNumericTextBox ID="rnSentCount" runat="server" MaxValue="1000000"
CausesValidation="True"   NumberFormat-DecimalDigits="0" DataType="Int32"  MinValue="1" 
DbValue='<%#Bind("SentToCount"%>'/>
          </EditItemTemplate>
          <InsertItemTemplate>
              <telerik:RadNumericTextBox ID="rnSentCount" runat="server" MaxValue="1000000"
CausesValidation="True" NumberFormat-DecimalDigits="0" DataType="Int32"  MinValue="1"
DbValue='<%#Bind("SentToCount"%>'/>
           </InsertItemTemplate>
 </telerik:GridTemplateColumn>
 
 
  <%#Bind ()%> will not work with Value property so use DbValue instead and it will
 work like a charm. Why intellisense doesnt display DbValue : good question ... to telerik :) 

Wednesday, June 19, 2013

RadioButtonList bind inside GridView

  <asp:RadioButtonList ID="rblSentTo" runat="server"  
SelectedValue='<%#Bind("SentTo"%>'>
                                <Items>
       <asp:ListItem Text="Community Members" Value="C"></asp:ListItem>
       <asp:ListItem Text="Parents/Students" Value="P"></asp:ListItem>
       <asp:ListItem Text="" Value=""></asp:ListItem> 
                                </Items>
                            </asp:RadioButtonList>
Here the SentTo is nullable , in case your field is not , you do not need the 3rd ListItem with "" value but if it's nullable, you must add it, otherwise it cant find a match to null value and give an error

Friday, June 14, 2013

SEO friendly data display in ASP.NET

 Google seems to be not indexing javascript links
So if you are using a paged GridView of asp.net, google may (or may be not, but in my case it didnt)  index only the original page not the links below it.


DataPager control helps you there to create SEO friendly data display

I also found a free user control for the same purpose:

http://asp-net-elephant.blogspot.com/2011/06/custom-seo-friendly-paging-with-aspnet.html

Thanks

Tuesday, June 11, 2013

Using empty value in a databound GridDropDownColumn



 In RadGrid if you want to use dropdown box (or the ComboBox) then  there is this  GridDropDownColumn.
And if you want to databind it just set the datasource .
Then the question comes to how to add the empty item to the dropdown
For ex you want 3 items in the combo and "--None--" as the default item in the dropdown box
And if "--None--" is selected it should return null as value.
The EmptyListItemValue  property comes to help, set these 3 properties as below 


EmptyListItemText="None" EmptyListItemValue="" EnableEmptyListItem="True"
 <telerik:GridDropDownColumn HeaderText="TargetOrganisation" 
ListValueField="ID" UniqueName="TargetOrganisationID" 
 DataField="TargetOrganisationID" 
ListTextField="Alias" DataSouceID="edsOrganisation"EmptyListItemText="None" EmptyListItemValue="" EnableEmptyListItem="True">
</telerik:GridDropDownColumn>

EF 4 and Membership Provider



Asp.Net's MembershipProvider is very useful. It has builtin user role access system , good encryption features and more. To make it work with EF you need to override MembershipProvider. Here is a project that  to make these two work: http://efmembership.codeplex.com/

I chose to use the older version 1.0 which is for EF 4.0  , the latest one works with EF4.2 and it's Code First and I m not very Code First fan , I prefer  to design so I chose Model First . After downloading the project I had to make changes to make it compile. And I also downloaded another tool which helps a lot using EF.

Normally for every single change you make in the  Model , you need to recreate all the tables or get the DDL  Difference and apply the difference script to database , this tools does detect incremental changes and migrare both schema and data so you wont be losing anything:http://visualstudiogallery.msdn.microsoft.com/df3541c3-d833-4b65-b942-989e7ec74c87
It has some bugs though. After making changes in your datamodel in EF you can create the SQL script to apply changes. I use the Table Per Type instead of Table Per Hierarchy.

 Although both EfRoleProvider and EFMembershipProvider classes in the overridden MEmbershipProvider  contain methods commonly needed, I recreated alternative methods as I don't like the signatures of some .
For example instead of passing/retrieving  string array as RoleNames or User names I want to pass/retrieve List<Object> or Collection of objects. This is the overridden GetRolesForUser method which returns a string array, which I think is very impractical:

    public override string[] GetRolesForUser(string username)
And this is my method which returns Role objects as IList: 
  public static List<Role> GetUsersRoles(string userName)
  {
        User user;
        using (Entities entities = new Entities())
        {
            entities.Connection.Open();
user = entities.Users.Include("Roles").FirstOrDefault(p => p.Username == userName);
        }
 
        if (user != null)
        {
            return user.Roles.ToList();
        }
        else
        {
            return null;
        }
    }

Permanent Fix to "Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information"

I keep getting this "Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information" Every time I had to restart IIS to temporarily fix it. I tried many things to resolve the issue nothing really helped. Finally I have a permanent fix : It's fixed in .Net 4.5 framework You have to install .NEt 4.5 and do nothing else. According to forums 4.5 requires VS 2012 And I m still using 2010

MembershipProvider and getting UserID

Common scenario is you will need the the Identity key of the logged in user You can achieve it like this: (Guid)Membership.GetUser().ProviderUserKey But this will make a call to database , so you may want to store UserID in session or maybe store it in Forms Authentication cookie. I will update about the Forms Authentication way

RadDatePicker and databinding at design time

RadDatePicker and databinding at design time If you want to bind RadDatePicker at design time , ( like using selectedvalue property of other asp.net controls ) , you can use the DbSelectedDate property:
 <telerik:RadDatePicker runat="server" ID="rdDeterminationDate"   
   
 DbSelectedDate='<%#Bind("DeterminationDate") %>' >  
   
 </telerik:RadDatePicker>