Error creating an instance of a proxy class - web-services

This is the error:
The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception.
This error ocurs when I try to instance my proxy class
namespace TesteWebService
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPdv_Click(object sender, EventArgs e)
{
SuporteTecnicoClientProxy proxy = new SuporteTecnicoClientProxy();=> **Here error**
try
{
TPDV pdv = proxy.getCnpjParceiro(txtCnpj.Text);
lblRazao.Text = pdv.RazaoSocial;
lblEndereco.Text = pdv.Endereco;
}
catch (Exception ex)
{ }
finally
{ }
}
}
}
My proxy class
namespace TesteWebService
{
class SuporteTecnicoClientProxy : ClientBase<ISuporteTecnicoContract>, ISuporteTecnicoContract
{
public TPDV getCnpjParceiro(string _cnpj)
{
return this.Channel.getCnpjParceiro(_cnpj);
}
}
}
My Interface
[ServiceContract]
public interface ISuporteTecnicoContract
{
[OperationContract]
[WebGet(UriTemplate = "/{_cnpj}")]
TPDV getCnpjParceiro(string _cnpj);
}
My App.Config
<client>
<endpoint adress="http://localhost:4600/SuporteTecnicoService.svc" binding="webHttpBinding" contract="V99SuporteTecnicoContracts.ISuporteTecnicoContract"
behaviorConfiguration="WebBehavior">
</endpoint>
</client>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
What is really going to generate the exception mentioned above. My Interface is other projet. A Class Library Project. So, I have 2 projects. A WCF project(Web Service) and my contract project(POCO class and Interface). This last project Class Library.

Related

Custom Provider for AWS SSM using Microsoft.Configuration.ConfigurationBuilders

I seem to be stuck at developing a custom Key/Value pair provider for Amazon's System Manager Parameter Store (SSM) using NETFramework 4.7.1 that utilizes Microsoft.Configuration.ConfigurationBuilders.
The implementation:
using System;
using System.Collections.Generic;
using Amazon.SimpleSystemsManagement;
using Amazon.SimpleSystemsManagement.Model;
using Microsoft.Configuration.ConfigurationBuilders;
using System.Linq;
using System.Diagnostics;
using System.Collections.Specialized;
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using System.Configuration;
using System.Threading.Tasks;
namespace AXS.Configurations
{
public class ParameterStoreConfigBuilder : KeyValueConfigBuilder
{
public const string envTag = "Environment";
public const string appNameTag = "AppName";
private IAmazonSimpleSystemsManagement client;
/// <summary>
/// Gets or sets an environment (dev|qa|staging|production)
/// </summary>
public string Environment { get; set; }
/// <summary>
/// Gets or sets a AppName
/// </summary>
public string AppName { get; set; }
public ParameterStoreConfigBuilder(IAmazonSimpleSystemsManagement client,
string appName,
string environment)
{
this.client = client;
Environment = environment.ToLower();
AppName = appName;
}
public ParameterStoreConfigBuilder()
{
client = new AmazonSimpleSystemsManagementClient();
}
public override string Description => "Parameter Store";
public override string Name => "SSM";
protected override void LazyInitialize(string name, NameValueCollection config)
{
Optional = false;
base.LazyInitialize(name, config);
string env = UpdateConfigSettingWithAppSettings(envTag);
if (string.IsNullOrWhiteSpace(env))
throw new ArgumentException($"environment must be specified with the '{envTag}' attribute.");
Environment = env;
string appName = UpdateConfigSettingWithAppSettings(appNameTag);
if (string.IsNullOrWhiteSpace(appName))
throw new ArgumentException($"appName must be specified with the '{appNameTag}' attribute.");
AppName = appName;
client = new AmazonSimpleSystemsManagementClient("","", Amazon.RegionEndpoint.USWest2);
}
public override ICollection<KeyValuePair<string, string>> GetAllValues(string prefix)
{
Trace.TraceInformation($"return values prefix {prefix}");
if (client == null)
return null;
var parameters = new List<Parameter>();
string nextToken = null;
do
{
var response = client.GetParametersByPath(new GetParametersByPathRequest { Path = prefix, Recursive = true, WithDecryption = true, NextToken = nextToken });
nextToken = response.NextToken;
parameters.AddRange(response.Parameters);
} while (!string.IsNullOrEmpty(nextToken));
return parameters.Select(p => new
{
Key = p.Name,
p.Value
}).ToDictionary(parameter => parameter.Key, parameter => parameter.Value, StringComparer.OrdinalIgnoreCase);
}
public override string GetValue(string key)
{
return Task.Run(async () => { return await GetValueAsync(key); }).Result;
}
private async Task<string> GetValueAsync(string key)
{
var name = $"/{Environment}/{AppName}/{key.Replace(':', '/')}";
Trace.WriteLine($"get value async:{name}");
if (client == null)
return null;
try
{
Trace.TraceInformation($"fetch key {name}");
var request = new GetParameterRequest
{
Name = name,
WithDecryption = true
};
var response = await client.GetParameterAsync(request);
var parameter = response.Parameter;
var value = parameter.Type == ParameterType.SecureString ? "*****" : parameter.Value;
Trace.TraceInformation($"fetched name={name} value={value}");
return value;
}
catch (Exception e) when (Optional && ((e.InnerException is System.Net.Http.HttpRequestException) || (e.InnerException is UnauthorizedAccessException))) { }
return null;
}
}
}
The problem seems to be that AWS SSM client never gets created.
If I change the code and try to instantiate in the constructor I get a stack overflow exception due to recursion.
Any ideas on how to force to get AmazonSimpleSystemsManagementClient created?
The code uses guidance from https://github.com/aspnet/MicrosoftConfigurationBuilders
The App.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false"
requirePermission="true" />
</configSections>
<configBuilders>
<builders>
<add name="ParameterStore" Environment="development" AppName="myAppNameforParmStore" type="AXS.Configurations.ParameterStoreConfigBuilder, AXS.Configurations" />
<add name="Env" prefix="appsettings_" stripPrefix="true" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment, Version=2.0.0.0, Culture=neutral" />
</builders>
</configBuilders>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />
</startup>
<appSettings configBuilders="Env,ParameterStore">
<add key="Url" value="URL Value for from paramter Store" />
<add key="Secret" value="Some Secret value decrypted" />
</appSettings>
</configuration>
Thanks
UPDATE
I posted an updated version of the AwsSsmConfigurationBuilder, and a sample ASP.NET Web Forms project that uses it, on my GitHub:
https://github.com/Kirkaiya/AwsSsmConfigBuilderPoC/
Disclaimer: This is a proof-of-concept (POC) for a custom ConfigurationBuilder for ASP.NET 4.7.1 or higher (running on .NET Framework obviously). It's a POC, so it doesn't do anything besides allow you store Configuration AppSettings in AWS Parameter Store (a feature of Simple Systems Manager). So, clearly, don't use this in production without productizing and testing it!
Prerequisites:
Your project must target .NET Framework 4.7.1 or higher
Include NuGet package Microsoft.Configuration.ConfigurationBuilders.Base
Have parameters in AWS SSM Parameter Store that have the same name (not counting the prefix) as parameters in your web.config file, and vice-versa.
Notes
In order to avoid recursively calling a concrete constructor or Initialize, I used a static constructor to instantiate the AmazonSimpleSystemsManagementClient, which is held in a static member.
Web.Config additions
Note: change the assembly/class-name of your builder to match yours, etc.
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="ParameterStore" ssmPrefix="/padnugapp/ApiKeys" type="Microsoft.Configuration.ConfigurationBuilders.AwsSsmConfigBuilder, AspNetWebFormsSample" />
</builders>
</configBuilders>
<appSettings configBuilders="ParameterStore">
<add key="TestKey" value="TestKey Value from web.config" />
<add key="TwitterKey" value="TwitterKey value from web.config" />
</appSettings>
And the AwsSsmConfigBuilder.cs file:
namespace Microsoft.Configuration.ConfigurationBuilders
{
public class AwsSsmConfigBuilder : KeyValueConfigBuilder
{
private string BaseParameterPath = "/padnugapp/ApiKeys";
private static IAmazonSimpleSystemsManagement _client;
static AwsSsmConfigBuilder()
{
_client = new AmazonSimpleSystemsManagementClient();
}
public override void Initialize(string name, NameValueCollection config)
{
base.Initialize(name, config);
if (config["ssmPrefix"] == null)
return;
BaseParameterPath = config["ssmPrefix"];
}
public override ICollection<KeyValuePair<string, string>> GetAllValues(string prefix)
{
if (_client == null)
return null;
var request = new GetParametersByPathRequest
{
Path = $"{BaseParameterPath}/{prefix}",
WithDecryption = true,
};
var response = _client.GetParametersByPathAsync(request).Result;
var result = response.Parameters.ToDictionary(param => param.Name, param => param.Value, StringComparer.OrdinalIgnoreCase);
return result;
}
public override string GetValue(string key)
{
if (_client == null)
return null;
var request = new GetParameterRequest
{
Name = $"{BaseParameterPath}/{key}",
WithDecryption = true,
};
var response = _client.GetParameterAsync(request).Result;
return response.Parameter.Value;
}
}
}
The code I put into a web-forms (.aspx) page that renders the two appSettings items in HTML:
TestKey =
<%=(System.Configuration.ConfigurationManager.AppSettings["TestKey"]) %>
<br />
TwitterKey =
<%=(System.Configuration.ConfigurationManager.AppSettings["TwitterKey"]) %>
I can't stress enough that this is just for a demo I'm doing, and not tested in any way, shape or form except on my laptop ;-)

500 Custom Error Pages

I want to implement 500 error page for multi-sites/multi-languages, i am following this article.
But Application_Error in Global.asax is not firing. Here is my code:
<%# Application Language='C#' Inherits="Sitecore.ContentSearch.SolrProvider.CastleWindsorIntegration.WindsorApplication" %>
<script RunAt="server">
private void Application_Error(object sender, EventArgs e)
{
var customErrorsSection = (System.Web.Configuration.CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors");
var lastException = Server.GetLastError();
if (customErrorsSection.Mode != System.Web.Configuration.CustomErrorsMode.Off)
{
try
{
// Log.Error( "There was an error in the application", lastException);
Server.ClearError();
HttpContext.Current.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
Server.Transfer(string.Format("/Error/{0}_500.html", GetSafeLanguage()));
}
catch
{
}
}
}
private string GetSafeLanguage()
{
try
{
return Sitecore.Context.Language.CultureInfo.TwoLetterISOLanguageName;
}
catch
{
}
return string.Empty;
}
</script>
Since I am using SOLR, It needs WindsorApplication in Global.asax and this class not inherited from System.Web.HttpApplication, i follow these links to handle 500 page error :
https://sitecorecommerce.wordpress.com/2015/10/15/500-error-page-in-your-sitecore-application/
http://www.partechit.nl/en/blog/2014/01/sitecore-mvc-applications-and-the-application-error-event
Connfiguation :
<pipelines>
<mvc.exception>
<processor type="Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage, Sitecore.Mvc">
<patch:attribute name="type">MyWebsite.Web.Pipelines.HandleMvcException, MyWebsite.Web</patch:attribute>
</processor>
</mvc.exception>
</pipelines>
My Class
public class HandleMvcException : ExceptionProcessor
{
public override void Process(ExceptionArgs args)
{
var customErrorsSection = (CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors");
var context = args.ExceptionContext;
var httpContext = context.HttpContext;
var exception = context.Exception;
if (customErrorsSection.Mode != CustomErrorsMode.Off)
{
if (context.ExceptionHandled || httpContext == null || exception == null)
{
return;
}
// Create a report with exception details.
string exceptionInfo = this.GetExceptionInfo(httpContext, exception);
// Store the report in a session variable so we can access it from the custom error page.
Log.Error(string.Format("There was an error in {0} : {1}", Sitecore.Context.Site.Name, exceptionInfo),this);
// Return a 500 status code and execute the custom error page.
httpContext.Server.ClearError();
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
httpContext.Server.Execute((Sitecore.Context.Site.ErrorPage(GetSafeLanguage())));
}
}
private string GetExceptionInfo(HttpContextBase httpContext, Exception exception)
{
// Generate an error report.
var errorInfo = new StringBuilder();
errorInfo.AppendLine(string.Concat("URL: ", httpContext.Request.Url));
/* Snipped additional lines of report generation */
errorInfo.AppendLine(string.Concat("Source: ", exception.Source));
errorInfo.AppendLine(string.Concat("Message: ", exception.Message));
errorInfo.AppendLine(string.Concat("Stacktrace: ", exception.StackTrace));
return errorInfo.ToString();
}
private string GetSafeLanguage()
{
try
{
return Sitecore.Context.Language.CultureInfo.TwoLetterISOLanguageName;
}
catch
{
}
return string.Empty;
}
}
and in site definition i added custom attribute for error page :
<site name="mywebsite" patch:before="site[#name='website']" xdt:Transform="Replace" xdt:Locator="Match(name)"
hostName ="mywebsite.local"
virtualFolder="/"
physicalFolder="/"
rootPath="/sitecore/content/mywebsite"
startItem="/home"
database="web"
domain="extranet"
allowDebug="true"
cacheHtml="true"
htmlCacheSize="50MB"
enablePreview="true"
enableWebEdit="true"
enableDebugger="true"
disableClientData="false"
errorPage="/assets/error/mywebsite/{0}_500.html"/>
and I created extended method to read the errorPage attribute :
public static class SiteExtension
{
/// <summary>
/// Retrun the site unique ID
/// </summary>
/// <returns></returns>
public static string ErrorPage(this SiteContext site, string language)
{
try
{
string errorPage = site.Properties["errorPage"];
if (!String.IsNullOrEmpty(errorPage))
return string.Format(errorPage, language);
else
return string.Empty;
}
catch (Exception)
{
return string.Empty;
}
}
}

Can not find the right WCF endpoint configuration

I created service that take the data from android and save them into SQL. I am using IIS 7
My code:
namespace WcfService_SuiviColis
{
// REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom d'interface "IService1" à la fois dans le code et le fichier de configuration.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat= WebMessageFormat.Json, BodyStyle =WebMessageBodyStyle.Wrapped, UriTemplate = "SaveData")]
void SaveData(Pers_Ordre_NET oData);
}
[DataContract]
public class Pers_Ordre_NET
{
[DataMember]
string _CodeClient;
public string CodeClient
{
get { return _CodeClient; }
set { _CodeClient = value; }
}
[DataMember]
string _CodeDest;
public string CodeDest
{
get { return _CodeDest; }
set { _CodeDest = value; }
}
[DataMember]
string _NoOrdre;
public string NoOrdre
{
get { return _NoOrdre; }
set { _NoOrdre = value; }
}
[DataMember]
string _DateTampon;
public string DateTampon
{
get { return _DateTampon; }
set { _DateTampon = value; }
}
[DataMember]
string _GeoPos;
public string GeoPos
{
get { return _GeoPos; }
set { _GeoPos = value; }
}
[DataMember]
string _StsOrdre;
public string StsOrdre
{
get { return _StsOrdre; }
set { _StsOrdre = value; }
}
[DataMember]
string _Camion;
public string Camion
{
get { return _Camion; }
set { _Camion = value; }
}
}
}
and service.svc.cs:
namespace WcfService_SuiviColis
{
// REMARQUE : vous pouvez utiliser la commande Renommer du menu Refactoriser pour changer le nom de classe "Service1" dans le code, le fichier svc et le fichier de configuration.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public void SaveData(Pers_Ordre_NET oOrdre)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
string sql_Adding = "INSERT INTO [SUIVI_ORDRE]"+
" ([CODE_CLIENT] ,[CODE_DEST],[NO_ORDRE],[DATE_TAMPON],[GPS_POS],[STATUS_ORDRE],CAMION)"+
"VALUES (#CODE_CLIENT,#CODE_DEST,#NO_ORDRE,#DATE_TAMPON,#GPS_POS,#STATUS_ORDRE,#CAMION)";
SqlCommand comm_Insrt = new SqlCommand(sql_Adding, connectionWrapper.conn);
comm_Insrt.Parameters.AddWithValue("#CODE_CLIENT", oOrdre.CodeClient);
comm_Insrt.Parameters.AddWithValue("#CODE_DEST", oOrdre.CodeDest);
comm_Insrt.Parameters.AddWithValue("#NO_ORDRE", oOrdre.NoOrdre);
comm_Insrt.Parameters.AddWithValue("#DATE_TAMPON", oOrdre.DateTampon);
comm_Insrt.Parameters.AddWithValue("#GPS_POS", oOrdre.GeoPos);
comm_Insrt.Parameters.AddWithValue("#STATUS_ORDRE", oOrdre.StsOrdre);
comm_Insrt.Parameters.AddWithValue("#CAMION", oOrdre.Camion);
comm_Insrt.ExecuteNonQuery();
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
}
}
and web.config:
<system.serviceModel>
<services>
<service name="WcfService_SuiviColis.Service1" behaviorConfiguration="ServiceBehaviour">
<endpoint
address="SaveData"
behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
</system.serviceModel>
<system.webServer>
<security>
<requestFiltering>
<verbs>
<add verb="POST" allowed="true"/>
</verbs>
<fileExtensions>
<add fileExtension=".svc" allowed="true"/>
</fileExtensions>
</requestFiltering>
</security>
<directoryBrowse enabled="true"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
I can not find the right configuration for the endpoint.
When I write like this:
<endpoint
address="SaveData" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
I got endpoint not found
When I write it like this:
<endpoint
address="" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
I got method not allowed
When I write like this:
<endpoint
address=""
binding="basicHttpBinding"
contract="WcfService_SuiviColis.IService1" />
I got error 415, type mismatch because I want to receive JSON but in fiddler I got html
I put also Factory="System.ServiceModel.Activation.WebServiceHostFactory"
When I put
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
I got error 400 page not found
I call my method like this:
http://mydomain:4004/Code/WcfService_SuiviColis/WcfService_SuiviColis/Service1.svc/SaveData
EDITED
i think the correct endpoint :
<endpoint
address="" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
but with this endpoint i got error 405, mmethode not allowed. is posible that IIS 7 not allowed POST (receive the data from ANDROID to SERVER) ?
because i have created another wcf programm with GET (send the data from SERVER to ANDROID) it work fine.
At first glance the address of the endpoint you are defining is not valid. It should contain the full address of the machine where the service is located along with the port number
<endpoint address ="http://mydomain:4004/...../>
Since you're using IIS, the web URL to use is basically defined by IIS: your server name, name of the virtual directory, path and location of the *.svc file.
http://YourWebServer/VirtualDirectory/Path/service.svc
Then, you might have an additional, relative address in your endpoint definition, so if you use
<endpoint
address="SaveData" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfService_SuiviColis.IService1" />
then the complete URL would be:
http://YourWebServer/VirtualDirectory/Path/service.svc/SaveData
I'm not sure if you might need to add another /SaveData to that URL since you've defined this as your UriTemplate on the service contract:
http://YourWebServer/VirtualDirectory/Path/service.svc/SaveData/SaveData
++++++++ ********
| |
relative address |
from endpoint |
|
UriTemplate from your service contract
Endpoint not found usually means you're using a wrong URL to try and access your service.

How to Return list of bytes from webservice

I want to retrieve list of images from database that are stored in the form of bytes.I am able to return only single images bytes length.How can i send list of bytes .i am using below code please let me know
public List<Byte[]> GetAllProjectStandardIcons()
{
var qry = (from p in dbModel.tbl_STANDARDPROJECTICONS
select new
{
p.ProjectIcons
}).ToList();
//How to return list here from WCF web service
}
I have tried to create a service with an Image Service that returns images from the images stored in the same folder as the service. You can the streaming later if you want.
[ServiceContract]
public interface IImagesService
{
[OperationContract]
List<Byte[]> FetchImages();
}
public class ImagesService : IImagesService
{
List<string> images = new List<string>();
public ImagesService()
{
images.Add("Box.png");
images.Add("Clock.png");
}
public List<byte[]> FetchImages()
{
List<Byte[]> imagesInBytes = new List<byte[]>();
foreach (var image in images)
{
Image newImage = new Bitmap(image);
byte[] b = this.imageToByteArray(newImage);
imagesInBytes.Add(b);
}
return imagesInBytes;
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
Hosted the service on httpbinding
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior0">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WCFImagesExample.ImagesService" behaviorConfiguration="NewBehavior0">
<endpoint address="Images" binding="basicHttpBinding" bindingConfiguration=""
contract="WCFImagesExample.IImagesService" />
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:{portnumber}" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
Now you can create a client proxy and save the images back
static void Main(string[] args)
{
ImagesReference.IImagesService imagesService = new ImagesServiceClient();
byte[][] bytes = imagesService.FetchImages();
int i=0;
foreach (byte[] byteArray in bytes)
{
Image image = byteArrayToImage(byteArray);
image.Save(#"c:\Development\" + i + ".png");
i++;
}
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Highly like you want to return an image. No matter what you can have a look at the following:Large Data and Streaming

Google Glass Live Card not inserting

Glass GDK here. Trying to insert a livecard using remote views from service. I'm launching service via voice invocation. The voice command works, however it appears my service is not starting(no entries in log). Service is in android manifest. Below is code:
public class PatientLiveCardService extends Service {
private static final String LIVE_CARD_ID = "timer";
#Override
public void onCreate() {
Log.warn("oncreate");
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
publishCard(this);
return START_STICKY;
}
#Override
public void onDestroy() {
unpublishCard(this);
super.onDestroy();
}
private void publishCard(Context context) {
Log.info("inserting live card");
if (mLiveCard == null) {
String cardId = "my_card";
TimelineManager tm = TimelineManager.from(context);
mLiveCard = tm.getLiveCard(cardId);
mLiveCard.setViews(new RemoteViews(context.getPackageName(),
R.layout.activity_vitals));
Intent intent = new Intent(context, MyActivity.class);
mLiveCard.setAction(PendingIntent
.getActivity(context, 0, intent, 0));
mLiveCard.publish();
} else {
// Card is already published.
return;
}
}
private void unpublishCard(Context context) {
if (mLiveCard != null) {
mLiveCard.unpublish();
mLiveCard = null;
}
}
}
Here is AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO" >
</uses-permission>
<application
android:name="com.myApp"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.myApp.MyActivity"
android:label="#string/app_name"
android:screenOrientation="landscape" >
</activity>
<service android:name="com.myApp.services.MyService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
</intent-filter>
<meta-data
android:name="com.google.android.glass.VoiceTrigger"
android:resource="#xml/voice_trigger_get_patient" />
</service>
</application>
This is a bug with XE11: the service is not started after the speech recognizer is complete.
As a workaround, you can have your voice trigger start an Activity which:
Processes the recognized speech in onResume.
Once the speech is processed, starts your Service with startService.
Calls finish to jump to the published LiveCard.