SharePoint / WSS3.0 : Creating static webpart connections at runtime - c#

I've created several master / detail webparts that need to be connected. We have a requirement the the webparts self discover and connect to other connectable webparts on the page. I've acheived this in a standard ASP.NET page with the following code:
protected override void OnLoad(EventArgs e)
{
WebPartManager manager = WebPartManager.GetCurrentWebPartManager(Page);
manager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
This approach, however, does not work in SharePoint. Using the SharePoint version of these objects results in a generic sharepoint error:
protected override void OnLoad(EventArgs e)
{
SPWebPartManager spManager = SPWebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
spManager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
The following approach works, but creates the connection as part of the user's personalization:
protected override void OnLoad(EventArgs e)
{
SPWebPartConnection connection = (from SPWebPartConnection c in spManager.SPWebPartConnections where c != null && c.Consumer == this && c.ConsumerConnectionPointID == "WebPartConnectableConsumer" && c.Provider == provider select c).FirstOrDefault();
if (connection == null)
{
try
{
ProviderConnectionPointCollection providerCollections = spManager.GetProviderConnectionPoints(provider);
ConsumerConnectionPointCollection consumerConnections = spManager.GetConsumerConnectionPoints(this);
connection = spManager.SPConnectWebParts(provider, providerCollections["WebPartConnectableProvider"], this, consumerConnections["WebPartConnectableConsumer"]);
}
catch { }
}
}

Hidden in the logs was an error stating that the StaticConnections property cannot be used in SharePoint/WSS environments. Instead, the SPWebPartConnections property must be used. Moreover, connections must be added prior to the load event (eg. OnInit).
Working code:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
SetUpProviderConnection();
}
private bool SetUpProviderConnection()
{
bool connectionCreated = false;
WebPartManager manager = WebPartManager.GetCurrentWebPartManager(Page);
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in manager.WebParts)
{
BaseWebPart provider = webPart as BaseWebPart;
if (provider != null && (provider != this))
{
if (manager is Microsoft.SharePoint.WebPartPages.SPWebPartManager)
{
SPWebPartManager spManager = SPWebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
spManager.SPWebPartConnections.Add(new SPWebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
else
{
manager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
connectionCreated = true;
}
}
return connectionCreated;
}

Related

Xamarin google Native Ads IOS

I am trying to implement Native ads in xamarin it works fine with android but I have a problem with ios
Here is my code
public class AdMobNativeAdRenderer : ViewRenderer<Controls.NativeAdView, UnifiedNativeAdView>, IAdLoaderDelegate, IUnifiedNativeAdDelegate, IUnifiedNativeAdLoaderDelegate, IVideoControllerDelegate
{
public UnifiedNativeAdView nativeAdView = null;
public void DidReceiveUnifiedNativeAd(AdLoader adLoader, UnifiedNativeAd nativeAd)
{
// A unified native ad has loaded, and can be displayed.
nativeAd.Delegate = this;
// The headline and mediaContent are guaranteed to be present in every native ad.
nativeAdView.NativeAd = nativeAd;
if (nativeAdView.HeadlineView==null)
{
nativeAdView.HeadlineView= new UILabel();
}
(nativeAdView.HeadlineView as UILabel).Text = nativeAd.Headline;
if (nativeAdView.MediaView == null) {
nativeAdView.MediaView = new MediaView();
}
if (nativeAdView.MediaView.MediaContent == null)
{
nativeAdView.MediaView.MediaContent = new MediaContent();
}
nativeAdView.MediaView.MediaContent = nativeAd.MediaContent;
nativeAdView.MediaView.ContentMode = UIViewContentMode.ScaleAspectFill;
if (nativeAdView.BodyView==null)
{
nativeAdView.BodyView = new UILabel();
}
(nativeAdView.BodyView as UILabel).Text = nativeAd.Body;
nativeAdView.BodyView.Hidden = nativeAd.Body == null;
if (nativeAdView.CallToActionView==null)
{
nativeAdView.CallToActionView = new UIButton();
}
(nativeAdView.CallToActionView as UIButton).SetTitle(nativeAd.CallToAction,UIControlState.Normal);
nativeAdView.CallToActionView.Hidden = nativeAd.CallToAction == null;
if (nativeAdView.IconView==null)
{
nativeAdView.IconView = new UIImageView();
}
(nativeAdView.IconView as UIImageView).Image = nativeAd.Icon.Image;
nativeAdView.IconView.Hidden = nativeAd.Icon == null;
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
nativeAdView.StoreView.Hidden = nativeAd.Store == null;
if (nativeAdView.PriceView==null)
{
nativeAdView.PriceView = new UILabel();
}
(nativeAdView.PriceView as UILabel).Text = nativeAd.Price;
nativeAdView.PriceView.Hidden = nativeAd.Price == null;
if (nativeAdView.AdvertiserView==null)
{
nativeAdView.AdvertiserView = new UILabel();
}
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
(nativeAdView.AdvertiserView as UILabel).Text = nativeAd.Advertiser;
nativeAdView.AdvertiserView.Hidden = nativeAd.Advertiser == null;
nativeAdView.CallToActionView.UserInteractionEnabled = false;
nativeAdView.NativeAd = nativeAd;
try
{
nativeAdView.BackgroundColor = UIColor.Green;
SetNativeControl(nativeAdView);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
[Export("adLoaderDidFinishLoading:")]
void DidFinishLoading(AdLoader adLoader)
{
// The adLoader has finished loading ads, and a new request can be sent.
}
public void DidFailToReceiveAd(AdLoader adLoader, RequestError error)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Controls.NativeAdView> e)
{
base.OnElementChanged(e);
try
{
if (e.OldElement != null)
{
try
{
e.OldElement.Content=null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
if (e.NewElement != null)
{
if (Control == null)
{
// Instantiate the native control and assign it to the Control property with
CreateAdView();
try
{
e.NewElement.Content = null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
AdLoader adLoader;
private void CreateAdView()
{
//if (Element == null) return;
var multipleAdsOptions = new MultipleAdsAdLoaderOptions { NumberOfAds = 1 };
adLoader = new AdLoader("ca-app-pub-3940256099942544/3986624511", GetVisibleViewController(), new[] { AdLoaderType.UnifiedNative }, new[] { multipleAdsOptions })
{
Delegate = this
};
var request = Request.GetDefaultRequest();
request.TestDevices = new string[] { Request.SimulatorId };
if (nativeAdView == null)
{
nativeAdView = new UnifiedNativeAdView();
};
try
{
adLoader.LoadRequest(request);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
Debug.WriteLine("Loading: " + adLoader.IsLoading);
}
private UIViewController GetVisibleViewController()
{
var windows = UIApplication.SharedApplication.Windows;
foreach (var window in windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
}
Every thing is working as anticipated and I receive the ad and the event DidReceiveUnifiedNativeAd fires but I get an empty ad although when I debug the code I see that the content of the ad is not empty and the control color is green so the control is loaded but why it doesn't show the ad content
Please can anyone help is solving this

Realm/Xamarin.Forms/Android/C#: Data not being saved across runs

I've implemented what I think is a pretty vanilla usage of Realm:
public class MyObj : RealmObject
{
[PrimaryKey]
public string Key { get; set; }
public bool Value { get; set; }
}
then, in my app:
using(Realm r = Realm.GetInstance()) {
var c1 = r.All<MyObj>().Count();
}
which returns zero, as expected.
Then I add an object:
using(Realm r = Realm.GetInstance()) {
r.Write(() =>
{
var obj = new MyObj() { Key = "test", Value = true };
r.Add(obj);
});
}
then reopen it and get the count:
using(r = Realm.GetInstance()) {
var c2 = r.All<MyObj>().Count();
}
and c2 is one, as expected. So far, so good.
But when I close my app, and restart, c1 (the initial count) is zero, not one.
Any idea why?
Sorry,we couldn't see the other code of your app.
But you can refer to an article by entering key words Xamarin.Forms - Working With Realm Database in your browser. It works properly even after restarting the app.
You can also check the full sample here.
The main code is:
public partial class MainPage : ContentPage
{
List<OptionItems> optionItems = new List<OptionItems>();
Student editStudent;
public MainPage()
{
InitializeComponent();
imgBanner.Source = ImageSource.FromResource("XamarinFormsRelam.images.banner.png");
var realmDB = Realm.GetInstance();
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource=studentList;
}
private void btnAdd_Clicked(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
var students= realmDB.All<Student>().ToList();
var maxStudentId = 0;
if (students.Count!=0)
maxStudentId = students.Max(s=>s.StudentID);
Student student = new Student()
{
StudentID = maxStudentId + 1,
StudentName = txtStudentName.Text
};
realmDB.Write(() =>
{
realmDB.Add(student);
});
txtStudentName.Text = string.Empty;
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource = studentList;
}
private async void listOptions_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var realmDB = Realm.GetInstance();
OptionItems selectedItem = optionList.SelectedItem as OptionItems;
if (selectedItem != null)
{
switch (selectedItem.OptionText)
{
case "Edit":
popupOptionView.IsVisible = false;
popupEditView.IsVisible = true;
editStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
txtEditStudentName.Text = editStudent.StudentName;
break;
case "Delete":
var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
using (var db = realmDB.BeginWrite())
{
realmDB.Remove(removeStudent);
db.Commit();
}
await DisplayAlert("Success", "Student Deleted", "OK");
popupOptionView.IsVisible = false;
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource = studentList;
break;
default:
popupOptionView.IsVisible = false;
break;
}
optionList.SelectedItem = null;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
var realmDb = Realm.GetInstance();
}
private void listStudent_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
Student selectedStudent = listStudent.SelectedItem as Student;
if(selectedStudent!=null)
{
optionItems.Add(new OptionItems { OptionText = "Edit",StudentId=selectedStudent.StudentID});
optionItems.Add(new OptionItems { OptionText = "Delete", StudentId = selectedStudent.StudentID });
optionItems.Add(new OptionItems { OptionText = "Cancel"});
optionList.ItemsSource = optionItems;
popupOptionView.IsVisible = true;
}
}
private void Button_Clicked(object sender, EventArgs e)
{
popupEditView.IsVisible = false;
}
private async void Button_Clicked_1(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);
using (var db = realmDB.BeginWrite())
{
editStudent.StudentName = txtEditStudentName.Text;
db.Commit();
}
await DisplayAlert("Success", "Student Updated","OK");
txtEditStudentName.Text = string.Empty;
popupEditView.IsVisible = false;
}
}
Are you deploying on a physical device? If that's the case, it's likely due to the automatic backup and restore functionality built into Android - when you deploy the app, it treats it as an install and restores the last known state.
You can read about it here: An Android app remembers its data after uninstall and reinstall but the tl;dr is - go to settings and turn off "Automatic Restore" or update your manifest to instruct Android not to backup the data.

C# Database not updating using ASP and EF

My database is not updating with new inserted values from text boxes, but when Account page has loaded, autocomplete with current values from DB works.
What did I miss there ?
It is affected from using Owin on Login/SignIn/LogOut form pages ?
Because Owin autogenerated few Tabels in my Database and one of them contains userID and password. But i don't think that should be the problem.
Here is my UserInfoModel class:
public UserInfo GetUserInformation(string uid)
{
FarmacieEntities db = new FarmacieEntities();
UserInfo info = (from x in db.UserInfoes where x.UID == uid select x).FirstOrDefault();
return info;
}
public void InsertUserInfo(UserInfo info)
{
FarmacieEntities db = new FarmacieEntities();
db.UserInfoes.Add(info);
db.SaveChanges();
}
public string UpdateUserInfo(int id, UserInfo userInfo)
{
try
{
FarmacieEntities db = new FarmacieEntities();
UserInfo p = db.UserInfoes.Find(id);
p.Nume = userInfo.Nume;
p.Prenume = userInfo.Prenume;
p.Adresa = userInfo.Adresa;
p.Telefon = userInfo.Telefon;
p.CodPostal = userInfo.CodPostal;
db.SaveChanges();
return p.Nume + " was succesfully updated";
}
catch (Exception e)
{
return "Error:" + e;
}
}
And here is my Page code:
protected void Page_Load(object sender, EventArgs e)
{
string id = User.Identity.GetUserId();
Completare(id);
}
private void Completare(string id)
{
UserInfoModel model = new UserInfoModel();
UserInfo user = model.GetUserInformation(id);
txtNume.Text = user.Nume;
txtPrenume.Text = user.Prenume;
txtAdresa.Text = user.Adresa;
txtTelefon.Text = user.Telefon;
txtcod.Text = user.CodPostal;
}
private int getID(string id)
{
UserInfoModel model = new UserInfoModel();
UserInfo user = model.GetUserInformation(id);
return user.ID;
}
private UserInfo CreateUser()
{
UserInfo user = new UserInfo();
user.Nume = txtNume.Text;
user.Prenume = txtPrenume.Text;
user.Adresa = txtAdresa.Text;
user.Telefon = txtTelefon.Text;
user.CodPostal = txtcod.Text;
return user;
}
protected void Button1_Click(object sender, EventArgs e)
{
UserInfoModel model = new UserInfoModel();
UserInfo user = CreateUser();
model.UpdateUserInfo(getID(User.Identity.GetUserId()), user);
Response.Redirect("~/Pages/Account/Comenzi.aspx");
}
Problem fixed:
At the page load function i forgot to add the 2 lines in this if: if(!IsPostBack).

Best way to override ext.net combobox

I try to find some examples for overriding ext.net combobox. I need to do this, because I want to use default values for most properties. But I have a problem. I could not to find some examples for store, handler, proxy and my own listeners which using in combobox. How can I override it? Can anybody give me some examples?
A C# class example for own combobox. My thanks.
Edit...
public class CombinedComboBox : ComboBox
{
#region Properties
private string _handlerAddress;
private Store _store;
private StoreParameterCollection _storeParameters;
private ModelFieldCollection _modelFields;
private ListenerCollection _listeners;
public string HandlerAddress
{
get { return _handlerAddress; }
set
{
if (!value.StartsWith("/Handlers/"))
_handlerAddress = "/Handlers/" + value;
else
_handlerAddress = value;
}
}
public StoreParameterCollection StoreParameters
{
get { return _storeParameters; }
set { _storeParameters = value; }
}
public ModelFieldCollection ModelFields
{
get { return _modelFields; }
set { _modelFields = value; }
}
#endregion
#region ASP.NET Controls Init & Events
public CombinedComboBox()
{
//Базовые автоматические значения, также можно просадить в Init
HideLabel = false;
DisplayField = "Name";
PageSize = 10;
TypeAhead = true;
LabelWidth = 160;
MinChars = 2;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
BuildStore();
if (!AllowBlank) AfterLabelTextTpl.Html = "<span style=\"color: red; font - weight: bold\" data-qtip=\"Required\">*</span>";
}
private void BuildStore()
{
_store = new Store
{
AutoLoad = false,
RemotePaging = true,
RemoteFilter = true,
IsPagingStore = true,
PageSize = PageSize
};
_store.Proxy.Add(new AjaxProxy
{
Json = true,
ActionMethods = { Read = HttpMethod.GET },
Url = HandlerAddress,
Reader = { new JsonReader { Root = "data", TotalProperty = "total" } }
});
if (_storeParameters != null && _storeParameters.Count > 0)
{
foreach (var item in _storeParameters)
{
_store.Parameters.Add(item);
}
}
_store.AutoLoadParams.Add(new Parameter("start", "0"));
_store.AutoLoadParams.Add(new Parameter("limit", PageSize.ToString()));
Model model = new Model { IDProperty = "Id" };
model.Fields.Add(new ModelField("Id", ModelFieldType.String));
model.Fields.Add(new ModelField("Name", ModelFieldType.String));
if (_modelFields != null && _modelFields.Count > 0)
{
foreach (var item in _modelFields)
{
model.Fields.Add(item);
}
}
_store.Model.Add(model);
Bin.Add(_store);
}
#endregion
}
My WebForm:
<elem:CombinedComboBox
ID="MyId"
runat="server"
EmptyText="Text"
FieldLabel="Text"
HandlerAddress="/Handlers/OrgStructureDirectionsListHandler.ashx">
<StoreParameters>
<ext:StoreParameter Name="DirectionType" Value="SomeDirection" Mode="Value" />
</StoreParameters>
<Listeners>
<Select Fn="ItemSelected"/>
</Listeners>
</elem:CombinedComboBox>
But Handler never called. Why?
Ok, I found a problem. It was because I didn't place ID for my store like this:
protected override void OnPreRender(EventArgs e)
{
StoreID = _store.ClientID;
base.OnPreRender(e);
}

How to transfer selected data(datalist) from one page to another page without using session in asp.net?

I have used two pages. First one is parent page and second one is popup page.
I want to retrieve selected data from popup page to parent page. currently I am using session for it but I want to do it without session.
Popup page Code is as below:
List<vw_ServiceandProduct> lstsapm = new List<vw_ServiceandProduct>();
lstsapm = (from a in db.vw_ServiceandProduct where a.IsActive == true && a.BranchID == Common.BranchID select a).ToList();
Session["lstsapmsession"] = lstsapm;
Parent page Code is as below :
List<vw_ServiceandProduct> lstsapm = Session["lstsapmsession"] as List<vw_ServiceandProduct>;
GridView1.DataSource = lstsapm;
GridView1.DataBind();
Since you mentioned memory usage, I'd recommend using cross page postback (cookie & query string can handle only so many data). With this method you essentially persist your data into view state (which is implemented as hidden field) and use http post method to get around - sending the viewstate along.
Example:
public interface ITransferSomething {
// anything here as long as it is decorated with [Serializable]
IList<vw_ServiceandProduct> SerializableValue { get; }
// exposing standard property of System.Web.UI.Page
bool IsCrossPagePostBack { get; }
}
Default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:LinkButton PostBackUrl="~/Default2.aspx" Text="Transfer!" runat="server" />
</asp:Content>
Default.aspx.cs
public partial class _Default : System.Web.UI.Page, ITransferSomething {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
SerializableValue = new List<vw_ServiceandProduct> {
new vw_ServiceandProduct { Name = "foo" }
};
}
}
public IList<vw_ServiceandProduct> SerializableValue {
get { return (IList<vw_ServiceandProduct>)ViewState["SerializableValue"]; }
set { ViewState["SerializableValue"] = value; }
}
}
Default2.aspx.cs
public partial class Default2 : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
var transfer = Page.PreviousPage as ITransferSomething;
if (transfer != null && transfer.IsCrossPagePostBack) {
SerializableValue = transfer.SerializableValue;
}
}
public IList<vw_ServiceandProduct> SerializableValue {
get { return (IList<vw_ServiceandProduct>)ViewState["SerializableValue"]; }
set { ViewState["SerializableValue"] = value; }
}
}
The method I described in the comment would work like this:
List<vw_ServiceandProduct> lstsapm = new List<vw_ServiceandProduct>();
lstsapm = (from a in db.vw_ServiceandProduct where a.IsActive == true && a.BranchID == Common.BranchID select a).ToList();
//Session["lstsapmsession"] = lstsapm;
string key = Guid.NewGuid().ToString("N");
string path = Server.MapPath("~/App_Data/TempFiles/" + key);
DataContractSerializer dcs = new DataContractSerializer(typeof(List<vw_ServiceandProduct>));
using (var outStream = File.OpenWrite(path))
{
using (XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(outStream, Encoding.UTF8))
{
dcs.WriteObject(xdw, lstsapm);
}
}
// pass key to parent using querystring or cookie
// Parent page Code:
string key = ""; // from cookie or querystring
List<vw_ServiceandProduct> lstsapm = null; //Session["lstsapmsession"] as List<vw_ServiceandProduct>;
string path = Server.MapPath("~/App_Data/TempFiles/" + key);
DataContractSerializer dcs = new DataContractSerializer(typeof(List<vw_ServiceandProduct>));
using (var inStream = File.OpenRead(path))
{
using (XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(inStream, new XmlDictionaryReaderQuotas()))
{
lstsapm = dcs.ReadObject(xdr) as List<vw_ServiceandProduct>;
}
}
if (lstsapm != null)
{
GridView1.DataSource = lstsapm;
GridView1.DataBind();
}

Categories

Resources