Getting the values of a dynamically created control inside Telerik:RadGrid - dynamic

I have a telerik RadGrid to which I am adding columns dynamically on click of a button. The Code is as follows :
private void AddColumns()
{
try
{
DataTable dtParMaintenanceListHeaderData = (DataTable)Session["ParMaintenanceListHeaderData"];
foreach (DataColumn dc in dtParMaintenanceListHeaderData.Columns)
{
dc.ReadOnly = false;
}
if (!dtParMaintenanceListHeaderData.Columns.Contains("parComboDataField"))
dtParMaintenanceListHeaderData.Columns.Add("parComboDataField", typeof(string));
dtParMaintenanceListHeaderData.AcceptChanges();
foreach (DataRow drEachRow in dtParMaintenanceListHeaderData.Rows)
{
string cusCombo = drEachRow["cusfstnam"].ToString() + " - " + drEachRow["cuslstnam"].ToString();
string parCombo = drEachRow["parcod"].ToString() + " - " + drEachRow["pardsc"].ToString();
drEachRow["parComboDataField"] = cusCombo + " " + parCombo;
GridTemplateColumn templateColumn = new GridTemplateColumn();
string templateColumnName = cusCombo + " - " + parCombo;
templateColumn.ItemTemplate = new RadGridTemplate(templateColumnName);
templateColumn.HeaderText = templateColumnName;
templateColumn.DataField = "parqty";
templateColumn.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
templateColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
templateColumn.HeaderStyle.Width = Unit.Pixel(60);
templateColumn.HeaderStyle.Wrap = true;
this.radgridParListItems.MasterTableView.Columns.Add(templateColumn);
}
}
catch (Exception Ex)
{
}
}
The above method is called on click of a button.
In each of the columns added I am adding a textbox as follows :
#region Namespaces used
using System;
using System.Web;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
#endregion
/// <summary>
/// Summary description for RadGridTemplate
/// </summary>
public class RadGridTemplate : ITemplate
{
protected LiteralControl lControl;
protected TextBox textBox;
private string colname;
public RadGridTemplate(string cName)
{
colname = cName;
}
public void InstantiateIn(System.Web.UI.Control container)
{
textBox = new TextBox();
textBox.ID = container.ID + "txtParQty";
textBox.Width = Unit.Pixel(50);
container.Controls.Add(textBox);
textBox.Text = HttpContext.Current.Request.Form[textBox.UniqueID];
}
}
Now there is another button,"Save" which when clicked upon will have to fetch the data from all the textboxes in the dynamically added controls. The trouble is :
On post back all the controls are cleared and re-created so their values are null.
How do I capture the values of all the textboxes in a row.

If you instantiate the template columns on init as explained in the telerik docs here, you should be able to keep their state steady on posbacks and fetch the data from the textboxes looping through the grid rows.

I am adding the solution for the use of other users who are all facing same problem.
To avoid recreation of dynamic controls in radgrid we have to call the set EnableColumnsViewState="false" in MasterTableView of the grid. It worked for me.
Regards,
Nathiya Rajendran.

Related

The Microsoft Access database engine cannot open or write to the file

I have the following function:
Public Function OleDBCSVToDataTable(directory As String, tableName As String, fileName As String, Optional start As Long = 0) As DataTable
Dim CnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & directory & ";Extended Properties='Excel 8.0;HDR=YES'"
Dim dt As DataTable = GetTableSchema(tableName)
Using Adp As New OleDbDataAdapter("select * from [" & fileName & "]", CnStr)
Adp.Fill(start, 1000, dt)
End Using
Return dt
End Function
The function is designed to read a CSV into a data table using OLEDB for import into SQL, however I am receiving this error:
"The Microsoft Access database engine cannot open or write to the file
'C:\TEST'. It is already opened exclusively by another user, or you
need permission to view and write its data."
I have attempted this solution. All permissions have been granted (permissions are Full Control across users):
I have seen this solution as well, however, the proposed options other than OLEDB are solutions that don't seem to work with CSV. Besides, I imagine there are native libraries.
I am open to suggestions for better ways to accomplish this, however, based on requirements - large CSVs, data validation - this appears to be the best, assuming I am able to get it working.
How about importing the CSV file into a DataGridView, and then exporting from that object into MS Access?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using System.Configuration;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
string delimiter = ",";
string tablename = "medTable";
DataSet dataset = new DataSet();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (MessageBox.Show("Are you sure you want to import the data from \n " + openFileDialog1.FileName + "?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
filename = openFileDialog1.FileName;
StreamReader sr = new StreamReader(filename);
string csv = File.ReadAllText(openFileDialog1.FileName);
dataset.Tables.Add(tablename);
dataset.Tables[tablename].Columns.Add("Order ID");
dataset.Tables[tablename].Columns.Add("Product");
dataset.Tables[tablename].Columns.Add("Unit Price");
dataset.Tables[tablename].Columns.Add("Quantity");
dataset.Tables[tablename].Columns.Add("Discount");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimiter.ToCharArray());
dataset.Tables[tablename].Rows.Add(items);
}
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
MessageBox.Show(filename + " was successfully imported. \n Please review all data before sending it to the database.", "Success!", MessageBoxButtons.OK);
}
else
{
this.Close();
}
}
}
public string filename { get; set; }
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void Import_Load(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
//remove the semicolon, and add brackets below after line
{
//create the connection string
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Ryan\\Desktop\\Coding\\Microsoft Access\\Northwind_2012.mdb";
//create the database query
string query = "SELECT * FROM [OrderDetailsTest]";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
//the DataGridView
DataGridView dataGridView1 = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView1.DataSource = bSource;
// An update function to get the changes back into the database.
dAdapter.Update(dTable);
}
}
}

WCF - Message and MessageBuffer close

Msdn says:
The message also disposes the object that was used to construct the body when it is disposed.
From this what I infer is closing Message also closes the MessageBuffer it is created from. But in actual code this is not the case. Closing message leaves messagebuffer.closed as false.
How message buffer and message created from that buffer should be closed?
source code below will help you understand how to use message created from message buffer.
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace _22756512 {
class Program {
static void Main(string[] args) {
Order order = new Order() { Id = 1, CustomerName = "Smith" };
var message = Message.CreateMessage(MessageVersion.Default, "http://127.0.0.1/someaction", order);
Console.WriteLine("message.state after creation: " + message.State.ToString());
using (MessageBuffer buffer = message.CreateBufferedCopy(int.MaxValue)) {
Console.WriteLine("message.state after create bufferedcopy: " + message.State.ToString());
using (var anotherMessage = buffer.CreateMessage()) {
var anotherOrder = anotherMessage.GetBody<Order>();
Console.WriteLine("anotherOrder.Id = " + anotherOrder.Id);
Console.WriteLine("antherOrder.customername = " + anotherOrder.CustomerName);
}
using (var the3rdMessage = buffer.CreateMessage()) {
var the3rdOrder = the3rdMessage.GetBody<Order>();
Console.WriteLine("3rd order.id = " + the3rdOrder.Id);
Console.WriteLine("3rd order.customer name = " + the3rdOrder.CustomerName);
}
}
message.Close();
Console.WriteLine("message.state after close: " + message.State.ToString());
Console.Read();
}
}
public class Order {
public Int32 Id { get; set; }
public String CustomerName { get; set; }
}
}

Flag / Unflag email sending in CRM 2011

In CRM 2011, I want to attach Contacts to Quote, no problems for that.
When I save the quote, for each Contact I want to send a email for reminder purpose. (With a plugin)
How It's possible to flag this and give the ability to CRM user to unflag this from the quote form with a checkbox.
The final purpose, It's to give the ability to CRM user to send a new email reminder to one or multiple contacts attached in the quote.
Can you help me ?
You will need to have a ribbon button that will call a JavaScript method in one of the web-resources.
In the CommandDefinition of you RibbonDiff XML you will need to send a parameter to the JS method which will contain all the IDs of selected records in the subgrid.
<CommandDefinitions>
<CommandDefinition Id="xyz.Button.SendEmail.command">
<EnableRules>
</EnableRules>
<DisplayRules>
</DisplayRules>
<Actions>
<JavaScriptFunction Library="$webresource:Test.Js" FunctionName="SendEmail">
<CrmParameter Value="SelectedControlAllItemIds" />
</JavaScriptFunction>
</Actions>
</CommandDefinition>
and then the JS method would be something like below wherein you will need to parse all the IDs and then process your logic
function SendEmail(selectedIds) {
if (selectedIds != null && selectedIds != “”) {
var strIds = selectedIds.toString();
var arrIds = strIds.split(“, ”);
for (var indxIds = 0; indxIds < arrIds.length; indxIds++) {
//The logic that you want to process on each record will come here.
}
} else {
alert(“No records selected !! !”);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}

Attaching a event receiver to a content type

I created some site columns / a content type and a list definition as part of a feature. I want to attach an eventreceiver to the content type. I added code to attach the event receiver to the content type. Using spmanager i can see that the event receiver is attached to the content type however when i create lists from the content type the event reciever is missing. Any ideas. My code is below
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
string asmName = System.Reflection.Assembly.GetExecutingAssembly().FullName;
string itemReceiverName = "xxxxxx.Intranet.SP.xxxxx.PermissionsUpdaterEventReceiver";
////surely a better way to get all lists than this
////re - do
using (SPSite thisSite = (SPSite)properties.Feature.Parent) {
using (SPWeb web = thisSite.RootWeb) {
SPContentType RambollNewsContentType = web.ContentTypes["RambollNewsContentType"];
RambollNewsContentType.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, itemReceiverName);
RambollNewsContentType.Update(true);
}
}
}
I am using this successfully. I left in my logging and the logging method.
/// <summary>
/// This method is executed on feature activation.
/// It attaches the event receiver to the content type.
/// </summary>
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
LogMessage("FeatureActivated - Start");
SPSite site = (SPSite)properties.Feature.Parent;
LogMessage("FeatureActivated - 1");
SPWeb web = site.RootWeb;
LogMessage("FeatureActivated - 2");
//ListContentTypes(web);
SPContentType ctype = web.ContentTypes["Wells Project Task List"];
LogMessage("FeatureActivated - 3");
LogMessage("ctype name: " + ctype.Name.ToString());
if (ctype != null)
{
LogMessage("FeatureActivated - I have a content type. Web url: " + web.Url);
SPEventReceiverDefinition er = ctype.EventReceivers.Add();
er.Class = "Wells.SharePoint.ProjectManagementEventReceiver";
er.Assembly = "ProjectManagementEventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a1cb21c41d80b7ae";
er.Type = SPEventReceiverType.ItemAdded;
er.Name = "ItemAdded";
er.SequenceNumber = 10001;
er.Update();
ctype.Update(false);
LogMessage("FeatureActivated - After ctype.update");
web.Dispose();
}
else
LogMessage("CT not found: " + web.Url);
LogMessage("FeatureActivated - End");
}
static void ListContentTypes(SPWeb web)
{
foreach (SPContentType ct in web.ContentTypes)
{
LogMessage("CT: " + ct.Name.ToString());
}
}
/// <summary>
/// This method is executed on feature deactivation.
/// It removes the event receiver from the content type
/// </summary>
/// <param name="properties"></param>
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
LogMessage("Feature DeActivated - Start");
SPSite site = (SPSite)properties.Feature.Parent;
SPWeb web = site.OpenWeb();
SPContentType contentType = web.ContentTypes["NAME OF CONTENT TYPE"];
if (contentType != null)
{
LogMessage("im have a content type. Web url: " + web.Url);
int i;
//Use the above integer to loop through the event recievers on the first list and delete the above assembly
for (i = 0; i < contentType.EventReceivers.Count; i++)
{
LogMessage("ER Count: " + contentType.EventReceivers.Count);
if (contentType.EventReceivers[i].Assembly.Contains("ProjectManagementEventReceiver"))
{
contentType.EventReceivers[i].Delete();
LogMessage("Deleting event receiver from CT");
}
}
contentType.Update();
}
else
LogMessage("CT not found: " + web.Url);
LogMessage("Feature DeActivated - End");
}
static void LogMessage(string msg)
{
StreamWriter wrtr = null;
try
{
wrtr = new StreamWriter("C:\\Logs\\FeatureActivatedDeactivated.txt", true);
wrtr.WriteLine(msg + "--[" + System.DateTime.Now.ToString() + "]" + Environment.NewLine);
wrtr.WriteLine(Environment.NewLine + "==================================");
}
catch (Exception e)
{
throw e;
}
finally
{
if (wrtr != null)
{
wrtr.Close();
wrtr.Dispose();
}
}
}
I am not sure is this related to your question or not but
but could you try to add the event receiver to the content type before you add the content type to the list.
I think the event receiver has to be added before because when adding a content type to a list the content type is not added directly to the list, rather a copy of it is added to the list. So when you add your content type to the list, there is no event receiver yet.
Correct me if i understand your question wrong?
Thanks

SharePoint issue with Eventhandler

PROBLEM: I have a list and if I create a new Item I would like to do the following:
Create a new AutoIncrement Number in Column [AutoGeneratedID]
Use [Titel] and [AutoGeneratedID] to create a HyperLink in the List and a new subsite
The problem is i cant get the [AutogeneratedID] filled with a value because it is an itemadded event but if i try to put the code together in an ItemAdding event, i get a problem as described in the following link:
http://www.sharepoint-tips.com/2006/09/synchronous-add-list-event-itemadding.html
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Diagnostics;
namespace KuC_Solution.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
// -----------------------------------------------------------
try
{
this.EventFiringEnabled = false;
// Column name AutoGeneratedID
string columnName = "AutoGeneratedID";
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = properties.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get the current list
SPList list = web.Lists[properties.ListId];
int highestValue = 0;
foreach (SPListItem item in list.Items)
{
if (item[columnName] != null && item[columnName].ToString().Trim() != "")
{
string value = item[columnName].ToString();
try
{
int currValue = int.Parse(value);
if (currValue > highestValue)
highestValue = currValue;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}
}
SPListItem currItem = list.Items.GetItemById(properties.ListItem.ID);
currItem[columnName] = (highestValue + 1).ToString();
currItem.SystemUpdate(false);
web.AllowUnsafeUpdates = false;
}
});
this.EventFiringEnabled = true;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
// -----------------------------------------------------------
}
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
//-------------------------------------------------------------
// Get the web where the event was raised
SPWeb spCurrentSite = properties.OpenWeb();
//Get the name of the list where the event was raised
String curListName = properties.ListTitle;
//If the list is our list named SubSites the create a new subsite directly below the current site
if (curListName == "TESTautoNumber")
{
//Get the SPListItem object that raised the event
SPListItem curItem = properties.ListItem;
//Get the Title field from this item. This will be the name of our new subsite
String curItemSiteName2 = properties.AfterProperties["Title"].ToString();
//String curItemSiteName3 = properties.AfterProperties["ID"].ToString();
String mia = properties.AfterProperties["AutoGeneratedID"].ToString();
String curItemSiteName = curItemSiteName2 + mia;
//Get the Description field from this item. This will be the description for our new subsite
//String curItemDescription = properties.AfterProperties["Projekt-ID"].ToString();
string curItemDescription = "CREWPOINT";
//String testme = "1";
//Update the SiteUrl field of the item, this is the URL of our new subsite
properties.AfterProperties["tLINK"] = spCurrentSite.Url + "/" + curItemSiteName;
//Create the subsite based on the template from the Solution Gallery
SPWeb newSite = spCurrentSite.Webs.Add(curItemSiteName, curItemSiteName, curItemDescription, Convert.ToUInt16(1033), "{4ADAD620-701D-401E-8DBA-B4772818E270}#myTemplate2012", false, false);
//Set the new subsite to inherit it's top navigation from the parent site, Usefalse if you do not want this.
newSite.Navigation.UseShared = true;
newSite.Close();
}
//---------------------------------------------------------------
}
}
}