2018년 1월 18일 목요일
C# - MSSQL CLR (AES256 암호화)
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
public partial class CryptoHelper
{
/// <summary>
/// AesManaged 생성
/// </summary>
/// <returns></returns>
private static AesManaged GetAesManaged()
{
// 암호화에 사용할 32bytes 의 키 값.
const string DEFAULT_KEY_ASE256 = "32자리 KEY 입력";
return new AesManaged()
{
KeySize = 256,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
Key = System.Text.Encoding.UTF8.GetBytes(DEFAULT_KEY_ASE256),
IV = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
}
/// <summary>
/// 암호화 AES256
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
[Microsoft.SqlServer.Server.SqlFunction]
public static string EncryptAES256(string inputText)
{
if (string.IsNullOrWhiteSpace(inputText))
return null;
byte[] encrypted;
AesManaged aesAlg = GetAesManaged();
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(inputText);
}
encrypted = msEncrypt.ToArray();
}
}
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// 복호화 AES256
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
[Microsoft.SqlServer.Server.SqlFunction]
public static string DecryptAES256(string inputText)
{
if (string.IsNullOrWhiteSpace(inputText))
return null;
string plaintext = null;
byte[] cipherText = Convert.FromBase64String(inputText);
AesManaged aesAlg = GetAesManaged();
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return plaintext;
}
/// <summary>
/// 단방향 암호화 (SHA256)
/// </summary>
/// <param name="Data"></param>
/// <returns></returns>
[Microsoft.SqlServer.Server.SqlFunction]
public static string SHA256Hash(string inputText)
{
StringBuilder sb = new StringBuilder();
SHA256 sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(inputText));
foreach (byte b in hash)
sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
}
/*
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
*/
/*
-- DROP ASSEMBLY myEncrypt
CREATE ASSEMBLY myEncrypt FROM 'D:\CryptoProject\CryptoSQLProject.dll'
WITH PERMISSION_SET = SAFE
*/
/*
-- DROP FUNCTION dbo.fn_Encrypt
-- DROP FUNCTION dbo.fn_Decrypt
CREATE FUNCTION fn_Encrypt(@value NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
EXTERNAL NAME myEncrypt.CryptoHelper.EncryptAES256
GO
CREATE FUNCTION fn_Decrypt(@value NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
EXTERNAL NAME myEncrypt.CryptoHelper.DecryptAES256
GO
*/
/*
SELECT *
FROM sys.assemblies
SELECT dbo.fn_Encrypt('123-12-123456')
SELECT dbo.fn_Decrypt('Jsh3QXSLqiv2U5q1wF+gEw==')
*/
2018년 1월 10일 수요일
C# - return new Tuple
//---------------------------------------------------------------------
public static T ConvertDataToModel<T>(DataRow dr) where T : class, new()
{
if (dr == null)
{
return null;
}
T toObj = new T();
foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
if (dr.Table.Columns.Contains(prop.Name) && !dr[prop.Name].Equals(DBNull.Value))
{
prop.SetValue(toObj, dr[prop.Name], null);
}
}
return toObj;
}
public static T[] ConvertDataToModelList<T>(DataTable dt) where T : class, new()
{
if (dt == null || dt.Rows.Count <= 0)
{
return null;
}
return dt.AsEnumerable().Select(x => ConvertDataToModel<T>(x)).ToArray();
}
//---------------------------------------------------------------------
var cnt = Convert.ToInt32(ds.Tables[0].Rows[0]["CNT"]);
var modelList = ModelUtil.ConvertDataToModelList<CouponMember>(ds.Tables[1]);
return new Tuple<int, CouponMember[]>(cnt, modelList);
//---------------------------------------------------------------------
[HttpPost]
public JsonResult GetDiscountCoupon(int totalProdPrice, int page, string[] venIds)
{
const int RowCnt = 5;
var bizCoupon = BizFactory.GetInstance<BizCoupon>();
var discountCoupons = bizCoupon.GetDiscountCouponMemberList(MisoMember.MemIdx, totalProdPrice, page, RowCnt, venIds); //몇개안나와서 다가져와서 처리
return Json(new { Cnt = discountCoupons.Item1, List = discountCoupons.Item2 });
}
//---------------------------------------------------------------------
function makeDiscountPopup(page) {
$.ajax({
url: "@Url.Action("GetDiscountCoupon", "Order")",
async: false,
type: "POST",
contentType: "application/json",
data: "{totalProdPrice: " + _totalProdPrice + ", page: " + page + ", venIds: [@Html.Raw(venIdsStr)]}",
success: function (result) {
if (result.Cnt == 0) {
$("#myCouponPopupClose").click();
alert("사용가능한 쿠폰이 없습니다.");
return false;
}
var htmlStr = new Array();
for(var idx = 0; idx < result.List.length; idx++) {
var item = result.List[idx];
var disPrice;
if (item.DIS_STATE == 1) { //비율
disPrice = item.DIS_PRICE + "%";
}
else {
disPrice = item.DIS_PRICE.toNumberFormat() + "원";
}
htmlStr.push('<tr><td scope="row" class="first"><input type="radio" name="myCouponItem" data-venNickname="' + item.VEN_NICKNAME + '" data-venid="' + item.DIS_VEN_ID + '" data-idx="' + item.IDX + '" data-copidx="' + item.COP_IDX + '" data-dissetprice="' + item.DIS_SETPRICE + '" data-disstate="' + item.DIS_STATE + '" data-disprice="' + item.DIS_PRICE + '" data-kind="' + item.COP_KIND + '" data-prodlist="' + item.PROD_LIST + '" /></td>');
htmlStr.push('<td class="left"><img src="/images/order/img_coupon.gif" alt="쿠폰" style="width:69px;height:34px;" />' + item.COP_NAME + '</td>');
htmlStr.push('<td>');
htmlStr.push(item.DIS_SETPRICE.toNumberFormat() + '원 이상');
if (item.DIS_VEN_ID != '0') {
htmlStr.push('<br/> (' + item.VEN_NICKNAME + ')');
}
htmlStr.push('</td>');
htmlStr.push('<td>' + disPrice + '</td>');
htmlStr.push('<td>' + item.ISSUE_DATE.toDateFormat() + '일 부터 ' + item.COP_APPLY_MONTH + '일간</td></tr>');
}
$("#tbdMyCoupon").html(htmlStr.join(''));
pager.makePage("pager", result.Cnt, 5, 5, page);
},
error: function() {
alert("실패");
}
});
}
//---------------------------------------------------------------------
2018년 1월 5일 금요일
정보 - 성능 앞세운 라즈베리파이 대항마 8선
성능 앞세운 라즈베리파이 대항마 8선
가성비 높은 초소형·고성능 보드 쏟아져
개발도상국 어린이의 소프트웨어 교육을 목적으로 만들어진 라즈베리파이. 탄생 5년을 넘어 전세계에 오픈소스 하드웨어와 초저가 컴퓨터 열풍이 한창이다.
라즈베리파이는 25달러짜리 저가보드였지만, 잠재력은 컸다. 어린이나 입문자를 위한 저가보드에서 성인층의 취미활동, 사업체의 인프라까지 무궁무진한 활용범위를 자랑했다.
이후 라즈베리파이의 대항마는 가격 경쟁력 중심과 성능 중심으로 갈라져 발전했다. 초소형 보드란 말이 무색한 고성능 보드가 쏟아져나왔다.
최근 미국 지디넷은 여러 대안 제품 가운데 고성능을 앞세운 라즈베리파이 대안 제품을 정리했다.
■ 화웨이 하이키960
화웨이 하이키960(Huawei HiKey 960)는 안드로이드OS를 구동할 수 있게 고안된 제품이다. 출고가는 239달러로 저렴하지 않다. 그러나 성능만큼은 상대적 고가의 값어치를 한다.[화웨이 하이키960 상세정보]
화웨이 하이키960
기린(Kirin) 960 SoC 쿼드코어 ARM 프로세서(4 개의 2.3GHz ARM A73 코어와 4개의 1.8GHz ARM A53 코어)를 탑재했다. ARM의 빅리틀 기술을 활용한다.
ARM 말리(Mali) G71 MP8 GPU, 3GB LPDDR4 RAM, 32GB UFS 플래시 스토리지를 내장했다.
USB 3.0 포트 2개, 와이파이 및 블루투스 칩셋, HDMI 포트, 40핀 LS 커넥터, 60핀 HS 커넥터, 마이크로SD 카드 슬롯, USB C 포트 등을 제공한다.
■ 우두 쿼드
우두 쿼드(Udoo Quad)는 리눅스 가운데 안드로이드만 사용가능한 보드다.[우두 쿼드 상세정보]
135달러 가격의 쿼드코어 보드로, 프리스케일 i.MX 6 ARM 코어텍스 A9 쿼드코어 프로세서를 장착했다. GPU로 비반테(Vivante) GC2000, 비반테 GC 355, GC 320 등을 탑재했다.
오픈GL ES2.0 3D와 오픈VG 가속기를 통합했다. 아트멜(Atmel) SAM3X8E ARM 코어텍스 M3 CPU도 탑재했다.
1GB DDR3 RAM과 76 GPIO, 아두이노 호환 R3 1.0 핀아웃, HDMI, LVDS+Touch2, 마이크로USB 포트 2개, USB A 포트 2개, USB 커넥터 1개 등을 제공한다.
■ 아두이노 인더스트리얼 101
아두이노 인더스트리얼101은 40달러짜리 아두이노다. 산업장비에 통합할 수 있게 만들어졌다.[아두이노 인더스트리얼101 상세정보]
아두이노 인더스트리얼 101
퀄컴 아테로스(Atheros) AR9331 프로세서와 64MB RAM, 16MB 플래시 스토리지, USB 2.0 포트 등을 제공한다.
■ 바나나파이 M3
바나나파이 M3는 옥타코어 프로세서와 2GB RAM을 자랑한다. 약 75달러에 판매되고 있다.[바나나파이 M3 상세정보]
바나나파이 M3
A83T ARM 코어텍스 A7 1.8 GHz 옥타코어 CPU와 8GB eMMC 플래시스토리지를 탑재했고, 기가비트 이더넷, 와이파이, 블루투스, HDMI포트, SATA 등을 제공한다.
운영체제로 안드로이드, 루분투, 우분투, 데비안, 라즈비안(Raspbian) 등을 지원한다. 마이크와 리셋, 전원 버튼 등을 내장했다.
■ 클라우드비트
클라우드비트(cloudBit)는 프로그래밍 없이 인터넷에 연결가능한 기기를 만들 수 있다. 납땜과 배선 작업도 필요없다.[클라우드비트 상세정보]
클라우드비트
IFTTT 지원으로 어떤 웹 서비스에도 연결가능하다. 페이스북, 지메일, 트위터 등을 연결할 수 있다. 구글 네스트와 필립스 휴 같은 하드웨어도 연결가능하다. 가격은 59.95달러다.
프리스케일 i.MX23 ARM926EJ-S 프로세서, 6MB RAM을 탑재했다. 아치리눅스 배포판을 운영체제로 사용한다. 802.11b/g/n 와이파이를 제공한다.
■ 패러렐라
페러렐라(Parallella)는 신용카드 크기의 고성능 보드다. 99달러에 판매된다. 패러렐라는 독자적인 컴퓨터로 동작하고, 임베디드 기기나 병렬 서버 크러스터의 요소로 활용가능하다.[패라렐라 상세정보]
16코어 이피퍼니(Epiphany) RISC SOC 칩을 장착했다. 징크(Zynq) SOC(FPGA+ARM A9) 프로세서도 내장했다. 소비전력이 5W에 불과하다.
1GB SDRAM, 마이크로SD 스토리지, HDMI 등을 제공하며, 옵션으로 USB 포트를 선택할 수 있다.
■ 인텔 에디슨(아두이노 킷 포함)
인텔 에디슨(Edison)은 아두이노 호환 보드로 92달러에 판매된다.[인텔 에디슨 상세정보]
듀얼코어, 듀얼스레드 인텔 아톰 CPU를 탑재했다. 인텔 쿼크 마이크로컨트롤러도 가졌다.
1GB RAM과 4GB 플래시스토리지를 장착했다. 와이파이와 블루투스 통합칩을 가졌다. 욕토리눅스, 파이썬, 노드JS, 울프램 등을 지원한다.
■ 픽셀프로
픽셀프로(Pixel Pro)는 멀티미디어 애플리케이션에 강점을 보이는 고성능 보드다. 웹서버, 디지털엔터테인먼트시스템, 산업용 제어시스템, 고해상도 비디오 등도 감당한다. 가격은 129.95달러다.[픽셀프로 상세정보]
픽셀프로
1.0GHz 프리스케일 i.MX6Q 쿼드코어 ARM 코어텍스 A9 프로세서를 장착했다. 2D와 3D GPU, 임베디드 2GB 64비트 DDR3 RAM 등을 탑재했다.
802.11b/g/n/ac 와이파이, 기가비트 이더넷, PCIe 1개, USB 2.0 포트 등을 제공한다.
Android - animation
[안드로이드 애니메이션 효과]
애니메이션 효과 프로그래밍 기초--AnimationAndroid
애니메이션 스타일
Android의 animation by 네 종류의 구성
XML 중
alpha : 그라디언트 투명도 애니메이션 효과
scale : 그라디언트 사이즈 신축 애니메이션 효과
translate : 화면 전환 애니메이션 효과 자리 이동
rotate : 화면 회전 애니메이션 효과 이동
JavaCode중
AlphaAnimation : 그라디언트 투명도 애니메이션 효과
ScaleAnimation : 그라디언트 사이즈 신축 애니메이션 효과
TranslateAnimation : 화면 전환 애니메이션 효과 자리 이동
RotateAnimation : 화면 회전 애니메이션 효과 이동
Android 애니메이션 모드
Animation두 가지 주요 애니메이션 모드:
한 가지가 tweened (그라디언트 애니메이션 animation)
XML중
JavaCode
alpha : AlphaAnimation
scale : ScaleAnimation
한 가지가 frame by frame (화면 전환 애니메이션)
XML중
JavaCode
translate : TranslateAnimation
rotate : RotateAnimation
어떻게 XML 파일 중 정의 애니메이션
① 열기 Eclipse, 새 Android 공사
② 지금 res 디렉터리에 새 anim 폴더
③ 지금 anim 디렉터리에 새 한 myanim.xml (파일 이름 소문자 주의)
④ 가입 XML 애니메이션 코드
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha/>
<scale/>
<translate/>
<rotate/>
</set>
Android 애니메이션 해석--XML
<alpha>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="3000"
/>
9 <!-- 투명도 제어 애니메이션 효과 알파
10 부동 소수점 형식 값:
11 fromAlpha 속성 애니메이션 시작 때 투명도 위해
12 toAlpha 속성 을 애니메이션 끝날 때 투명도
13 설명:
14 0.0 대해 완전히 투명
15 1.0 대해 완전히 불투명
16 이상 값 찾다 0.0-1.0 사이의 float 데이터 형식 숫자
17
18 긴 정수 값:
19 duration 속성 을 애니메이션 지속 시간
20 설명:
21 시간 은 밀리초 단위로
22 -->
23 </set>
<scale>
1 <?xml version="1.0" encoding="utf-8"?>
2 <set xmlns:android="http://schemas.android.com/apk/res/android">
3 <scale
4 android:interpolator=
5 "@android:anim/accelerate_decelerate_interpolator"
6 android:fromXScale="0.0"
7 android:toXScale="1.4"
8 android:fromYScale="0.0"
9 android:toYScale="1.4"
10 android:pivotX="50%"
11 android:pivotY="50%"
12 android:fillAfter="false"
13 android:startOffset="700"
14 android:duration="700" />
15 </set>
16 <!-- 사이즈 신축 애니메이션 효과 scale
17 속성: interpolator 지정하지 애니메이션 삽입 그릇
18 내가 실험 과정에서 사용 android.res.anim 중 자원 때 발견
19 세 가지 애니메이션 삽입 그릇:
20 accelerate_decelerate_interpolator 가속 - 감속 애니메이션 삽입 그릇
21 accelerate_interpolator 가속 - 애니메이션 삽입 그릇
22 decelerate_interpolator 감속 - 애니메이션 삽입 그릇
23 다른 은 특정한 애니메이션 효과
24 부동 소수점 형식 값:
25
26 fromXScale 속성 애니메이션 시작 때 X 좌표 위의 신축 사이즈 위해
27 toXScale 속성 을 애니메이션 끝날 때 X 좌표 위의 신축 사이즈
28
29 fromYScale 속성 애니메이션 시작 때 Y 좌표 위의 신축 사이즈 위해
30 toYScale 속성 을 애니메이션 끝날 때 Y 좌표 위의 신축 사이즈
31 startOffset 속성 을 지난번부터 애니메이션 계속 몇 시간 시작한 다음 애니메이션 실행
32
33 설명:
34 이상 네 가지 속성 값
35
36 0.0 표시 수축 없다
37 1.0 것은 정상적인 신축 없다.
38 값 < 1.0 표시 수축
39 가치가 크다 1.0 표시 확대
40
41 pivotX 속성 을 애니메이션 건가요, 물건 X 좌표 시작 위치
42 pivotY 속성 을 애니메이션 건가요, 물건의 Y 좌표 시작 위치
43
44 설명:
45 두 개 이상의 속성 값 이 0%-100% 중 순위
46 50% 물건 X 또는 Y축 좌표 에서 중점 위치 위해
47
48 긴 정수 값:
49 duration 속성 을 애니메이션 지속 시간
50 설명: 시간을 밀리초 단위로 위해
51
52 불 형 값:
53 fillAfter 속성 이 설정을 위해 true 이 애니메이션 전환 애니메이션 끝나면 여기서 다른 응용
54 -->
<translate>
1 <?xml version="1.0" encoding="utf-8"?>
2 <set xmlns:android="http://schemas.android.com/apk/res/android">
3 <translate
4 android:fromXDelta="30"
5 android:toXDelta="-80"
6 android:fromYDelta="30"
7 android:toYDelta="300"
8 android:duration="2000"
9 />
10 <!-- translate 위치 전송 애니메이션 효과
11 정수 값:
12 fromXDelta 속성 애니메이션 시작 때 X 좌표 위의 위치 위해
13 toXDelta 속성 을 애니메이션 끝날 때 X 좌표 위의 위치
14 fromYDelta 속성 애니메이션 시작 때 Y 좌표 위의 위치 위해
15 toYDelta 속성 을 애니메이션 끝날 때 Y 좌표 위의 위치
16 주의:
17 지정되지 fromXType toXType fromYType toYType 때,
18 기본 은 자신을 위해 상대 참조 물건
19 긴 정수 값:
20 duration 속성 을 애니메이션 지속 시간
21 설명: 시간을 밀리초 단위로 위해
22 -->
23 </set>
<rotate>
1 <?xml version="1.0" encoding="utf-8"?>
2 <set xmlns:android="http://schemas.android.com/apk/res/android">
3 <rotate
4 android:interpolator="@android:anim/accelerate_decelerate_interpolator"
5 android:fromDegrees="0"
6 android:toDegrees="+350"
7 android:pivotX="50%"
8 android:pivotY="50%"
9 android:duration="3000" />
10 <!-- rotate 회전 애니메이션 효과
11 속성: interpolator 지정하지 애니메이션 삽입 그릇
12 내가 실험 과정에서 사용 android.res.anim 중 자원 때 발견
13 세 가지 애니메이션 삽입 그릇:
14 accelerate_decelerate_interpolator 가속 - 감속 애니메이션 삽입 그릇
15 accelerate_interpolator 가속 - 애니메이션 삽입 그릇
16 decelerate_interpolator 감속 - 애니메이션 삽입 그릇
17 다른 은 특정한 애니메이션 효과
18
19 부동 소수점 숫자 형식 값:
20 fromDegrees 속성 애니메이션 시작 때 개체 각도에서 위해
21 toDegrees 속성 을 애니메이션 끝날 때 개체 회전 각도를 크다 360 도 할 수 있다
22
23 설명:
24 이 각도에서 위해 음수 — — 기 반시계 방향으로 회전
25 이 각도에서 위해 플러스 — — 표시 시계 방향으로 회전
26 (부 from— — to 플러스: 시계 방향으로 회전)
27 (부 from— — to 음수: 반시계방향으로)
28 (양수 from— — to 플러스: 시계 방향으로 회전)
29 (양수 from— — to 음수: 반시계방향으로)
30
31 pivotX 속성 을 애니메이션 건가요, 물건 X 좌표 시작 위치
32 pivotY 속성 을 애니메이션 건가요, 물건의 Y 좌표 시작 위치
33
34 설명: 이상 두 속성 값 이 0%-100% 중 순위
35 50% 물건 X 또는 Y축 좌표 에서 중점 위치 위해
36
37 긴 정수 값:
38 duration 속성 을 애니메이션 지속 시간
39 설명: 시간을 밀리초 단위로 위해
40 -->
41 </set>
XML 중 애니메이션 효과 어떻게 사용
1 public static Animation loadAnimation (Context context, int id)
2 //첫 번째 인자 Context 프로그램 컨텍스트 위해
3 //두 번째 인자 id 위해 애니메이션 XML 파일 참조
4 //예:
5 myAnimation= AnimationUtils.loadAnimation(this,R.anim.my_action);
6 //사용 AnimationUtils 같은 정적 방법 loadAnimation () 와 XML 불러오기 중 애니메이션 XML 파일
어떻게 중에 자바 코드 정의 애니메이션
1 //코드 정의 애니메이션 대상 은 중 인스턴스
2 private Animation myAnimation_Alpha;
3 private Animation myAnimation_Scale;
4 private Animation myAnimation_Translate;
5 private Animation myAnimation_Rotate;
6
7 //각자의 구조 방법에 근거해서 하나의 인스턴스를 대상 초기화할 수 없습니다.
8 myAnimation_Alpha=new AlphaAnimation(0.1f, 1.0f);
9
10 myAnimation_Scale =new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
11 Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
12
13 myAnimation_Translate=new TranslateAnimation(30.0f, -80.0f, 30.0f, 300.0f);
14
15 myAnimation_Rotate=new RotateAnimation(0.0f, +350.0f,
16 Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
Android 애니메이션 해석--JavaCode
AlphaAnimation
① AlphaAnimation 클래스 대상 정의
1 private AlphaAnimation myAnimation_Alpha;
② AlphaAnimation 클래스 대상 구조
1 AlphaAnimation(float fromAlpha, float toAlpha)
2 //첫 번째 매개 변수 fromAlpha 위해 애니메이션 시작 때 투명도
3 //두 번째 매개 변수 toAlpha 위해 애니메이션 끝날 때 투명도
4 myAnimation_Alpha=new AlphaAnimation(0.1f, 1.0f);
5 //설명:
6 // 0.0 대해 완전히 투명
7 // 1.0 대해 완전히 불투명
③ 설정 애니메이션 지속 시간
1 myAnimation_Alpha.setDuration(5000);
2 //설정 시간 지속 시간 을 5천 초
ScaleAnimation
① ScaleAnimation 클래스 대상 정의
1 private AlphaAnimation myAnimation_Alpha;
② ScaleAnimation 클래스 대상 구조
1 ScaleAnimation(float fromX, float toX, float fromY, float toY,
2 int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)
3 //첫 번째 매개 변수 fromX 애니메이션 시작 때 X 좌표 위의 신축 사이즈 위해
4 //두 번째 매개 변수 toX 위해 애니메이션 끝날 때 X 좌표 위의 신축 사이즈
5 //세 번째 매개 변수 fromY 애니메이션 시작 때 Y 좌표 위의 신축 사이즈 위해
6 //네 번째 매개 변수 toY 위해 애니메이션 끝날 때 Y 좌표 위의 신축 사이즈
7
8 //다섯 개의 인자를 pivotXType 위해 애니메이션 X 축 건가요, 물건 위치 형식
9 //여섯 개의 인자를 pivotXValue 위해 애니메이션 건가요, 물건 X 좌표 시작 위치
10 //일곱 개의 인자를 pivotXType 위해 애니메이션 지금 Y축 건가요, 물건 위치 형식
11 //여덟 개의 인자를 pivotYValue 위해 애니메이션 건가요, 물건의 Y 좌표 시작 위치
12 myAnimation_Scale =new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
13 Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
③ 설정 애니메이션 지속 시간
1 myAnimation_Scale.setDuration(700);
2 //설정 시간 시간 (밀리초 위해 700
TranslateAnimation
① TranslateAnimation 클래스 대상 정의
1 private AlphaAnimation myAnimation_Alpha;
② TranslateAnimation 클래스 대상 구조
1 TranslateAnimation(float fromXDelta, float toXDelta,
2 float fromYDelta, float toYDelta)
3 //첫 번째 매개 변수 fromXDelta 애니메이션 시작 때 X 좌표 위로 이동 위치 위해
4 //두 번째 매개 변수 toXDelta 위해 애니메이션 끝날 때 X 좌표 위로 이동 위치
5 //세 번째 매개 변수 fromYDelta 애니메이션 시작 때 Y 좌표 위로 이동 위치 위해
6 //네 번째 매개 변수 toYDelta 위해 애니메이션 끝날 때 Y 좌표 위로 이동 위치
③ 설정 애니메이션 지속 시간
1 myAnimation_Translate.setDuration(2000);
2 //설정 시간 지속 시간 은 2000년 초
RotateAnimation
① RotateAnimation 클래스 대상 정의
1 private AlphaAnimation myAnimation_Alpha;
② RotateAnimation 클래스 대상 구조
1 RotateAnimation(float fromDegrees, float toDegrees,
2 int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)
3 //첫 번째 매개 변수 fromDegrees 애니메이션 시작 때 회전 각도 위해
4 //두 번째 매개 변수 toDegrees 위해 애니메이션 회전 각도 까지
5 //세 번째 매개 변수 pivotXType 위해 애니메이션 X 축 건가요, 물건 위치 형식
6 //네 번째 매개 변수 pivotXValue 위해 애니메이션 건가요, 물건 X 좌표 시작 위치
7 //다섯 개의 인자를 pivotXType 위해 애니메이션 지금 Y축 건가요, 물건 위치 형식
8 //여섯 개의 인자를 pivotYValue 위해 애니메이션 건가요, 물건의 Y 좌표 시작 위치
9 myAnimation_Rotate=new RotateAnimation(0.0f, +350.0f,
10 Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
③ 설정 애니메이션 지속 시간
1 myAnimation_Rotate.setDuration(3000);
2 //설정 시간 지속 시간 3천 초
자바 코드 중 애니메이션 효과 어떻게 사용
에서 View 부 클래스 상속 온 사용 방법 startAnimation () 와 위해 View 또는 하위 클래스 View, 한 애니메이션 효과 추가
애니메이션 효과 순서
1 android:animationOrder="random" //임의
4 android:animationOrder="reverse"//부정
9 gridLayoutAnimation
12 android:directionPriority="row"
14 android:directionPriority="column"
16 android:direction="right_to_left|bottom_to_top"
출처 : http://www.programkr.com/blog/MYDNzADMwYTy.html
2017년 12월 26일 화요일
Unity - Local DB - C# - JsonHelper
https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity
Unity added JsonUtility to their API after 5.3.3 Update. Forget about all the 3rd party libraries unless you are doing something more complicated. JsonUtility is faster than other Json libraries. Update to Unity 5.3.3 version or above then try the solution below.
JsonUtility is a lightweight API. Only simple types are supported. It does not support collections such as Dictionary. One exception is List. It supports List and List array!
If you need to serialize a
Dictionary or do something other than simply serializing and deserializing simple datatypes, use a third-party API. Otherwise, continue reading.
Example class to serialize:
[Serializable]
public class Player
{
public string playerId;
public string playerLoc;
public string playerNick;
}
1. ONE DATA OBJECT (NON-ARRAY JSON)
Serializing Part A:
Serialize to Json with the
public static string ToJson(object obj); method.Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
//Convert to Jason
string playerToJason = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJason);
Output:
{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}
Serializing Part B:
Serialize to Json with the
public static string ToJson(object obj, bool prettyPrint); method overload. Simply passing true to the JsonUtility.ToJson function will format the data. Compare the output below to the output above.Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";
//Convert to Jason
string playerToJason = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJason);
Output:
{
"playerId": "8484239823",
"playerLoc": "Powai",
"playerNick": "Random Nick"
}
Deserializing Part A:
Deserialize json with the
public static T FromJson(string json); method overload.string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);
Deserializing Part B:
Deserialize json with the
public static object FromJson(string json, Type type); method overload.string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);
Deserializing Part C:
Deserialize json with the
public static void FromJsonOverwrite(string json, object objectToOverwrite); method. When JsonUtility.FromJsonOverwrite is used, no new instance of that Object you are deserializing to will be created. It will simply re-use the instance you pass in and overwrite its values.
This is efficient and should be used if possible.
Player playerInstance;
void Start()
{
//Must create instance once
playerInstance = new Player();
deserialize();
}
void deserialize()
{
string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
//Overwrite the values in the existing class instance "playerInstance". Less memory Allocation
JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
Debug.Log(playerInstance.playerLoc);
}
2. MULTIPLE DATA(ARRAY JSON)
Your Json contains multiple data objects. For example
playerId appeared more than once. Unity's JsonUtility does not support array as it is still new but you can use a helper class from this person to get array working with JsonUtility.
Create a class called
JsonHelper. Copy the JsonHelper directly from below.public static class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper);
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return JsonUtility.ToJson(wrapper, prettyPrint);
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
Serializing Json Array:
Player[] playerInstance = new Player[2];
playerInstance[0] = new Player();
playerInstance[0].playerId = "8484239823";
playerInstance[0].playerLoc = "Powai";
playerInstance[0].playerNick = "Random Nick";
playerInstance[1] = new Player();
playerInstance[1].playerId = "512343283";
playerInstance[1].playerLoc = "User2";
playerInstance[1].playerNick = "Rand Nick 2";
//Convert to Jason
string playerToJason = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJason);
Output:
{
"Items": [
{
"playerId": "8484239823",
"playerLoc": "Powai",
"playerNick": "Random Nick"
},
{
"playerId": "512343283",
"playerLoc": "User2",
"playerNick": "Rand Nick 2"
}
]
}
Deserializing Json Array:
string jsonString = "{\r\n \"Items\": [\r\n {\r\n \"playerId\": \"8484239823\",\r\n \"playerLoc\": \"Powai\",\r\n \"playerNick\": \"Random Nick\"\r\n },\r\n {\r\n \"playerId\": \"512343283\",\r\n \"playerLoc\": \"User2\",\r\n \"playerNick\": \"Rand Nick 2\"\r\n }\r\n ]\r\n}";
Player[] player = JsonHelper.FromJson<Player>(jsonString);
Debug.Log(player[0].playerLoc);
Debug.Log(player[1].playerLoc);
Output:
PowaiUser2
If this is a Json array from the server and you did not create it by hand:
You may have to Add
{"Items": in front of the received string then add } at the end of it.
I made a simple function for this:
string fixJson(string value)
{
value = "{\"Items\":" + value + "}";
return value;
}
then you can use it:
string jsonString = fixJson(yourJsonFromServer);
Player[] player = JsonHelper.FromJson<Player>(jsonString);
3.Deserialize json string without class && De-serializing Json with numeric properties
This is a Json that starts with a number or numeric properties.
For example:
{
"USD" : {"15m" : 1740.01, "last" : 1740.01, "buy" : 1740.01, "sell" : 1744.74, "symbol" : "$"},
"ISK" : {"15m" : 179479.11, "last" : 179479.11, "buy" : 179479.11, "sell" : 179967, "symbol" : "kr"},
"NZD" : {"15m" : 2522.84, "last" : 2522.84, "buy" : 2522.84, "sell" : 2529.69, "symbol" : "$"}
}
Unity's
JsonUtility does not support this because the "15m" property starts with a number. A class variable cannot start with an integer.
Download
SimpleJSON.cs from Unity's wiki.
To get the "15m" property of USD:
var N = JSON.Parse(yourJsonString);
string price = N["USD"]["15m"].Value;
Debug.Log(price);
To get the "15m" property of ISK:
var N = JSON.Parse(yourJsonString);
string price = N["ISK"]["15m"].Value;
Debug.Log(price);
To get the "15m" property of NZD:
var N = JSON.Parse(yourJsonString);
string price = N["NZD"]["15m"].Value;
Debug.Log(price);
The rest of the Json properties that doesn't start with a numeric digit can be handled by Unity's JsonUtility.
4.TROUBLESHOOTING JsonUtility:
Problems when serializing with
JsonUtility.ToJson?
Getting empty string or "
{}" with JsonUtility.ToJson?
A. Make sure that the class is not an array. If it is, use the helper class above with
JsonHelper.ToJson instead of JsonUtility.ToJson.
B. Add
[Serializable] to the top of the class you are serializing.
C. Remove property from the class. For example, in the variable,
public string playerId { get; set; } remove { get; set; }. Unity cannot serialize this.
Problems when deserializing with
JsonUtility.FromJson?
A. If you get
Null, make sure that the Json is not a Json array. If it is, use the helper class above with JsonHelper.FromJson instead of JsonUtility.FromJson.
B. If you get
NullReferenceException while deserializing, add [Serializable] to the top of the class.
C.Any other problems, verify that your json is valid. Go to this site here and paste the json. It should show you if the json is valid. It should also generate the proper class with the Json. Just make sure to remove remove
{ get; set; } from each variable and also add [Serializable] to the top of each class generated.
Newtonsoft.Json:
If for some reason Newtonsoft.Json must be used then check out the forked version for Unity here. Note that you may experience crash if certain feature is used. Be careful.
To answer your question:
Your original data is
[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]
Add
{"Items": in front of it then add } at the end of it.
Code to do this:
serviceData = "{\"Items\":" + serviceData + "}";
Now you have:
{"Items":[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]}
To serialize the multiple data from php as arrays, you can now do
public player[] playerInstance;
playerInstance = JsonHelper.FromJson<player>(serviceData);
playerInstance[0] is your first dataplayerInstance[1] is your second dataplayerInstance[2] is your third data
or data inside the class with
playerInstance[0].playerLoc, playerInstance[1].playerLoc, playerInstance[2].playerLoc ......
You can use
playerInstance.Length to check the length before accessing it.
NOTE: Remove
{ get; set; } from the player class. If you have { get; set; }, it wont work. Unity's JsonUtility does NOT work with class members that are defined as properties.
피드 구독하기:
글 (Atom)
MSSQL - Cursor vs Temp Table
#테이블 변수사용의 예 use pubs go declare @tmptable table ( nid int identity(1,1) not null, title varchar (80) not null ) -- 테이블 변수 선언 inse...
-
11 SQL Client for Productive Database Administration & Development Working as a web developer or database administrator, often n...
-
Network Address Description 10.0.2.1 Router/gateway address 10.0.2.2 Special alias to your host loopback interface (i.e., 127.0....