Tips and Tricks in a world of Mix

Archive for the ‘C#’ Category

Image

Getting images byte[] from MS SQLServer through WCF to Ionic3 Angular4

So , that was quite a challenge.

After saving the images as byte[] pretty neat through the MVC client into the MS SqlServer , I wanted to get them into the app of Ionic3 with Angular4 ..

 

The problem was –

Well there were several problems –

  1. How to return the data through the http without loosing data in “translation” on the way ?

Solution is in C# WCF before returning it convert to base64 – it will send the data intact through the www traffic.

dto.Logo = Convert.ToBase64String(dal.Logo);

       2.   When we get the data – we need to translate it into the image again :

this post helped me –  Search for the comment with 400 upvotes!

So, in my ts client side – my Ionic3 Angular4 baby ,  I added a function translating the byte[] into a Blob.

Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn’t necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user’s system.

b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || ”;
sliceSize = sliceSize || 512;

let byteCharacters = atob(b64Data);
let byteArrays = [];

for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);

let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

let byteArray = new Uint8Array(byteNumbers);

byteArrays.push(byteArray);
}

let blob = new Blob(byteArrays, {type: contentType});
return blob;
}

3. Now I started getting those messages from Chrome 

unsafe:blob:http://localhost:8100/55df97ad-0b55-4724-8a4f-83861b87e60a:1 GET unsafe:blob:http://localhost:8100/55df97ad-0b55-4724-8a4f-83861b87e60a net::ERR_UNKNOWN_URL_SCHEME

 

So I’ve built a pipe as suggested here  in compbination with the DomSanitation suggested here :

So at last I have taken this solution :

import { Pipe } from ‘@angular/core’;

import { Pipe } from ‘@angular/core’;

import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from ‘@angular/platform-browser’;
@Pipe({ name: ‘safe’})

export class SafePipe {
constructor(protected _sanitizer: DomSanitizer) {
}
public transform(value: string, type: string = ‘html’): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {

switch (type) {

case ‘html’: return this._sanitizer.bypassSecurityTrustHtml(value);

case ‘style’: return this._sanitizer.bypassSecurityTrustStyle(value);

case ‘script’: return this._sanitizer.bypassSecurityTrustScript(value);

case ‘url’: return this._sanitizer.bypassSecurityTrustUrl(value);

case ‘resourceUrl’:

return this._sanitizer.bypassSecurityTrustResourceUrl(value);

default: throw new Error(`Invalid safe type specified: ${type}`);

}

}
}

 

Added it to declarations in your app.module.ts with class name SafePipe .
And added the pipe on the html template
<img [src]=”company.LogoImage | safe: ‘resourceUrl'”>
And here I am – after two days without sleep I have images from the server side in my app..
   WiseAppSettings.JPG
Now it’s just about vise-versa – trying to upload those slippery brothers  🙂
Advertisements

Init async data in db for tests–simple example

When you need a test running during your process to insert data you may want to use task for async insertion.

Also you may run it parallel to your process from outside.

If you want to be able to stop you should implement Cancellation Token and put it inside the process as a stop condition for a while loop.

 


namespace AsyncTest
{
 public class InitTestPerSecond{
 public Task initData;
 public InitTestPerSecond()
 {
 initData = new Task()(
 ()=>
 {
 while(true)
 {
 MyDAL.InsertInTableEachSecond(DateTime.Now);
 Thread.Sleep(1000);
 }
 });
 initData.Start();
 }
}
 
namespace MyDAL
{
 public class MyDAL{
 public static void InsertInTableEachSecond(DateTime timestamp)
 {
 try{
 OracleConnection localConn = new OracleConnection(Utils.GetConnectionString());
 localConn.Open();
 int maxId;
 using (OracleCommand maxIdCommand = new OracleCommand("SELECT MAX(MYID) FROM SCHEMA_NAME.MYTABLE", localConn))
 {
 maxId = int.Parse(maxIdCommand.ExecuteScalar().ToString());
 }
 using (OracleCommand initMyData = localConn.CreateCommand())
 {
 
 initMyData = string.Format(" INSERT INTO SCHEMA_NAME.MYTABLE (MYID , COL1, DATE)
 VALUES 
 ({0}, 
 '{0} test ' ,
 {1})", ++maxId ,Utils.GetDateFormat(timeStamp) ));
 
 initMyData.ExecuteNonQuery();
 }
 localConn.Close();
 localConn.Dispose();
 }
 catch(Exception ex){
 throw ex;
 }
 }
 
 }
 
}
 
public class Utils{
 
 public static string GetDateFormat(DateTime date){
 return string.Format(@"TO_DATE('{0}', 'MM/DD/YYYY HH24:MI:SS')", date.ToString("MM/dd/YYYY HH:mm:ss"));
 }
 
 public static string GetConnectionString()
 {
 return ConnectionStringHandler.ConnectionString;
 }
} 
 
 
public static class ConnectionStringHandler
{
 public static string ConnectionString= String.Empty;
 static ConnectionStringHandler()
 {
 Decrypt();
 ConnectionString = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
 Encrypt();
 }
}


Remove Special Charachters \n\r CR LF from data PL / SQL Oracle and .Net

In ORACLE

SELECT REPLACE(REPLACE(YourColumn,CHAR(13),NULL),CHAR(10),NULL)
FROM YourTable


FOR ONE CHAR :
SELECT replace(YourColumn,CHAR(13),'')
FROM YourTable

OR
update YourTable
set YourColumn =replace(YourColumn,CHAR(13),'')

IN .NET 
MyString.Replace("\r\n","")   

or..

MyString.Replace("\r\n",@"\n")

Potential Blacklist
Special control chars 0-31 by Unicode must be handled
White list 
[^a-zA-Zא-ת0-9._] -and punctuation chars by your choice
- this is a start of a regex pattern - [^] -everything that not in the pattern is not allowed.
also can do 
[^\w\s\p{IsHebrew}\p{P}] - not taking accesnt chars like ~^ , not finished , but a start

better handled by StringBuilder with loop through chars than Regex 
(more than 10 times better).just Whitelist of allowed chars and if in range 
like this 

if(c>=a && c<=z)...
  sb.append(c)
else
  sb.append(' '); //replacement char
 

Yield & readonly

Yield interacts with the foreach-loop. It is a contextual keyword: yield is a keyword only in certain statements. It allows each iteration in a foreach-loop be generated only when needed. In this way it can improve performance.

The nice things about using yield return is that it’s a very quick way of implementing the iterator pattern, so things are evaluated lazly.

Iterator pattern provides a way to traverse (iterate) over a collection of items without detailing the underlying structure of the collection.

 

 

readonly The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

If you use a const in dll A and dll B references that const, the value of that const will be compiled into dll B. If you redeploy dll A with a new value for that const, dll B will still be using the original value.

If you use a readonly in dll A and dll B references that readonly, that readonly will always be looked up at runtime. This means if you redeploy dll A with a new value for that readonly, dll B will use that new value.

http://stackoverflow.com/questions/277010/what-are-the-benefits-to-marking-a-field-as-readonly-in-c/312840#312840

http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

Tag Cloud

%d bloggers like this: