Sharepoint regional settings - sharepoint-2010

I've created a Web Part using Visual Studio to show the selected columns of a list in gridview. But the problem is that whenever I'm changing the locale to English-UK (it's by default English-US), unfortunately it as well as the site has no effect on it though the date format is supposed to be changed.
I tried the following code to change the locale and date format:
protected void btnClick_Event(object sender, EventArgs e)
{
using (SPSite osite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb oweb = osite.OpenWeb())
{
if (DropDownList1.SelectedValue == "English-UK")
{
oweb.AllowUnsafeUpdates = true;
oweb.Locale = new System.Globalization.CultureInfo("en-GB");
oweb.Update();
}
else if(DropDownList1.SelectedValue == "English-US")
{
oweb.Locale = new System.Globalization.CultureInfo("en-US");
oweb.Update();
}
lblmsg.Text = "Region changed successfully";
}
}
}
Webpart code is as follows:
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
namespace SharePointProject100.CustomGridWebpart
{
[ToolboxItemAttribute(false)]
public class CustomGridWebpart : WebPart
{
SPGridView grdview = new SPGridView();
protected override void CreateChildControls()
{
grdview.ID = "grdview";
grdview.AutoGenerateColumns = false;
this.Controls.Add(grdview);
using (SPSite osite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = osite.OpenWeb())
{
SPList mylist = web.Lists["EmployeeDetails"];
BindToGrid(mylist, grdview);
}
}
}
private void BindToGrid(SPList myList, SPGridView gridView)
{
// get all the listitem
SPListItemCollection results = myList.Items;
// create the datatable object
DataTable table = new DataTable();
table.Columns.Add("Employee Name", typeof(string));
table.Columns.Add("DOB", typeof(string));
table.Columns.Add("JoiningDate", typeof(string));
table.Columns.Add("MembershipExpiryDate", typeof(string));
// Create rows for each splistitem
DataRow row;
foreach (SPListItem result in results)
{
row = table.Rows.Add();
row["Employee Name"] = Convert.ToString(result["Employee Name"]);
row["DOB"] = Convert.ToString(result["DOB"]);
row["JoiningDate"] = Convert.ToString(result["JoiningDate"]);
row["MembershipExpiryDate"] = Convert.ToString(result["MembershipExpiryDate"]);
}
// create the bound fields
SPBoundField boundField;
boundField = new SPBoundField();
boundField.HeaderText = "Employee Name";
boundField.DataField = "Employee Name";
boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
boundField.ItemStyle.Wrap = false;
gridView.Columns.Add(boundField);
boundField = new SPBoundField();
boundField.HeaderText = "DOB";
boundField.DataField = "DOB";
boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
boundField.ItemStyle.Wrap = false;
gridView.Columns.Add(boundField);
boundField = new SPBoundField();
boundField.HeaderText = "JoiningDate";
boundField.DataField = "JoiningDate";
boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
boundField.ItemStyle.Wrap = false;
gridView.Columns.Add(boundField);
boundField = new SPBoundField();
boundField.HeaderText = "MembershipExpiryDate";
boundField.DataField = "MembershipExpiryDate";
boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
boundField.ItemStyle.Wrap = false;
gridView.Columns.Add(boundField);
gridView.AutoGenerateColumns = false;
gridView.DataSource = table.DefaultView;
gridView.DataBind();
}
}
}

Setting the LocaleID in the web's RegionalSettings is supposed to mark it "dirty" (looking at the disassembled code in ILSpy), but I have not had any luck in then getting it to "update" the other proerties based off that change.

Related

How to convert MailAttachment to MimeKit Attachment

We have to rework how we're sending emails since we are using Amazon SES. In the past, we were using smtp but can't do that in this case. The class that needs updated has taken in a MailMessage object and used smtp to send it. So I'm trying to rework the method to be able to continue to accept the MailMessage object and convert it to a MimeKit MimeMessage. For the most part it's working fine except when it comes to attachments. In the code I have, the attachment gets added and sent, however, when trying to open it appears it's corrupted or something. In my test case I attached a csv file. I could not open it in excel after receiving the email.
public class EmailAbstraction
{
public virtual void Send(MailMessage mailMessage)
{
sendMessage(mailMessage);
}
private static void sendMessage(MailMessage mailMessage)
{
using (var client = new AmazonSimpleEmailServiceClient(AwsConstants.SESAWSKey, AwsConstants.SESAWSSecret, AwsConstants.RegionEndpoint))
{
foreach (var to in mailMessage.To)
{
using (var messageStream = new MemoryStream())
{
var newMessage = new MimeMessage();
var builder = new BodyBuilder
{
HtmlBody = mailMessage.Body
};
newMessage.From.Add(mailMessage.From == null
? new MailboxAddress(EmailConstants.DefaultFromEmailDisplayName, EmailConstants.DefaultFromEmailAddress)
: new MailboxAddress(mailMessage.From.Address));
newMessage.To.Add(new MailboxAddress(to.DisplayName, to.Address));
newMessage.Subject = mailMessage.Subject;
foreach (var attachment in mailMessage.Attachments)
{
builder.Attachments.Add(attachment.Name, attachment.ContentStream);
}
newMessage.Body = builder.ToMessageBody();
newMessage.WriteTo(messageStream);
var request = new SendRawEmailRequest
{
RawMessage = new RawMessage { Data = messageStream }
};
client.SendRawEmail(request);
}
}
}
}
}
And in my test app, I have this.
internal class Program
{
private static void Main(string[] args)
{
var s = GetFileStream();
var m = new MailMessage();
var sender = new MailAddress("info#ourwebsite.com", "info");
m.From = sender;
m.Sender = sender;
m.Body = "test email";
m.Subject = "test subject";
m.To.Add(myemail);
m.Attachments.Add(new Attachment(s, "test-file.csv"));
new EmailAbstraction().Send(m);
}
private static MemoryStream GetFileStream()
{
var stream = new MemoryStream();
var fileStream = File.Open(#"C:\Users\dev\Desktop\test-file.csv", FileMode.Open);
fileStream.CopyTo(stream);
fileStream.Close();
return stream;
}
}
This is just copied from the MimeKit source code:
static MimePart GetMimePart (System.Net.Mail.AttachmentBase item)
{
var mimeType = item.ContentType.ToString ();
var contentType = ContentType.Parse (mimeType);
var attachment = item as System.Net.Mail.Attachment;
MimePart part;
if (contentType.MediaType.Equals ("text", StringComparison.OrdinalIgnoreCase))
part = new TextPart (contentType);
else
part = new MimePart (contentType);
if (attachment != null) {
var disposition = attachment.ContentDisposition.ToString ();
part.ContentDisposition = ContentDisposition.Parse (disposition);
}
switch (item.TransferEncoding) {
case System.Net.Mime.TransferEncoding.QuotedPrintable:
part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
break;
case System.Net.Mime.TransferEncoding.Base64:
part.ContentTransferEncoding = ContentEncoding.Base64;
break;
case System.Net.Mime.TransferEncoding.SevenBit:
part.ContentTransferEncoding = ContentEncoding.SevenBit;
break;
//case System.Net.Mime.TransferEncoding.EightBit:
// part.ContentTransferEncoding = ContentEncoding.EightBit;
// break;
}
if (item.ContentId != null)
part.ContentId = item.ContentId;
var stream = new MemoryStream ();
item.ContentStream.CopyTo (stream);
stream.Position = 0;
part.Content = new MimeContent (stream);
return part;
}

Issue with API Deleting for Team Foundation Server TFS

Hello can anyone tell me how to delete files using the API for TFS? Below is what I have but I can not get it to work any help would really be appreciated.
string[] InLocalDirectory = Directory.GetFiles(LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path), "*", SearchOption.AllDirectories);
// Source Control
List<string> InSourceControl = new List<string>();
ItemSet SetOfItem = _ServerVersionControl.GetItems(_ServerPath, VersionSpec.Latest, RecursionType.Full);
foreach (Item GotItem in SetOfItem.Items)
{
ItemType TypeOfItem = GotItem.ItemType;
if (TypeOfItem == ItemType.File)
{
string LocalPath = _WorkspaceLocal.GetLocalItemForServerItem(GotItem.ServerItem);
InSourceControl.Add(LocalPath);
}
}
List<int> ToDeleteById = new List<int>();
foreach (string SourceFile in InSourceControl)
{
if (!IsIgnored(SourceFile) && !InLocalDirectory.Contains(SourceFile))
{
// Delete Source Control File
Item DeleteItem = _ServerVersionControl.GetItem(SourceFile);
ToDeleteById.Add(DeleteItem.ItemId);
// Update Local XML Directory
DataXml.Delete(SourceFile);
}
}
WorkItemStore wis = _CollectionTeamProject.GetService<WorkItemStore>();
wis.DestroyWorkItems(ToDeleteById);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
namespace ConsoleAppX
{
class Program
{
static void Main(string[] args)
{
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
VssConnection connection = new VssConnection(new Uri("https://tfsuri"), creds);
TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>();
TfvcItem ti = tfvcClient.GetItemAsync("ProjectName", "$/FilePath","FileName").Result;
TfvcChange tchange = new TfvcChange(ti,VersionControlChangeType.Delete);
List<TfvcChange> change = new List<TfvcChange> { tchange };
TfvcChangeset tchangeset = new TfvcChangeset();
tchangeset.Changes = change;
tfvcClient.CreateChangesetAsync(tchangeset);
}
}
}
To delete a file, you need to use the VersionControlServer class to get an existing Workspace or create a new workspace. The workspace has a PendDelete method to create pending changes in the workspace. Then use the Workspace.Checkin method to commit them to source control:
https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.versioncontrol.client.workspace.aspx
I tried the penddelete before I tried the last way of doing it. But even when I manually go and delete a file and it hits the _WorkspaceLocal.PendDelete(SourceFile); line and is inserted for deletion it does not pick up on the line if (changes.Count() > 0) and then never check in.
string[] InLocalDirectory = Directory.GetFiles(LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path), "*", SearchOption.AllDirectories);
// Source Control
List<string> InSourceControl = new List<string>();
ItemSet SetOfItem = _ServerVersionControl.GetItems(_ServerPath, VersionSpec.Latest, RecursionType.Full);
foreach (Item GotItem in SetOfItem.Items)
{
ItemType TypeOfItem = GotItem.ItemType;
if (TypeOfItem == ItemType.File)
{
string LocalPath = _WorkspaceLocal.GetLocalItemForServerItem(GotItem.ServerItem);
InSourceControl.Add(LocalPath);
}
}
List<int> ToDeleteById = new List<int>();
foreach (string SourceFile in InSourceControl)
{
if (!IsIgnored(SourceFile) && !InLocalDirectory.Contains(SourceFile))
{
// Delete Source Control File
Item DeleteItem = _ServerVersionControl.GetItem(SourceFile);
ToDeleteById.Add(DeleteItem.ItemId);
// Update Local XML Directory
DataXml.Delete(SourceFile);
// Set for Deletion
_WorkspaceLocal.PendDelete(SourceFile);
}
}
string ConflictMessage = "";
Conflict[] conflicts = _WorkspaceLocal.QueryConflicts(new string[] { _LocalPath }, true);
foreach (Conflict conflict in conflicts)
{
if (conflict != null)
{
try
{
if (conflict.CanMergeContent)
{
conflict.Resolution = Resolution.AcceptMerge;
}
else
{
conflict.Resolution = Resolution.AcceptYoursRenameTheirs;
}
ConflictMessage += #"\n\r\n\r" + conflict.GetFullMessage();
_WorkspaceLocal.ResolveConflict(conflict);
}
catch (Exception ex)
{
LogicAppConfig.Insert(AppConfigLogic.TypeOfConfig.Message, "Error Detected Previously:\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.Source + "\r\n\r\n" + ex.StackTrace + "\r\n\r\n" + LogicAppConfig.Query(AppConfigLogic.TypeOfConfig.Path));
}
}
}
if (!String.IsNullOrEmpty(ConflictMessage))
{
LogicAppConfig.Insert(AppConfigLogic.TypeOfConfig.Message, ConflictMessage);
}
PendingChange[] changes = _WorkspaceLocal.GetPendingChanges();
if (changes.Count() > 0)
{
int ChangeSetId = _WorkspaceLocal.CheckIn(changes, _WorkspaceName + " Deleted by Member Collaboration Utility");
}

Coded UI Testing Without UIMAP

I have working in coded ui project. I have trying to coded ui test without UIMAP.In this requirement using following code in c#.
[TestMethod]
public void CodedUITestMethod1()
{
var app = ApplicationUnderTest.Launch("C:\\Windows\\System32\\calc.exe", "%windir%\\System32\\calc.exe");
WinWindow calWindow = app.SearchFor<WinWindow>(new { Name = "Calculator" },new { ClassName = "CalcFrame" });
WinButton buttonAdd = calWindow.Container.SearchFor<WinButton>(new { Name = "Add" });
WinButton buttonEqual = calWindow.Container.SearchFor<WinButton>(new { Name = "Equals" });
WinButton button1 = calWindow.Container.SearchFor<WinButton>(new { Name = "1" });
WinButton button2 = calWindow.Container.SearchFor<WinButton>(new { Name = "2" });
WinButton button3 = calWindow.Container.SearchFor<WinButton>(new { Name = "3" });
WinText txtResult = calWindow.Container.SearchFor<WinText>(new { Name = "Result" });
//do all the operations
Mouse.Click(button2);
Mouse.Click(buttonAdd);
Mouse.Click(button3);
Mouse.Click(buttonEqual);
//evaluate the results
Assert.AreEqual("5", txtResult.DisplayText);
//close the application
app.Close();
}
I have referred following dll's
Microsoft.VisualStudio.QualityTools.CodedUITestFramework
Microsoft.VisualStudio.QualityTools.UnitTestFramework
Microsoft.VisualStudio.TestTools.UITest.Common
Microsoft.VisualStudio.TestTools.UITest.Extension
Microsoft.VisualStudio.TestTools.UITesting
But,Above the code raise the error like
'Microsoft.VisualStudio.TestTools.UITesting.ApplicationUnderTest' does not contain a definition for 'SearchFor' and no extension method 'SearchFor' accepting a first argument of type
'Microsoft.VisualStudio.TestTools.UITesting.ApplicationUnderTest' could be found (are you missing a using directive or an assembly reference?)
I don't know what is this issue. Please help for this task.
Thanks in Advance.
CodedUIExtension File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UITesting;
namespace CodedUITest
{
public static class CodedUIExtension
{
public static T SearchFor<T>(this UITestControl _this, dynamic searchProperties, dynamic filterProperties = null) where T : UITestControl, new()
{
T ctrl = new T();
ctrl.Container = _this;
IEnumerable<string> propNames = ((object)searchProperties).GetPropertiesForObject();
foreach (var item in propNames)
{
ctrl.SearchProperties.Add(item, ((object)searchProperties).GetPropertyValue(item).ToString());
}
object s = filterProperties;
if (s != null)
{
propNames = ((object)filterProperties).GetPropertiesForObject();
foreach (var item in propNames)
{
ctrl.SearchProperties.Add(item, ((object)filterProperties).GetPropertyValue(item).ToString());
}
}
return ctrl as T;
}
private static IEnumerable<string> GetPropertiesForObject(this object _this)
{
return (from x in _this.GetType().GetProperties() select x.Name).ToList();
}
private static object GetPropertyValue(this object _this, string propName)
{
var prop = (from x in _this.GetType().GetProperties() where x.Name == propName select x).FirstOrDefault();
return prop.GetValue(_this);
}
}
}
Testmethod
[TestMethod]
public void CodedUITestMethod1()
{
try
{
//ProcessStartInfo processStartInfo = new ProcessStartInfo(#"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CodedUITestBuilder.exe ");
//processStartInfo.Arguments = #"/standalone";
//ApplicationUnderTest app = ApplicationUnderTest.Launch(processStartInfo);
ApplicationUnderTest app = ApplicationUnderTest.Launch("C:\\Windows\\System32\\calc.exe", "%windir%\\System32\\calc.exe");
WinWindow calWindow = new WinWindow();
calWindow = app.SearchFor<WinWindow>(
/* pass search properties */
new { Name = "Calculator" },
/*pass filter properties if needed */
new { ClassName = "CalcFrame" });
WinButton buttonAdd = calWindow.Container.SearchFor<WinButton>(new { Name = "Add" });
WinButton buttonEqual = calWindow.Container.SearchFor<WinButton>(new { Name = "Equals" });
WinButton button1 = calWindow.Container.SearchFor<WinButton>(new { Name = "1" });
WinButton button2 = calWindow.Container.SearchFor<WinButton>(new { Name = "2" });
WinButton button3 = calWindow.Container.SearchFor<WinButton>(new { Name = "3" });
WinText txtResult = calWindow.Container.SearchFor<WinText>(new { Name = "Result" });
//do all the operations
Mouse.Click(button2);
Mouse.Click(buttonAdd);
Mouse.Click(button3);
Mouse.Click(buttonEqual);
//evaluate the results
Assert.AreEqual("5", txtResult.DisplayText);
//close the application
app.Close();
}
catch (Exception e)
{
}
}
I hope this is working sample for code ui without uimap

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;
}
}
}

Object reference not set to an instance of an object when using SPGridViewPager

It's my first sharepoint project and eveything looks very confusing.
I need to have a SPGridView with paging.
Here is an entire code of mx webpart:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace FirstSPGridView.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public class VisualWebPart1 : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/FirstSPGridView/SPGridViewWebPartTest/VisualWebPart1UserControl.ascx";
SPGridView _grid;
protected override void CreateChildControls()
{
base.CreateChildControls();
try
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
//Using RunWithElevatedPrivileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(mySite.ID))
{
using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{
_grid = new SPGridView();
_grid.AutoGenerateColumns = false;
_grid.PageSize = 3;
_grid.AllowPaging = true;
_grid.DataSource = SelectData();
Controls.Add(_grid);
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
}
}
});
}
catch (Exception ex)
{ }
}
protected sealed override void Render(HtmlTextWriter writer)
{
try
{
GenerateColumns();
_grid.DataBind();
base.Render(writer);
}
catch (Exception e)
{
throw new NotImplementedException();
}
}
private void GenerateColumns()
{
BoundField clientNameColumn = new BoundField();
clientNameColumn.HeaderText = "Client";
clientNameColumn.DataField = "LastName";
_grid.Columns.Add(clientNameColumn);
BoundField birthDayColumn = new BoundField();
birthDayColumn.HeaderText = "BirthDate";
birthDayColumn.DataField = "BirthDate";
_grid.Columns.Add(birthDayColumn);
}
public DataTable SelectData()
{
var dataGet = new DataTable();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (
var conn =
new SqlConnection(
"Data Source=localhost;Initial Catalog=AdventureWorksDW2008R2;Integrated Security=True")
)
{
var adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("Select TOP 100 LastName,Birthdate FROM DimCustomer");
adapter.SelectCommand.Connection = conn;
conn.Open();
adapter.Fill(dataGet);
}
});
return dataGet;
}
}
}
Everything was working (except paging until I added this code:
SPGridViewPager pager = new SPGridViewPager();
pager.GridViewId = _grid.ID;
this.Controls.Add(pager);
After that I get an exception on the Render method here:
base.Render(writer);
StackTrace is:
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)\r\n at Microsoft.SharePoint.WebControls.Menu.FindControlByWalking(Control namingContainer, String id)\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.get_GridViewControl()\r\n at Microsoft.SharePoint.WebControls.SPGridViewPager.Render(HtmlTextWriter output)\r\n at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)\r\n at System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer)\r\n at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)\r\n at FirstSPGridView.VisualWebPart1.VisualWebPart1.Render(HtmlTextWriter writer)
How can I fix that error?
You must just set ID for _grid.
For example, _grid.ID = "_gridView";