is it possible to use MS Excel for all CRUD operations on OData source? - excel

I have the following OData Controller, which provides for all common CRUD operations:
public class ProductsController : ODataController
{
ApplicationDbContext db = new ApplicationDbContext();
private bool ProductExists(int key)
{
return db.Products.Any(p => p.Id == key);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Product> Get()
{
return db.Products;
}
[EnableQuery]
public SingleResult<Product> Get([FromODataUri] int key)
{
IQueryable<Product> result = db.Products.Where(p => p.Id == key);
return SingleResult.Create(result);
}
public async Task<IHttpActionResult> Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await db.Products.FindAsync(key);
if (entity == null)
{
return NotFound();
}
product.Patch(entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != update.Id)
{
return BadRequest();
}
db.Entry(update).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(update);
}
public async Task<IHttpActionResult> Delete([FromODataUri] int key)
{
var product = await db.Products.FindAsync(key);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
}
Is it possible to use MS Excel's OData client capabilities to use Excel as a data management tool to perform addition, deletion, complete and partial updates of the data exposed via my controller?

Related

Session null jsf getExternalContext()

I generate a session in my code but then when using it in another file the session returns null, thx all!
this linux server primefaces,payara 5
public Usuarios loginUsuario(String usuario, String password) {
Usuarios user = null;
try {
UsuariosDAO us = new UsuariosDAO();
user = us.loginUsuario(usuario, password);
if (user != null) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuario", user); // here set user ok! not null
FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
} else {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Atencion!", "User o Password Inconrrectos"));
}
} catch (Exception e) {
System.out.println(e);
}
return user;
}
public void probarSession() {
try {
FacesContext esta = FacesContext.getCurrentInstance();
System.err.println(esta.getExternalContext().getSessionMap().get("usuario")+"this is null!!!");
Usuarios us = (Usuarios) esta.getExternalContext().getSessionMap().get("usuario");
if (us == null) {
esta.getExternalContext().redirect("login.xhtml");
}
} catch (IOException e) {
System.err.println(e);
}
}

How to catch an exception from Azure Mobile App Backend?

In my Azure Mobile App backend, I have a validation for the data in a post method. In certains circunstances, the backend server throw an exception, but, in the app side, I can't get catch this exception. How can I do that?
That's my method
// POST tables/Paciente
public async Task<IHttpActionResult> PostPaciente(Paciente novoPaciente)
{
//other things
if (paciente != null)
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Já existe um paciente com esse token cadastrado.")
};
//throw new HttpResponseException(responseMessage);
return InternalServerError(new Exception("Já existe um paciente com esse token cadastrado."));
}
}
I tried throw HttpResponseException and return InternalServerException, but none works.
You need to check the status code of the response to your http call (there should be a IsSuccesStatusCode property to check).
I recommend using EnsureSuccessStatusCode() which exists in the HttpResponseMessage class. This method will throw an exception if the StatusCode is not OK (or some variant of a 200-level status code).
Below is a generic class, BaseHttpClientServices, that I use for making REST API requests in all of my projects. It follows all of the best practices for using HttpClient like Reusing HttpClient, Deserializing JSON using Stream, and using ConfigureAwait(false).
Sending A Post Request in Xamarin.Forms
public abstract class HttpClientServices : BaseHttpClientServices
{
const string apiUrl = "your api url";
public static void PostPaciente(Paciente novoPaciente)
{
try
{
var response = await PostObjectToAPI(apiUrl, novoPaciente);
response.EnsureSuccessStatusCode();
}
catch(Exception e)
{
//Handle Exception
}
}
}
Generic HttpClient Implementation
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Xamarin.Forms;
namespace NameSpace
{
public abstract class BaseHttpClientService
{
#region Constant Fields
static readonly Lazy<JsonSerializer> _serializerHolder = new Lazy<JsonSerializer>();
static readonly Lazy<HttpClient> _clientHolder = new Lazy<HttpClient>(() => CreateHttpClient(TimeSpan.FromSeconds(60)));
#endregion
#region Fields
static int _networkIndicatorCount = 0;
#endregion
#region Properties
static HttpClient Client => _clientHolder.Value;
static JsonSerializer Serializer => _serializerHolder.Value;
#endregion
#region Methods
protected static async Task<T> GetObjectFromAPI<T>(string apiUrl)
{
using (var responseMessage = await GetObjectFromAPI(apiUrl).ConfigureAwait(false))
return await DeserializeResponse<T>(responseMessage).ConfigureAwait(false);
}
protected static async Task<HttpResponseMessage> GetObjectFromAPI(string apiUrl)
{
try
{
UpdateActivityIndicatorStatus(true);
return await Client.GetAsync(apiUrl).ConfigureAwait(false);
}
catch (Exception e)
{
Report(e);
throw;
}
finally
{
UpdateActivityIndicatorStatus(false);
}
}
protected static async Task<TResponse> PostObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PostObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PostObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(HttpMethod.Post, apiUrl, requestData);
protected static async Task<TResponse> PutObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PutObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PutObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(HttpMethod.Put, apiUrl, requestData);
protected static async Task<TResponse> PatchObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PatchObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PatchObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(new HttpMethod("PATCH"), apiUrl, requestData);
protected static async Task<TResponse> DeleteObjectFromAPI<TResponse>(string apiUrl)
{
using (var responseMessage = await DeleteObjectFromAPI(apiUrl).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> DeleteObjectFromAPI(string apiUrl) => SendAsync<object>(HttpMethod.Delete, apiUrl);
static HttpClient CreateHttpClient(TimeSpan timeout)
{
HttpClient client;
switch (Device.RuntimePlatform)
{
case Device.iOS:
case Device.Android:
client = new HttpClient();
break;
default:
client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip });
break;
}
client.Timeout = timeout;
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
static async Task<HttpResponseMessage> SendAsync<T>(HttpMethod httpMethod, string apiUrl, T requestData = default)
{
using (var httpRequestMessage = await GetHttpRequestMessage(httpMethod, apiUrl, requestData).ConfigureAwait(false))
{
try
{
UpdateActivityIndicatorStatus(true);
return await Client.SendAsync(httpRequestMessage).ConfigureAwait(false);
}
catch (Exception e)
{
Report(e);
throw;
}
finally
{
UpdateActivityIndicatorStatus(false);
}
}
}
static void UpdateActivityIndicatorStatus(bool isActivityIndicatorDisplayed)
{
if (isActivityIndicatorDisplayed)
{
Device.BeginInvokeOnMainThread(() => Application.Current.MainPage.IsBusy = true);
_networkIndicatorCount++;
}
else if (--_networkIndicatorCount <= 0)
{
Device.BeginInvokeOnMainThread(() => Application.Current.MainPage.IsBusy = false);
_networkIndicatorCount = 0;
}
}
static async ValueTask<HttpRequestMessage> GetHttpRequestMessage<T>(HttpMethod method, string apiUrl, T requestData = default)
{
var httpRequestMessage = new HttpRequestMessage(method, apiUrl);
switch (requestData)
{
case T data when data.Equals(default(T)):
break;
case Stream stream:
httpRequestMessage.Content = new StreamContent(stream);
httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
break;
default:
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(requestData)).ConfigureAwait(false);
httpRequestMessage.Content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
break;
}
return httpRequestMessage;
}
static async Task<T> DeserializeResponse<T>(HttpResponseMessage httpResponseMessage)
{
httpResponseMessage.EnsureSuccessStatusCode();
try
{
using (var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var reader = new StreamReader(contentStream))
using (var json = new JsonTextReader(reader))
{
if (json is null)
return default;
return await Task.Run(() => Serializer.Deserialize<T>(json)).ConfigureAwait(false);
}
}
catch (Exception e)
{
Report(e);
throw;
}
}
static void Report(Exception e, [CallerMemberName]string callerMemberName = "") => Debug.WriteLine(e.Message);
#endregion
}
}

Unauthorized exception with SPSecurity.RunWithElevatedPrivileges?

I'm checking, if a given user is part of a group by this code below. I'm getting
unauthorized exception
(0x80070005)
and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}
You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.
So, try and modify the below code as per your requirement :
public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
try
{
bool returnValue = false;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using(SPSite site = new SPSite(web.Site.ID))
{
using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
{
if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
{
SPGroup spGroup = elevatedWeb.Groups[groupName];
if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
{
returnValue = true;
}
else
{
returnValue = false;
}
}
else
{
returnValue = false;
}
}
}
});
return returnValue;
}
catch (Exception exp)
{
Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
return false;
}
}

Unable to use Web API OData v3 feed in Excel

I have a self-hosted Web API OData v3 service:
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
app.UseWebApi(config);
}
}
I also have the following Controller, which exposes a full CRUD:
public class ProductsController : ODataController
{
ApplicationDbContext db = new ApplicationDbContext();
private bool ProductExists(int key)
{
return db.Products.Any(p => p.Id == key);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Product> Get()
{
return db.Products;
}
[EnableQuery]
public SingleResult<Product> Get([FromODataUri] int key)
{
IQueryable<Product> result = db.Products.Where(p => p.Id == key);
return SingleResult.Create(result);
}
public async Task<IHttpActionResult> Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return Created(product);
}
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var entity = await db.Products.FindAsync(key);
if (entity == null)
{
return NotFound();
}
product.Patch(entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != update.Id)
{
return BadRequest();
}
db.Entry(update).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(update);
}
public async Task<IHttpActionResult> Delete([FromODataUri] int key)
{
var product = await db.Products.FindAsync(key);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
}
I am able to access this feed from a browser without any issues.
However, when I try to get Excel 2013 to use this data feed (using this url: http://localhost:8080/Products), I get this error:
"We can't use the data from this feed. Make sure the external data feed server is available and your connection information is correct"
What can I do to make Excel 2013 to work with this data feed?

Database in J2ME

I am new in J2ME.
In my Application, I want to add the Multiple Records in the Record Store and also want to access it.
How can I add the multiple Records in the Record Store and how can I access it?
Here is my library code for RMS, just study it, it is very easy to implement, all the methods like insert,updated, delete is there.
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotOpenException;
import com.project.gui.components.CustomAlert;
import com.project.gui.midlet.MyMidlet;
public class RMSStore
{
private RecordStore rs = null;
public void openRecordStore(String str)
{
try
{
if(rs == null)
{
rs = RecordStore.openRecordStore(str, true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void closeRecordStore()
{
try
{
if(rs!=null)
{
rs.closeRecordStore();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void deleteRecordStore(String storenName)
{
try
{
RecordStore.deleteRecordStore(storenName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void deleteRMS(String storenName)
{
int count = 0;
try
{
RecordStore newRS = RecordStore.openRecordStore(storenName, true);
count = newRS.getNumRecords();
newRS.closeRecordStore();
}
catch ( Exception e )
{
System.out.println ( "Error while Opening " + e.toString() );
}
if ( count > 0 )
{
try
{
RecordStore.deleteRecordStore(storenName);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static String[] listAllRecordStore ()
{
return RecordStore.listRecordStores();
}
public boolean SearchRecord(String Rec)
{
String [] data = getRecordData();
for ( int i = 0 ; i < data.length ; i++ )
{
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
public boolean SearchRecord(String Rec, int pos )
{
String [] data = getRecordData();
Rec = Rec.substring(0,pos);
for ( int i = 0 ; i < data.length ; i++ )
{
data[i] = data[i].substring(0, pos );
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
public int getCurrentRecordID ( RMSStore rmsTable, String Rec )
{
RecordEnumeration re = null;
try
{
re = rmsTable.getRecordEnumData();
while ( re.hasNextElement() )
{
int id = re.nextRecordId();
String record = rmsTable.getRecordFromId(id);
if ( record.indexOf(Rec) != -1 )
{
return id;
}
}
}
catch ( Exception e ) { System.out.println ( "getCurrentRecordID Error:" + e.toString() ); }
return -1;
}
public int writeRecord(String str)
{
int id = 0;
try
{
id = rs.addRecord(str.getBytes(), 0, str.getBytes().length);
}
catch (RecordStoreFullException e)
{
CustomAlert memoryFullAlert = new CustomAlert("");
memoryFullAlert.setString("Memory Full");
MyMidlet.getDisplay().setCurrent(memoryFullAlert);
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public int writeByteRecord(byte[] data)
{
int id = -1;
try
{
id = rs.addRecord(data, 0, data.length);
}
catch (RecordStoreFullException e)
{
e.printStackTrace();
CustomAlert memoryFullAlert = new CustomAlert("");
memoryFullAlert.setString("Memory Full");
MyMidlet.getDisplay().setCurrent(memoryFullAlert);
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public int getRecordCount()
{
try
{
return rs.getNumRecords();
}
catch (Exception e)
{
e.printStackTrace();
}
return 0;
}
public byte[] getRecordDataFromId(int id)
{
byte[] data = null;
try
{
data = rs.getRecord(id);
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}
public String getRecordFromId(int id)
{
return new String(getRecordDataFromId(id));
}
public byte[] getRecordByteFromId(int id)
{
return getRecordDataFromId(id);
}
public void deleteRecord(int id)
{
try
{
rs.deleteRecord(id);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public boolean checkRecordExists(String compare)
{
for(int i = 0; i < getRecordCount(); i++)
{
if(compare.equals(getRecordFromId(i + 1)))
{
return true;
}
}
return false;
}
public int getMaxRMSSize()
{
int size = 0;
try
{
size = rs.getSizeAvailable() + rs.getSize();
}
catch (RecordStoreNotOpenException e)
{
e.printStackTrace();
}
return size;
}
public void setRecordById(String str, int id)
{
try
{
rs.setRecord(id, str.getBytes(), 0, str.getBytes().length);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public int getNextRecordId()
{
int id = 0;
try
{
id = rs.getNextRecordID();
}
catch (Exception e)
{
e.printStackTrace();
}
return id;
}
public RecordEnumeration getRecordEnumData ()
{
try
{
return rs.enumerateRecords(null, null, false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public String [] getRecordData()
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = rs.enumerateRecords(null, null, false);
str = new String[rs.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
RMS is a record based data storage mechanism, so you can store multiple records very easily, see following blog to see how RMS works.
http://www.ibm.com/developerworks/library/wi-rms/

Resources