Telerik Forums
UI for ASP.NET AJAX Forum
7 answers
558 views
I'm having an issue trying to convert one of my RadGrids to Batch edit mode from EditForms. The following is all code that worked natively prior to changing the EditMode.

Here is an example of the problem, starting with the GridTemplateColumn causing problems:
<telerik:GridTemplateColumn HeaderText="Unit #" ColumnGroupName="GeneralInformation" UniqueName="EmpORUnitID" DataField="EmpORUnitID" HeaderStyle-Width="100px">
                <ItemTemplate>
                    <asp:Label ID="lblUnitID" runat="server" Text=<%#DataBinder.Eval(Container, "DataItem.EmpORUnitID")%>></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <telerik:RadComboBox runat="server" ID="rcbUnitNumber"
                        EnableLoadOnDemand="True" ShowMoreResultsBox="true" BorderStyle="None" Width="90px"
                        EnableVirtualScrolling="true" EmptyMessage="Choose a Unit #"
                        DataTextField="EmpORUnitID" MarkFirstMatch="True" Filter="StartsWith"
                        HighlightTemplatedItems="true" Height="200px" Text='<%#DataBinder.Eval(Container, "DataItem.EmpORUnitID")%>'>
                        <WebServiceSettings Method="GetUnitNumberList" Path="Timesheet.aspx" />
                    </telerik:RadComboBox>
                </EditItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridTemplateColumn HeaderText="Odo Start" ColumnGroupName="GeneralInformation" UniqueName="OdoStart" DataField="OdoStart" HeaderStyle-Width="100px">
                <ItemTemplate>
                    <%#DataBinder.Eval(Container, "DataItem.OdoStart")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <telerik:RadNumericTextBox runat="server" ID="rtbOdoStart" Width="50px" Text='<%#DataBinder.Eval(Container, "DataItem.OdoStart")%>'>
                    </telerik:RadNumericTextBox>
                    <telerik:RadButton ID="btnFindOdoStart" runat="server" Width="20px"
                                            OnClick="btnFindOdoStart_Click" Icon-PrimaryIconUrl="~/Images/Icons/gauge.png"></telerik:RadButton>
                </EditItemTemplate>
            </telerik:GridTemplateColumn>

Then, I have the following (with some lines cut out) to extract values from the EditItemTemplate controls (bolded the relevant sections to this problem)

protected void rgTodaysVehicles_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                SWG.Timesheet.WebApp.Entities.Timesheet timesheet = Session["CurrentTimesheet"] as SWG.Timesheet.WebApp.Entities.Timesheet;
                VehicleMileageSummary vehicleMileageSummary = timesheet.VehicleMileages[editedItem.ItemIndex];
                try
                {
                    vehicleMileageSummary = BuildVehicleMileageSummary(editedItem, vehicleMileageSummary);

The last line above leads to:

private VehicleMileageSummary BuildVehicleMileageSummary(GridEditableItem editedItem, VehicleMileageSummary vehicleMileage)
        {
            List<String> errorList = new List<string>();
            try
            {
                vehicleMileage.IsDirty = true;            
                RadComboBox cbxEmpOrUnitID = (RadComboBox)editedItem["EmpORUnitID"].FindControl("rcbUnitNumber");       
                vehicleMileage.EmpORUnitID = cbxEmpOrUnitID.Text;

I receive null Object errors for the bolded line above, as the control "rcbUnitNumber" isn't found. Using breakpoints and some testing I can confirm that "editedItem" only contains the controls from the column ItemTemplate rather than EditItemTemplate.

Can anyone see what I'm doing wrong here?



Angel Petrov
Telerik team
 answered on 17 Jul 2014
1 answer
214 views
Our client is using Acunetix as their web application scanner - to find security vulnerabilities. One of the findings is about the Telerik.Web.UI.WebResource.axd. Details of the Acunetix below. How can we resolve this? Thanks!



Acunetix: Content type is not specified

Description

This page does not set a Content-Type header value. This value informs the browser what kind of data to expect. If this
header is missing, the browser may incorrectly handle the data. This could lead to security problems.

/Telerik.Web.UI.WebResource.axd


Recommendation
Set a Content-Type header value for this page
Ianko
Telerik team
 answered on 17 Jul 2014
7 answers
541 views
So on the button click of a telerik:RadToolBarDropDown I export a Telerik:RadGrid to either PDF, Excel or Word, depending on what they select.
The telerik:RadGrid has 2 levels of DetailTables.  I was able to add a background color of the MasterTableView using the code below:

For Each hdrItem As GridHeaderItem In RadGrid1.MasterTableView.GetItems(GridItemType.Header)
            hdrItem.BackColor = System.Drawing.Color.LightBlue
            For Each cell As TableCell In hdrItem.Cells
                cell.Style("text-align") = "left"
            Next
Next

My question is how can I also add a background color of each DetailTable Header?  Please Advice.  Thank You.
Shinu
Top achievements
Rank 2
 answered on 17 Jul 2014
1 answer
191 views
Hi friends,In the  radgrid i have a Tempalte coloumn  Which has an EditTempalte as shown below.I want to the update new value for the field User_login: User.identity.name

<telerik:GridTemplateColumn SortExpression="User_Login" UniqueName="User_Login" HeaderText="User_Login" >
<ItemTemplate>
<asp:Label Text='<%# Eval("User_Login") %>' runat="server" ID="lblUserLoginItem" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID ="txtUserLoginEdit" runat="server" Text='<%# Bind("User_Login") %>'> </asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>

But when I try to do the following in the code behind:  It retrieves the only the old value beacause of the bind and if i dont use the bind it does not update at all.Is there something I am missing..Please guide..thank You

protected void rgTransferDetails_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditFormInsertItem && e.Item.OwnerTableView.IsItemInserted)
{
GridEditFormInsertItem item = (GridEditFormInsertItem)e.Item;
TextBox lblUserLogin = (TextBox)item.FindControl("txtUserLoginEdit");
lblUserLogin.Text = User.Identity.Name;

}

if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
GridEditFormItem editItem = (GridEditFormItem)e.Item;
TextBox lblUserLoginEdit = (TextBox)editItem.FindControl("txtUserLoginEdit");
lblUserLoginEdit.Text = User.Identity.Name;

}

}
Princy
Top achievements
Rank 2
 answered on 17 Jul 2014
7 answers
550 views
I have a radgrid (multi select) which is set in editmode through a button eventhandler. Now I had to add a detailtable which is displayed correct.
However, what I want is when a row in the mastertable is selected, and the edit putton is clicked, the detailtable has to expand and has to be put in edit mode. I can't get this done. This is what I have:

protected void button_Click(object sender, EventArgs e) {

bool isInEditMode = false;

foreach (GridItem item in rg.MasterTableView.Items) {                           

    if (item.Selected){

        if (item is GridEditableItem){

            ((GridEditableItem) item).Edit = true;

            isInEditMode = true;

        }

        if (item is GridDataItem){

            GridTableView nestedView = ((GridDataItem)item).ChildItem.NestedTableViews[0];

            if (tmp.Name == "Pricing"){

                item.Expanded = true;

                item.Edit = true;

            }

        }

       

        item.Selected = false;

    }

}

if (isInEditMode) {

    // disable selecting because we're in edit mode

    rg.ClientSettings.Selecting.AllowRowSelect = false;

    rg.Rebind();

}

}

if (isInEditMode) {

    // disable selecting because we're in edit mode

    rg.ClientSettings.Selecting.AllowRowSelect = false;

    rg.Rebind();

<Philips:MagAgRadGrid ID="rg" runat="server" AllowSorting="True" OnNeedDataSource="rg_NeedDataSource" AllowMultiRowEdit="True" OnItemCommand="rg_ItemCommand" Skin="Outlook" AllowMultiRowSelection="True" EnableOutsideScripts="True" EnableViewState="true" OnDetailTableDataBind="rg_DetailTableDataBind" >

..........

..........

<DetailTables>

    <radG:GridTableView DataKeyNames="MarketProductID" Name="Pricing"  Width="100%" AutoGenerateColumns="false" >

        <ParentTableRelation>

            <radG:GridRelationFields DetailKeyField="MarketProductID" MasterKeyField="MarketProductID" />

        </ParentTableRelation>

        <Columns>

            <radG:GridBoundColumn SortExpression="Country" HeaderText="Country"  DataField="Name"></radG:GridBoundColumn>

            <radG:GridTemplateColumn HeaderText="AVNP" UniqueName="AVNP" SortExpression="AVNP">

                <ItemStyle VerticalAlign="Top" HorizontalAlign="Center" />

                <ItemTemplate>

                    <asp:Label ID="lblAVNP" runat="server" Text='<%# Eval("AVNP") == DBNull.Value ? " 0.00" : Convert.ToDouble(Eval("AVNP")).ToString(" #0.00") %>' ></asp:Label>                            

                </ItemTemplate>

                <EditItemTemplate>

                    <radG:RadNumericTextBox ID="txtAVNP" runat="server" MinValue="0" EnabledStyle-HorizontalAlign="Right" Skin="Outlook" Value='<%# Eval("AVNP") %>' Width="60px">

                   <NumberFormat DecimalDigits="2" GroupSeparator="" />

                    </radG:RadNumericTextBox>

                </EditItemTemplate>

            </radG:GridTemplateColumn>

        </Columns>

    </radG:GridTableView>           

</DetailTables>

..........

..........

I hope anybody can help me.


Greg
Top achievements
Rank 1
 answered on 16 Jul 2014
5 answers
516 views
I have the following grid, but have found that the Itemcommand event is not fired when I click btnEdit2 on the detail table. It does fire correctly when I click the button on the master table. Do I need to do anything else to get this to work?

Thanks

<telerik:RadGrid ID="testgrid" runat="server" OnItemCommand="ItemCommand" DataSourceID="dsAppointments">
    <MasterTableView Name="Master" DataSourceID="dsAppointments" DataKeyNames="TaskID" EditMode="PopUp" AllowAutomaticUpdates="true" CommandItemDisplay="Top">
        <CommandItemSettings ShowAddNewRecordButton="false" ShowExportToCsvButton="false" ShowRefreshButton="false" />
        <Columns>
            <telerik:GridTemplateColumn UniqueName="Edit">
                <ItemTemplate>
                    <asp:LinkButton ID="btnEdit1" runat="server"
                        CommandName="JumpTo" CommandArgument='<%# Eval("TaskID") %>' CausesValidation="false"
                        PostBackUrl="~/Default.aspx">
                        Edit
                    </asp:LinkButton>
                </ItemTemplate>
            </telerik:GridTemplateColumn>
        </Columns>
        <DetailTables>
            <telerik:GridTableView Name="Detail" DataSourceID="dsAttendees" CommandItemDisplay="None" DataKeyNames="TaskID" TableLayout="Auto" HorizontalAlign="NotSet" ShowHeader="true" AllowAutomaticUpdates="true" AllowAutomaticDeletes="true">
                <ParentTableRelation>
                    <telerik:GridRelationFields MasterKeyField="TaskID" DetailKeyField="TaskID" />
                </ParentTableRelation>
                <Columns>
                    <telerik:GridTemplateColumn UniqueName="Edit">
                        <ItemTemplate>
                            <asp:LinkButton ID="btnEdit2" runat="server"
                                CommandName="JumpTo" CommandArgument='<%# Eval("TaskID") %>' CausesValidation="false"
                                PostBackUrl="~/Default.aspx">
                                Edit
                            </asp:LinkButton>
                        </ItemTemplate>
                    </telerik:GridTemplateColumn>
                </Columns>
            </telerik:GridTableView>
        </DetailTables>
    </MasterTableView>
</telerik:RadGrid>
Ryan Strand
Top achievements
Rank 1
 answered on 16 Jul 2014
9 answers
406 views
Hello All

I have a problem with a RadGrid where the paging section is not refreshing. If, for example, the first search returns 15 records and the second search only 5 records, I see '... page 1 of 2...' in the second search which is incorrect info caused by the paging section of the grid not refreshing. My page count is set to 10 records. That means there should be only one page in the second search.

Please help as soon as possible.
Thank you!

Colin
Top achievements
Rank 1
 answered on 16 Jul 2014
8 answers
175 views
Hi All,

Is there any possible way to set dataformatstring of a Calculated Item? I am customising the calculation behind the C# code and would like to format it into {0:p0}.

Right now, e.CalculatedValue is a double without any format.

Many thanks.
Tim
Top achievements
Rank 1
 answered on 16 Jul 2014
3 answers
226 views
Hey
Guys/gals,



We have developed some functionality for Gatorade and have deployed it on the
test server, the functionality seems to be working fine on all browsers except
Internet Explorer 8 and 9. Please could you guys have a look and let us know
your thoughts.



At first we I thought it is a css display issue thing , but later when i looked
at the html code in firebug realized that the radtabstrip is not working, the
code is not being injected on to the page. You can have a look at the same page
in chrome and see the difference.



Test URL: http://gatoradecmsupg.teectest.co.uk/shopifyproducts



Looking forward to your reply.



Regards.

Harish
Dimitar Terziev
Telerik team
 answered on 16 Jul 2014
1 answer
166 views
Hope someone has the patients to spell out for me the actual changes needed in the DBSchedulerProviderBase(inherited from SchedulerProviderBase) class to work with my Entities Provider.  I cant seem to find any examples of what needs to change in this base class to get my Entities associated with my custom RadLabDBSchedulerProvider class.

Here is what i have so far in this Base Class - I have added the obvious DBFactory and ConnectionString, :

public abstract class DbSchedulerProviderBase : SchedulerProviderBase
    {
        protected DbProviderFactory DbFactory { get { return DbProviderFactories.GetFactory("System.Data.EntityClient");} set { }}
        protected bool PersistChanges { get { }; set { }; }
        protected string ConnectionString { get { return ConfigurationManager.ConnectionStrings["RadLabDBEntities"].ConnectionString;} set { }; }
        public override void Initialize(string name, NameValueCollection config) { };
        protected virtual DbConnection OpenConnection() { };
        protected virtual DbParameter CreateParameter(string name, object value) { };
    }


So what needs to go in PersitChanges, Initialize(), DbConnection, etc??...   I have my inherited class for the provider all ready, just i don't understand all these function in the base class, and what needs be changed.  Can you point me to examples?  Ok with giving me links to other resources, but if you could spell out an examples (cant seem to find any examples of this in your codebase or docs).  

Here is my web.config info:
<configSections>
   <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
   <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
 <connectionStrings>
   <add name="TelerikConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Telerik.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
   <add name="TelerikVSXConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TelerikVSX.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
   <add name="Telerik" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Telerik;Integrated Security=True" providerName="System.Data.SqlClient" />
   <add name="RadLabDBEntities" connectionString="metadata=res://BarLab/BarLabModel.csdl|res://BarLab/BarLabModel.ssdl|res://BarLab/BarLabModel.msl;provider=System.Data.SqlClient;provider connection string='data source=IRIONVO\SQLIRIONVO;initial catalog=RadLabDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
 </connectionStrings>
 
<entityFramework>
   <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
   <providers>
     <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
   </providers>
 </entityFramework>

And if needed, here is my RadLabDbSchedulerProvider.cs code  - This is what i would then assign to radscheduler1.Provider = RadLabDbSchedulerProvider:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Telerik.Web.UI;
 
 
    public class RadLabDbSchedulerProvider : DbSchedulerProviderBase
    {
 
        public ArrayList resourceKeys = new ArrayList();
 
        public Dictionary<int, Resource> _persons { get; set; }
 
        public Dictionary<int, Resource> _hardware { get; set; }
 
        public override IEnumerable<ResourceType> GetResourceTypes(RadScheduler owner)
        {
            ResourceType[] resourceTypes = new ResourceType[2];
            resourceKeys.Clear();
 
            resourceTypes[0] = new ResourceType("Person", true);
            resourceKeys.Add("Person");
 
            resourceTypes[1] = new ResourceType("BAR_HW", true);
            resourceKeys.Add("BAR_HW");
            return resourceTypes;
        }
 
        public override IEnumerable<Resource> GetResourcesByType(RadScheduler owner, string resourceType)
        {
            switch (resourceType)
            {
                case "Person":
                    return Persons.Values;
 
                case "BAR_HW":
                    return BAR_HWs.Values;
 
                default:
                    throw new InvalidOperationException("Unknown resource type: " + resourceType);
            }
        }
 
        private IDictionary<int, Resource> Persons
        {
            get
            {
                if (_persons == null)
                {
                    _persons = new Dictionary<int, Resource>();
                    foreach (Resource person in LoadPersons())
                    {
                        _persons.Add((int)person.Key, person);
                    }
                }
                return _persons;
            }
        }
 
        private IDictionary<int, Resource> BAR_HWs
        {
            get
            {
                _hardware = new Dictionary<int, Resource>();
                foreach (Resource hardware in LoadHardware())
                {
                    _hardware.Add((int)hardware.Key, hardware);
                }
                return _hardware;
            }
        }
 
        private IEnumerable<Resource> LoadPersons()
        {
            List<Resource> resources = new List<Resource>();
            using (DbConnection conn = OpenConnection())
            {
                DbCommand cmd = DbFactory.CreateCommand();
                cmd.Connection = conn;
                cmd.CommandText = "SELECT [ResourceId], [Name], [Type], [Available], [ParentId], [Level], [Status], [Shared], [LastModifedTime], [Url], [LastModifedUser], [Building], [PersonId], [QuicklookId], [Cube], [Phone], [Email] FROM [Person]";
                using (DbDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Resource res = new Resource();
                        res.Type = "Person";
                        res.Key = reader["ResourceId"];
                        res.Text = Convert.ToString(reader["Name"]);
                        res.Attributes["ParentId"] = Convert.ToString(reader["ParentId"]);
                        res.Attributes["Type"] = Convert.ToString(reader["Type"]);
                        res.Attributes["BomId"] = string.Empty;
                        res.Attributes["Approved"] = string.Empty;
                        resources.Add(res);
                    }
                }
            }
            return resources;
        }
 
        private IEnumerable<Resource> LoadHardware()
        {
            List<Resource> resources = new List<Resource>();
            using (DbConnection conn = OpenConnection())
            {
                DbCommand cmd = DbFactory.CreateCommand();
                cmd.Connection = conn;
                cmd.CommandText = "SELECT [ResourceId], [Name], [Type], [Available], [ParentId], [Level], [Status], [Shared], [LastModifedTime], [Url], [LastModifedUser], [Building], [HWId], [Lab], [Tile], [BomId], [Owner], [RegisteredTime], [LastContactTime], [Station], [Row], [IP], [Cabinet], [RailSlot], [SizeU], [AssetTag], [SrvsTicket] FROM [BAR_HW]";
                using (DbDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Resource res = new Resource();
                        res.Type = "BAR_HW";
                        res.Key = reader["ResourceId"];
                        res.Text = Convert.ToString(reader["Name"]);
                        res.Attributes["ParentId"] = Convert.ToString(reader["ParentId"]);
                        res.Attributes["Type"] = Convert.ToString(reader["Type"]);
                        res.Attributes["BomId"] = Convert.ToString(reader["BomId"]);
                        res.Attributes["Approved"] = string.Empty;
 
                        resources.Add(res);
                    }
                }
            }
            return resources;
        }
 
        private void LoadResources(Appointment apt)
        {
            using (DbConnection conn = OpenConnection())
            {
                DbCommand cmd = DbFactory.CreateCommand();
                cmd.Connection = conn;
 
                cmd.Parameters.Add(CreateParameter("@ScheduleId", apt.ID));
                cmd.CommandText = "SELECT [ResourceId], [ParentId], [BomId], [Type], [Approved] FROM [ScheduleResource] WHERE [ScheduleId] = @ScheduleId";
                using (DbDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        switch (Convert.ToString(reader["Type"]))
                        {
                            case "Person":
                                Resource presource = Persons[Convert.ToInt32(reader["ResourceId"])];
                                presource.Attributes["ParentId"] = Convert.ToString(reader["ParentId"]);
                                presource.Attributes["Type"] = Convert.ToString(reader["Type"]);
                                presource.Attributes["BomId"] = Convert.ToString(reader["BomId"]);
                                presource.Attributes["Approved"] = Convert.ToString(reader["Approved"]);
                                apt.Resources.Add(presource);
                                break;
 
                            case "BAR_HW":
                                Resource resource = BAR_HWs[Convert.ToInt32(reader["ResourceId"])];
                                resource.Attributes["ParentId"] = Convert.ToString(reader["ParentId"]);
                                resource.Attributes["Type"] = Convert.ToString(reader["Type"]);
                                resource.Attributes["BomId"] = Convert.ToString(reader["BomId"]);
                                resource.Attributes["Approved"] = Convert.ToString(reader["Approved"]);
                                apt.Resources.Add(resource);
                                break;
 
                            default:
                                throw new InvalidOperationException("Unknown resource type: " + Convert.ToString(reader["Type"]));
                        }
                    }
                }
            }
        }
 
        public override IEnumerable<Appointment> GetAppointments(RadScheduler owner)
        {
            List<Appointment> appointments = new List<Appointment>();
            using (DbConnection conn = OpenConnection())
            {
                DbCommand cmd = DbFactory.CreateCommand();
                cmd.Connection = conn;
                cmd.CommandText = "SELECT [ScheduleId], [Subject], [Start], [End], [RecurrenceRule], [RecurrenceParentID], [Email], [LastModified], [Description], [ProjectId], [TicketId], [QuicklookId], [Reminder], [AppointmentColor] FROM [Schedules]";
                using (DbDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Appointment apt = new Appointment();
                        apt.Owner = owner;
                        apt.ID = reader["ScheduleId"];
                        apt.Subject = Convert.ToString(reader["Subject"]);
                        apt.Start = DateTime.SpecifyKind(Convert.ToDateTime(reader["Start"]), DateTimeKind.Utc);
                        apt.End = DateTime.SpecifyKind(Convert.ToDateTime(reader["End"]), DateTimeKind.Utc);
                        apt.RecurrenceRule = Convert.ToString(reader["RecurrenceRule"]);
                        apt.RecurrenceParentID = reader["RecurrenceParentId"] == DBNull.Value ? null : reader["RecurrenceParentId"];
                        apt.Description = Convert.ToString(reader["Description"]);
 
                        apt.Attributes["Email"] = reader["Email"].ToString();
                        apt.Attributes["ProjectId"] = reader["ProjectId"].ToString();
                        apt.Attributes["TicketId"] = reader["TicketId"].ToString();
                        apt.Attributes["QuicklookId"] = reader["QuicklookId"].ToString();
                        apt.Attributes["AppointmentColor"] = reader["AppointmentColor"].ToString();
                        apt.Attributes["LastModified"] = DateTime.SpecifyKind(Convert.ToDateTime(reader["LastModified"]), DateTimeKind.Utc).ToShortDateString();
 
                        if (apt.RecurrenceParentID != null)
                        {
                            apt.RecurrenceState = RecurrenceState.Exception;
                        }
                        else if (apt.RecurrenceRule != string.Empty)
                        {
                            apt.RecurrenceState = RecurrenceState.Master;
                        }
                        LoadResources(apt);
                        appointments.Add(apt);
                    }
                }
            }
            return appointments;
        }
 
        private void FillSchedResources(Appointment appointment, DbCommand cmd, object ScheduleId, string resType)
        {
            foreach (Resource resource in appointment.Resources.GetResourcesByType(resType))
            {
                cmd.Parameters.Clear();
                cmd.Parameters.Add(CreateParameter("@SchedleId", ScheduleId));
                cmd.Parameters.Add(CreateParameter("@ResourceId", resource.Key));
                cmd.Parameters.Add(CreateParameter("@ParentId", resource.Attributes["ParentId"]));
                cmd.Parameters.Add(CreateParameter("@Type", resource.Attributes["Type"]));
                cmd.Parameters.Add(CreateParameter("@BomId", resource.Attributes["BomId"]));
                cmd.Parameters.Add(CreateParameter("@Approved", resource.Attributes["Approved"]));
 
                cmd.CommandText = "INSERT INTO [ScheduleResource] ([ScheduleId], [ResourceId], [ParentId], [Type], [BomId], [Approved]) VALUES (@ScheduleId, @ResourceId, @ParentId, @Type, @BomId, @Approved)";
                cmd.ExecuteNonQuery();
            }
        }
 
        private void ClearSchedResources(object ScheduleId, DbCommand cmd)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.Add(CreateParameter("@ScheduleId", ScheduleId));
            cmd.CommandText = "DELETE FROM [ScheduleResource] WHERE [ScheduleId] = @ScheduleId";
            cmd.ExecuteNonQuery();
        }
 
        private void PopulateAppointmentParameters(DbCommand cmd, Appointment apt)
        {
            cmd.Parameters.Add(CreateParameter("@Subject", apt.Subject));
            cmd.Parameters.Add(CreateParameter("@Start", apt.Start));
            cmd.Parameters.Add(CreateParameter("@End", apt.End));
            cmd.Parameters.Add(CreateParameter("@Description", apt.Description));
            cmd.Parameters.Add(CreateParameter("@Reminder", apt.Reminders));
 
 
            cmd.Parameters.Add(CreateParameter("@Email", apt.Attributes["Email"]));
            cmd.Parameters.Add(CreateParameter("@LastModified", apt.Attributes["LastModified"]));
            cmd.Parameters.Add(CreateParameter("@ProjectId", apt.Attributes["ProjectId"]));
            cmd.Parameters.Add(CreateParameter("@TicketId", apt.Attributes["TicketId"]));
            cmd.Parameters.Add(CreateParameter("@QuicklookId", apt.Attributes["QuicklookId"]));
            cmd.Parameters.Add(CreateParameter("@AppointmentColor", apt.Attributes["AppointmentColor"]));
            string rrule = null;
            if (apt.RecurrenceRule != string.Empty)
            {
                rrule = apt.RecurrenceRule;
            }
            cmd.Parameters.Add(CreateParameter("@RecurrenceRule", rrule));
 
            object parentId = null;
            if (apt.RecurrenceParentID != null)
            {
                parentId = apt.RecurrenceParentID;
            }
            cmd.Parameters.Add(CreateParameter("@RecurrenceParentId", parentId));
 
 
        }
 
        public override void Insert(RadScheduler owner, Appointment appointmentToInsert)
        {
            if (!PersistChanges)
            {
                return;
            }
            using (DbConnection conn = OpenConnection())
            using (DbTransaction tran = conn.BeginTransaction())
            {
                DbCommand cmd = DbFactory.CreateCommand();
                cmd.Connection = conn;
                cmd.Transaction = tran;
                PopulateAppointmentParameters(cmd, appointmentToInsert);
                cmd.CommandText =
                    @" INSERT INTO [Schedules]
                                   ([Subject], [Start], [End],
                                    [RecurrenceRule], [RecurrenceParentID],
                                    [Email], [LastModified], [Description], [ProjectId], [TicketId], [QuicklookId], [Reminder], [AppointmentColor])
                          VALUES (@Subject, @Start, @End,
                                  @RecurrenceRule, @RecurrenceParentID,
                                  @Email, @LastModified, @Description, @ProjectId, @TicketId, @QuicklookId, @Reminder, @AppointmentColor)";
                if (DbFactory is SqlClientFactory)
                {
                    cmd.CommandText += Environment.NewLine + "SELECT SCOPE_IDENTITY()";
                }
                else
                {
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "SELECT @@IDENTITY";
                }
                int identity = Convert.ToInt32(cmd.ExecuteScalar());
 
                foreach (string resType in resourceKeys)
                {
                    FillSchedResources(appointmentToInsert, cmd, identity, resType);
                }
 
                tran.Commit();
            }
        }
 
        public override void Update(RadScheduler owner, Appointment appointmentToUpdate)
        {
            if (!PersistChanges)
            {
                return;
            }
            using (DbConnection conn = OpenConnection())
            {
                using (DbTransaction tran = conn.BeginTransaction())
                {
                    DbCommand cmd = DbFactory.CreateCommand();
                    cmd.Connection = conn;
                    cmd.Transaction = tran;
                    PopulateAppointmentParameters(cmd, appointmentToUpdate);
                    cmd.Parameters.Add(CreateParameter("@ScheduleId", appointmentToUpdate.ID));
                    cmd.CommandText =
                                  @"UPDATE [Schedules] SET [Subject] = @Subject, [Start] = @Start, [End] = @End,
                                        [RecurrenceRule] = @RecurrenceRule, [RecurrenceParentID]= @RecurrenceParentID,
                                        [Email] = @Email, [LastModified] = @LastModified, [Description] = @Description,
                                        [ProjectId] = @ProjectId, [TicketId] = @TicketId, [QuicklookId] = @QuicklookId,
                                        [Reminder] = @Reminder, [AppointmentColor] = @AppointmentColor WHERE [ScheduleId] = @ScheduleId";
                    cmd.ExecuteNonQuery();
                    ClearSchedResources(appointmentToUpdate.ID, cmd);
                    foreach (string resType in resourceKeys)
                    {
                        FillSchedResources(appointmentToUpdate, cmd, appointmentToUpdate.ID, resType);
                    }
                    tran.Commit();
                }
            }
        }
 
        public override void Delete(RadScheduler owner, Appointment appointmentToDelete)
        {
            if (!PersistChanges)
            {
                return;
            }
            using (DbConnection conn = OpenConnection())
            {
                DbCommand cmd = DbFactory.CreateCommand();
                cmd.Connection = conn;
                using (DbTransaction tran = conn.BeginTransaction())
                {
                    cmd.Transaction = tran;
                    ClearSchedResources(appointmentToDelete.ID, cmd);
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add(CreateParameter("@ScheduleId", appointmentToDelete.ID));
                    cmd.CommandText = "DELETE FROM [Schedules] WHERE [ScheduleId] = @ScheduleId";
                    cmd.ExecuteNonQuery();
                    tran.Commit();
                }
            }
        }
    }


Boyan Dimitrov
Telerik team
 answered on 16 Jul 2014
Narrow your results
Selected tags
Tags
+? more
Top users last month
Hiba
Top achievements
Rank 1
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Max
Top achievements
Rank 1
Veteran
Iron
Alina
Top achievements
Rank 1
Rakhee
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Hiba
Top achievements
Rank 1
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Max
Top achievements
Rank 1
Veteran
Iron
Alina
Top achievements
Rank 1
Rakhee
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?