How can i send data from ToolPart1 class to WebPart1 class - sharepoint

I cannot send a array data from ToolPart to WebPart although string data is oke. I debug and know that the statement code webpart.ListColumns[i] = lstBoxSend.Items[i].Value is right and have data but i dont know why property ListColumns in WebPart is null
public class ToolPart1 : Microsoft.SharePoint.WebPartPages.ToolPart
{
public override void ApplyChanges()
{
base.ApplyChanges();
var webpart = (WebPart1)this.ParentToolPane.SelectedWebPart;
webpart.SiteUrl = txtURL.Text;
webpart.ListName = ddlList.SelectedValue;
if (webpart.ListColumns == null)
{
webpart.ListColumns = new string[lstBoxSend.Items.Count];
}
for (int i = 0; i < lstBoxSend.Items.Count; i++)
{
webpart.ListColumns[i] = lstBoxSend.Items[i].Value;
}
}
}
public class WebPart1 : Microsoft.SharePoint.WebPartPages.WebPart
{
public string SiteUrl { get; set; }
public string ListName { get; set; }
public string[] ListColumns { get; set; }
}
I want receive array data in WebPart From ToolPart

Override ApplyChanges to send data to webpart, check this demo
public override void ApplyChanges()
{
int i = 0;
WebPartCustom1 wpCustom = (WebPartCustom1)this.ParentToolPane.SelectedWebPart;
int.TryParse(_itensToolPart.Text, out i);
wpCustom.MyInt = i;
wpCustom.MyString = _titleToolPart.Text;
wpCustom.MyGuid = _ddlToolPart.SelectedItem.Value;
}

Related

Create field in SharePoint programmatically using CSOM (Not with XML)

Is it possible to create fields in SharePoint with CSOM, not using XML?
I've seen many examples using XML, but none with just setting properties for the field programmatically?
fields.Add(new **FieldCreationInformation** {
InternalName = "Test",
etc..
});
That's doable, in the following example is introduced a FieldCreationInformation class:
[XmlRoot("Field")]
public class FieldCreationInformation
{
[XmlAttribute("ID")]
public Guid Id { get; set; }
[XmlAttribute()]
public string DisplayName { get; set; }
[XmlAttribute("Name")]
public string InternalName { get; set; }
[XmlIgnore()]
public bool AddToDefaultView { get; set; }
//public IEnumerable<KeyValuePair<string, string>> AdditionalAttributes { get; set; }
[XmlAttribute("Type")]
public FieldType FieldType { get; set; }
[XmlAttribute()]
public string Group { get; set; }
[XmlAttribute()]
public bool Required { get; set; }
public string ToXml()
{
var serializer = new XmlSerializer(GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, this, emptyNamepsaces);
return stream.ToString();
}
}
public FieldCreationInformation()
{
Id = Guid.NewGuid();
}
}
and then extension method for creating a new field:
public static class FieldCollectionExtensions
{
public static Field Add(this FieldCollection fields, FieldCreationInformation info)
{
var fieldSchema = info.ToXml();
return fields.AddFieldAsXml(fieldSchema, info.AddToDefaultView, AddFieldOptions.AddFieldToDefaultView);
}
}
Usage
var fieldInfo = new FieldCreationInformation();
fieldInfo.FieldType = FieldType.Geolocation;
fieldInfo.InternalName = "ContactsLocation";
fieldInfo.DisplayName = "Contacts Location";
ctx.Site.RootWeb.Fields.Add(fieldInfo);
ctx.ExecuteQuery();
When I add fields with CSOM/JSOM I use the method on the FieldCollection AddFieldAsXml. This requires you to build a string of xml with all of the properties for the desired field, but it works. I included an excerpt of the related cpde below:
Microsoft.SharePoint.Client.Web web = _context.Web;
FieldCollection fields = web.Fields;
_context.Load(fields);
_context.ExecuteQuery();
Field field = fields.FirstOrDefault(f => f.StaticName == _staticName);
if (field == null)
{
Field createdField = fields.AddFieldAsXml(xml, false, AddFieldOptions.AddToNoContentType);
_context.Load(createdField);
_context.ExecuteQuery();
}
Similar code is used if you would like to add a field directly to an existing list.

Xml Parsing in C#

http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom on this site, I wrote the following code to retrieve the data.
protected void Button1_Click(object sender, EventArgs e)
{
string adresal = "http://" + txtAd.Text;
WebResponse GelenCevap;
WebRequest adresistegi = HttpWebRequest.Create(adresal);
GelenCevap = adresistegi.GetResponse();
StreamReader CevapOku = new StreamReader(GelenCevap.GetResponseStream());
string KaynakKodlar = CevapOku.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
xmlDoc.Load("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom"); // Load the XML document from the specified file
XmlNodeList depremler = xmlDoc.GetElementsByTagName("entry");
foreach (XmlNode node in depremler)
{
var a = node.ChildNodes;
foreach (XmlElement x in a)
{
ListBox1.Items.Add(x.InnerText);
}
}
}
In this way I get all the data in the ListBox.But I need to assign them to variable data line by line.How can I do? I would appreciate if you can help.
Also i need id,title, updated, georss:point,georss:elev variables.
First add an Enrty and Category class:
public class Entry
{
public string Id { get; set; }
public string Title { get; set; }
public string Updated { get; set; }
public string Summary { get; set; }
public string GPoint { get; set; }
public string GElev { get; set; }
public List<string> Categories { get; set; }
}
public class Category
{
public string Label { get; set; }
public string Term { get; set; }
}
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path");
List<Entry> entries = (from x in xDoc.Descendants("entry")
select new Entry()
{
Id = (string) x.Element("id"),
Title = (string)x.Element("title"),
Updated = (string)x.Element("updated"),
Summary = (string)x.Element("summary"),
GPoint = (string)x.Element("georss:point"),
GElev = (string)x.Element("georss:elev"),
Categories = (from c in x.Elements("category")
select new Category
{
Label = (string)c.Attribute("label"),
Term = (string)c.Attribute("term")
}).ToList();
}).ToList();

XML serialization and deserialization

I receive an XML file from a server, which contains many elements, and one attribute.
When Try and serialize/deserialize the xml, all the elements are serialized/deserialized properly, except for the attribute. Why does this happen?
here is the XML file:
"<msg><msisdn>123456789</msisdn><sessionid>535232573</sessionid><phase>2</phase><request type=\"1\">*120*111#</request></msg>"
and the class:
[Serializable]
[XmlRoot(ElementName = "msg", Namespace = "")]
public class myClass
{
[XmlElement(ElementName = "msisdn")]
public string number = string.Empty;
[XmlElement(ElementName = "sessionid")]
public string sessionID = string.Empty;
[XmlAttribute(AttributeName = "type")]
public string requestType = string.Empty;
[XmlElement(ElementName = "request")]
public string request = string.Empty;
[XmlElement(ElementName = "phase")]
public string phase = string.Empty;
public override string ToString()
{
return number + " - " + sessionID;
}
}
Thanks for any help
Try defining a sub class for request because type is attribute of the request and not of the root MyClass:
[XmlRoot(ElementName = "msg", Namespace = "")]
public class MyClass
{
[XmlElement(ElementName = "msisdn")]
public string Number { get; set; }
[XmlElement(ElementName = "sessionid")]
public string SessionID { get; set; }
[XmlElement(ElementName = "request")]
public Request Request { get; set; }
[XmlElement(ElementName = "phase")]
public string Phase { get; set; }
public override string ToString()
{
return Number + " - " + SessionID;
}
}
public class Request
{
[XmlAttribute(AttributeName = "type")]
public string Type { get; set; }
[XmlText]
public string Value { get; set; }
}
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(MyClass));
using (var stringReader = new StringReader("<msg><msisdn>123456789</msisdn><sessionid>535232573</sessionid><phase>2</phase><request type=\"1\">*120*111#</request></msg>"))
using (var xmlReader = XmlReader.Create(stringReader))
{
var obj = (MyClass)serializer.Deserialize(xmlReader);
Console.WriteLine(obj.Request.Type);
}
}
}

How to bind List Data to combobox

I mae a WCF service that contain this method :
public List<LocationDB> GetLocation()
{
List<LocationDB> locations = null;
using (SqlConnection connection = new SqlConnection(conn))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = string.Format("Select L_ID ,L_Name from Location");
connection.Open();
//code to fill the locations list..
my problem is when i want to bind the result from this method in my code i do the following.
void MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
client.GetLocationCompleted += new EventHandler<GetLocationCompletedEventArgs>(client_GetLocationCompleted);
client.GetLocationAsync();
}
}
and :
void client_GetLocationCompleted(object sender, GetLocationCompletedEventArgs e)
{
LocationCombo.ItemsSource = e.Result;
LocationCombo.SelectedValuePath =
LocationCombo.DisplayMemberPath =
}
and finally my LocationDB Class that is located in the App_code folder in the asp web site:
[DataContract]
public class LocationDB
{
[DataMember]
public int Lid { get; set; }
[DataMember]
public int SmId { get; set; }
[DataMember]
public string Lname { get; set; }
how can i bind the SelectedValePath and the DisplayMemberPath in code behind not in XAML.
Thanks
From what I can tell you already have everything you need although some of it needs to be in a different order.
void client_GetLocationCompleted(object sender, GetLocationCompletedEventArgs e)
{
LocationCombo.SelectedValuePath = "Lid";
LocationCombo.DisplayMemberPath = "Lname";
LocationCombo.ItemsSource = e.Result;
}
You should be able to set each of them to a string which represents the property (on the bject you're binding to) to use as the SelectedValuePath and DisplayMemberPath respectively:
LocationCombo.SelectedValuePath = "Lid";
LocationCombo.DisplayMemberPath ="Lname";
LocationCombo.ItemsSource = e.Result.ToList();

Automapper map custom collections

Hello. I have a list that looks like this one:
public class PagedList<T> : List<T>
{
public PagedList(IEnumerable<T> collection) : base(collection)
{ }
public int TotalItems { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
//some other properties
}
and used in repository for paging
public PagedList<TEntity> GetPaged(int page)
{
var pagedEntities = some_query;
return pagedEntities.AsPagedList(totalResults, page, pageSize);
}
The same PagedList is also used in asp mvc view models for paging.
Is it possible to map this collections using Automapper with all the properties TotalItems/CurrentPage/... ?
PagedList<DbItem> dbItems = _repository.GetPages(page);
var viewItems = new PagedList<SomeItemView>();
Mapper.Map(dbItems , viewItems);
Tahnk You !
This worked for me. Are you looking for something more generic?
public class DbItem
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ViewItem
{
public int Id { get; set; }
public string Name { get; set; }
}
public class PagedList<T>: List<T>
{
public int TotalItems { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
}
class Program
{
static void Main(string[] args)
{
MapItems();
}
public static void MapItems()
{
Mapper.CreateMap<DbItem, ViewItem>();
Mapper.CreateMap<PagedList<DbItem>, PagedList<ViewItem>>()
.AfterMap((s, d) => Mapper.Map<List<DbItem>, List<ViewItem>>(s, d));
var dbList = new PagedList<DbItem>
{
new DbItem {Id = 1, Name = "a"},
new DbItem {Id = 2, Name = "b"}
};
dbList.TotalItems = 2;
dbList.CurrentPage = 1;
dbList.PageSize = 10;
var viewList = Mapper.Map<PagedList<DbItem>, PagedList<ViewItem>>(dbList);
Console.WriteLine(viewList.TotalItems);
Console.WriteLine(viewList.CurrentPage);
Console.WriteLine(viewList.PageSize);
Console.WriteLine(viewList[0].Id + " " + viewList[0].Name);
Console.WriteLine(viewList[1].Id + " " + viewList[1].Name);
Console.ReadLine();
}
}
What you need is a custom type converter
public class PagedListConverter<TIn, TOut> : ITypeConverter<IPagedList<TIn>, IPagedList<TOut>>
{
public IPagedList<TOut> Convert(AutoMapper.ResolutionContext context)
{
var source = (IPagedList<TIn>)context.SourceValue;
var mapped = Mapper.Map<IList<TOut>>(source);
return new StaticPagedList<TOut>(mapped, source.GetMetaData());
}
}
Usage:
Mapper.CreateMap<IPagedList<Company>, IPagedList<CompanyViewModel>>().ConvertUsing<PagedListConverter<Company, CompanyViewModel>>();
For those who have faced the similar problem recently, and as an update to NoPyGod's answer, you can achieve the general mapping using ITypeConverter. According to the official documentation:
AutoMapper also supports open generic type converters with any number of generic arguments:
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap(typeof(Source<>), typeof(Destination<>)).ConvertUsing(typeof(Converter<,>)));
The closed type from Source will be the first generic argument, and the closed type of Destination will be the second argument to close Converter<,>.
So the custom type converter would be:
private class Converter<TSource, TDestination>
: ITypeConverter<PagedList<TSource>, PagedList<TDestination>>
{
public PagedList<TDestination> Convert(
PagedList<TSource> source,
PagedList<TDestination> destination,
ResolutionContext context) =>
new PagedList<TDestination>(
context.Mapper.Map<List<TSource>, List<TDestination>>(source));
/* Additional settings comes here. */
}
And then register it:
this.CreateMap(typeof(PagedList<>), typeof(PagedList<>)).ConvertUsing(typeof(Converter<,>));

Resources