SharePoint Office365 Signin issue using CSOM - sharepoint-2013

I am trying to connect and retrieve a List from my Office365 sharepoint portal through CSOM. In document.ready function of jquery I am calling an ajax call.
I am using the below code and its working fine.
[WebMethod]
public static List<myClass> GetDataOnPageLoad()
{
List<myClass> objmyClass = new List<myClass>();
string strSiteCollection = "<Site Url>";
string login = "<username>";
string password = "<password>";
SecureString securePassword = new SecureString();
foreach (char c in password)
securePassword.AppendChar(c);
try
{
ClientContext Clientcontext = new ClientContext(strSiteCollection);
Clientcontext.Credentials = new SharePointOnlineCredentials(login, securePassword);
DataTable dtData = new DataTable();
dtData.Columns.Add("ID", typeof(string));
dtData.Columns.Add("UserEmail", typeof(string));
dtData.Columns.Add("InstalledVersion", typeof(string));
if (Clientcontext != null)
{
List docList = Clientcontext.Web.Lists.GetByTitle("<List Name>");
Microsoft.SharePoint.Client.ListItemCollection items = docList.GetItems(CamlQuery.CreateAllItemsQuery());
Clientcontext.Load(items);
Clientcontext.ExecuteQuery();
foreach (var item in items)
dtData.Rows.Add(item["ID"].ToString(), item["UserEmail"].ToString(), item["InstalledVersion"].ToString());
}
if (dtData != null && dtData.Rows.Count > 0)
{
for (int i = 0; i < dtData.Rows.Count; i++)
{
//binding list
}
}
}
catch (Exception ex)
{
}
return objmyClass;
}
All good till now.
Now I in another project I need this same code.
So I copied it and pasted in the new project. Included the sharepoint client dll. Calling this from ajax. Now when I am running this new project it gives an exception from Clientcontext.ExecuteQuery();
Exception says : The partner returned a bad sign-in name or password error. For more information, see Federation Error-handling Scenarios.
I searched for this error but it didn't helped. I'm running the two projects side by side. The old one is running perfectly but the new one is getting the above said error.
Please help. Thanks & Regards.

Related

Integrating ASP.NET Web Api and Android Volley

I'm developing an ASP.NET Web Api project with Entity Framework and other project with Android and the Volley lib.
The idea is the project in ASP.NET to be the server and the Android app the client.
Both projects already work. The ASP.NET project is already connected to SQL Server and returns values in json format from one database, and the client also parses json from an online server that I used for testing when I was following one tutorial.
ASP.NET Web Api Controller:
public class StoreController : ApiController
{
// GET: api/Store
public IEnumerable<bo> Get()
{
using (EGLA_PHCEntities services = new EGLA_PHCEntities())
{
return services.bo.Where(e => e.nmdos == "Ficha Servico 30").Where(e => e.fechada == false).ToList();
}
}
...
}
Android:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(null);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
String firstName = employee.getString("fieldA");
String mail = employee.getString("fieldB");
mTextViewResult.append(firstName + ", " + mail + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
The problem is that my project in ASP.NET does not return a name for the array of objects, and Android is waiting for a name.
The solution can be applied in one side or another. It can go through the ASP.NET project to return a name, or the project in Android to parse the json with an empty array name.
Modified because the list of fields is very extense:
[
{
"fieldA":"Something",
"fieldB":"Store 30",
},
{
"fieldA":"Something 2",
"fieldB":"Store 30 2",
}
]
The error that is returned in the Android app is "org.json.JSONException: No value for null". If I change
JSONArray jsonArray = response.getJSONArray(null);
to:
JSONArray jsonArray = response.getJSONArray("services");
The error returned is: "org.json.JSONException: No value for services"

Want to get the details of the user(member) after login successfully in xamarin forms

my question is how to pass username and password from the C# client(xamarin forms) to server's API? if details are correct then the client will get whole product list from webapi(URL).and bind all the details to a listview.I want to get the member details after the success of response code.
the client will send username password from login page to server's API. if server's webapi check whether the details matched with the database, if not, don't let it get product list.
here is the code in loginservices for login(xamarin forms)
public async Task GetData(string username,string password)
{
//string detail = new UserDetails();
UserDetails userDetails = new UserDetails();
// List<UserDetails> detail = new List<UserDetails>();
try
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("Username", username));
values.Add(new KeyValuePair<string, string>("Password", password));
var content = new FormUrlEncodedContent(values);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("nl-NL"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync("http://192.168.1.50/Accounts/Authenticate", content);
return response.IsSuccessStatusCode;
};
}
catch (Exception ex)
{
throw ex;
}
}
here is the code for web api---
public async Task ValidateUser([FromBody] Credentials credentials)
{
using (DemoAPPEntities entities = new DemoAPPEntities())
{
var result = await entities.MemberDetails.Where(x => x.UserName == credentials.UserName && x.Password == credentials.Password).SingleOrDefaultAsync();
if (result == null)
{
return NotFound();
}
return Ok(entities.MemberDetails);
}
}

write web serice for android with C#

i want write a web service with C# to call from an android app
in my web service i wrote HElloWorld() method to calles and ConvertDataTableTojSonString to converted data to Json i downloaded converting fonction from internet , my probleim is ConvertDataTableTojSonString function it's return me some thing like
"[{\"ProId\":1,\"ProcName\":\"لبنیات\"},{\"ProId\":2,\"ProcName\":\"لوازم بهداشتی\"},{\"ProId\":3,\"ProcName\":\"لوازم آرایشی\"},{\"ProId\":4,\"ProcName\":\"خشکبار\"},{\"ProId\":5,\"ProcName\":\"نوشیدنی ها\"},{\"ProId\":6,\"ProcName\":\"سبزیجات\"},{\"ProId\":7,\"ProcName\":\"فرآورده های گوشتی\"}]"
the json format that return is not recognizable for my android app i dont need that '/' befor and after items .
any body can help me to find an fanction to change my data table to JSON format for use in android app , thank you : )
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HelloWorldData data = new HelloWorldData();
data.Message = ConvertDataTableTojSonString(db.Select("select * from ProCategory ",CommandType.Text));
Context.Response.Write(js.Serialize(data.Message));
}
public String ConvertDataTableTojSonString(DataTable dataTable)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();
Dictionary<String, Object> row;
foreach (DataRow dr in dataTable.Rows)
{
row = new Dictionary<String, Object>();
foreach (DataColumn col in dataTable.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
tableRows.Add(row);
}
return serializer.Serialize(tableRows);
}

CRM 2013: Passing Account Info into Webservice via Plugin

We are using CRM 2013. I'm trying to create a plugin that triggers when a CRM Account is created. Then the plugin will fires and sends an attribute 'AccountNumber' into an internal webservice. However the webservice does not seem to get called whatsoever now.
At first I thought I had to do a PostImage, but then decided not to use it anymore. Also at first I was using "EntityMoniker" as a plugin parameter but then corrected it to type "Target".
Here's my code:
Could someone please guide me in the right direction?
var targetEntity = context.GetParameterCollection<Entity>(context.InputParameters,
"Target");
if (targetEntity == null)
{throw new InvalidPluginExecutionException(OperationStatus.Failed,
"Target Entity cannot be null");}
// Make sure the new Account Id is available
if (!context.OutputParameters.Contains("id"))
{return;}
var accountID = new Guid(context.OutputParameters["id"].ToString());
//putting postImage here but not being used
var postImage = context.PostEntityImages["PostImage"];
if (postImage == null)
{throw new InvalidPluginExecutionException(OperationStatus.Failed,
"Post Image is required");}
var AccountNumber = context.OutputParameters["new_AccountNumber"].ToString();
var service = new ServiceClient("");
var newProp = new PropertySetup
{
_prop = new Property
{
_propertyNm = AccountNumber
}
};
service.CreateNewProperty(newProp);
service.Close();
To get the new_AccountNumber attribute change:
var AccountNumber = context.OutputParameters["new_AccountNumber"].ToString();
to
var AccountNumber = targetEntity.Attributes["new_AccountNumber"].ToString();

publish related media items in Sitecore 6.5 without using workflow

Our client wants to automatically publish related media items when publishing a page. They're not using workflow which would have made things simpler, so I need to find another way. At the moment I've created a custom publish pipeline processor (as shown in this blog post) where I've enabled History storage for the web database and get the list of changed items from there. When looping through the changed items I'm checking for any related media items and publish them.
This works fine, but I just wanted to check if there's any pitfalls to watch out for or if there is a better way of doing this. Anyone have any ideas?
The best way without using workflow is to replace the AddItemReferences processor in the PublishItem workflow. There you can add what types of items will be published along with the original item.
Here is a blog post Alex Shyba about it.
Here is my local implementation
public class AddItemReferences : Sitecore.Publishing.Pipelines.PublishItem.AddItemReferences
{
private readonly static ILogger _logger = AppLogger.GetNamedLogger(typeof(AddItemReferences));
protected override List<Item> GetItemReferences(PublishItemContext context)
{
Assert.ArgumentNotNull(context, "context");
var list = new List<Item>();
// calling base method which processes links from FileDropArea field
list.AddRange(base.GetItemReferences(context));
// adding our "own" related items
list.AddRange(GetRelatedReferences(context));
return list;
}
protected virtual List<Item> GetRelatedReferences(PublishItemContext context)
{
Assert.ArgumentNotNull(context, "context");
var relatedReferenceList = new List<Item>();
if (context.PublishOptions.Mode == PublishMode.SingleItem )
{
try
{
var sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
if (sourceItem.Paths.IsContentItem)
{
var itemLinks = sourceItem.Links.GetValidLinks();
ItemLink[] referers = Globals.LinkDatabase.GetReferers(sourceItem);
relatedReferenceList.AddRange(GetMediaItems(itemLinks));
relatedReferenceList.AddRange(GetAliases(referers));
}
}
catch (Exception ex)
{
var options = context.PublishOptions;
StringBuilder msg = new StringBuilder();
msg.AppendLine("Publishing options");
msg.AppendLine("Deep: " + options.Deep);
msg.AppendLine("From date: " + options.FromDate);
msg.AppendLine("Language: " + options.Language);
msg.AppendLine("Mode: " + options.Mode);
msg.AppendLine("PublishDate: " + options.PublishDate);
msg.AppendLine("Targets: " + string.Join(",",options.PublishingTargets.ToArray()));
msg.AppendLine("Republish all: " + options.RepublishAll);
msg.AppendLine("Root item: " + options.RootItem);
msg.AppendLine("Source database: " + options.SourceDatabase.Name);
_logger.LogError(msg.ToString(), ex);
}
}
return relatedReferenceList;
}
private static IEnumerable<Item> GetMediaItems(ItemLink[] itemLinks)
{
foreach (var link in itemLinks)
{
var item = link.GetTargetItem();
if (item == null)
continue;
if (item.Paths.IsMediaItem)
{
yield return item;
}
}
}
private static IEnumerable<Item> GetAliases(ItemLink[] referrers)
{
foreach (var link in referrers)
{
var item = link.GetSourceItem();
if (item != null && IsAlias(item))
yield return item;
}
}
private static bool IsAlias(Item item)
{
return item.TemplateID.Guid == DataAccessSettings.Templates.AliasTemplateId;
}
}
Input for risk areas:
Missing entries in History storage if editing session is above 30 days prior to publish
Finding related media items involves both link fields and also rich text fields, there can be possible direct links to media, these could be handled and transformed to correctly formatted links.
Alternative solutions
Depending on the Sitecore maturity of your editors another user model could be that you autopublish the media Items from the Save Pipeline. For some users this is easier to understand, since the publishing model is then restricted to handling page visibility.