using System;
using System.Globalization;
using System.Net;
using System.Runtime.InteropServices;
namespace timechange
{
internal class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetLocalTime(ref SYSTEMTIME st);
static void Main(string[] args)
{
DateTime dateTime = DateTime.MinValue;
try
{
// 네이버 사이트 시간하고 맞춰서 시간 설정
using (var response = WebRequest.Create("https://www.naver.com").GetResponse())
dateTime = DateTime.ParseExact(response.Headers["date"],
"ddd, dd MMM yyyy HH:mm:ss 'GMT'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
catch (Exception)
{
dateTime = DateTime.Now;
}
Console.WriteLine(dateTime);
SYSTEMTIME st = new SYSTEMTIME();
st.wYear = (short)dateTime.Year;
st.wMonth = (short)dateTime.Month;
st.wDay = (short)dateTime.Day;
st.wHour = (short)dateTime.Hour;
st.wMinute = (short)dateTime.Minute;
st.wSecond = (short)dateTime.Second;
st.wMilliseconds = (short)dateTime.Millisecond;
SetSystemTime(ref st);
SetLocalTime(ref st);
Console.ReadKey();
}
}
}
22. 7. 7.
C# 내 로컬 PC시간 NAVER 서버 시간으로 변경
19. 4. 4.
C#으로 MYSQL 연동
C# 에서 MySql을 연동하려면 사전 준비가 필요.
기준 : 비주얼스튜디오
1. 프로젝트 생성할 때 프레임워크를 4.5.2로 생성
2. 솔루션 탐색기의 프로젝트명에서 우클릭
3. NuGet 패키지 관리
4. MySql.Data 설치(8.0.15 버전으로 설치함)
insert,update,delete
select
기준 : 비주얼스튜디오
1. 프로젝트 생성할 때 프레임워크를 4.5.2로 생성
2. 솔루션 탐색기의 프로젝트명에서 우클릭
3. NuGet 패키지 관리
4. MySql.Data 설치(8.0.15 버전으로 설치함)
insert,update,delete
using MySql.Data.MySqlClient;
namespace MySql
{
class Program
{
static void Main(string[] args)
{
// Sql 연결정보(서버:127.0.0.1, 아이디:sa, 비밀번호 : password, db : member)
string connectionString = "server = 127.0.0.1; uid = sa; pwd = password; database = member;";
// Sql 새연결정보 생성
MySqlConnection sqlConn = new MySqlConnection(connectionString);
MySqlCommand sqlComm = new MySqlCommand();
sqlComm.Connection = sqlConn;
sqlComm.CommandText = "insert into tbl_member (id,name,addr) values ('abc','홍길동','서울');";
//sqlComm.CommandText = "update tbl_member set addr='서울' where id='abc' and name='홍길동';";
//sqlComm.CommandText = "delete tbl_member where id='abc' and name='홍길동' and addr='서울';";
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}
}
}
select
using MySql.Data.MySqlClient;
using System;
namespace MySql
{
class Program
{
static void Main(string[] args)
{
string connectionString = "server = 127.0.0.1,3535; uid = sa; pwd = password; database = member;";
// Sql 새연결정보 생성
MySqlConnection sqlConn = new MySqlConnection(connectionString);
MySqlCommand sqlComm = new MySqlCommand();
sqlComm.Connection = sqlConn;
sqlComm.CommandText = "select id,addr from tbl_member where name='홍길동' order by id asc limit 10";
sqlConn.Open();
using (MySqlDataReader SqlRs = sqlComm.ExecuteReader())
{
Console.WriteLine("ID \t \t | Address");
while (SqlRs.Read())
{
Console.WriteLine(string.Format("{0} \t \t | {1}", SqlRs[0].ToString(), SqlRs[1].ToString()));
}
}
sqlConn.Close();
}
}
}
19. 1. 28.
HTML을 PDF로 저장(C#, VB)
Visual Studio 의 솔루션 탐색기에서 우클릭
Nuget 패키지 관리 -> 찾아보기 -> NReco.PdfGenerator -> 설치
C#
VB
Nuget 패키지 관리 -> 찾아보기 -> NReco.PdfGenerator -> 설치
C#
using System.IO;
using System.Text;
namespace HtmlToPdf
{
class Program
{
static void Main(string[] args)
{
StringBuilder saveHtml = new StringBuilder();
saveHtml.Append("<!DOCTYPE html>");
saveHtml.Append("<html lang=\"ko\">");
saveHtml.Append("<head>");
saveHtml.Append("<meta charset=\"utf-8\" />");
saveHtml.Append("<title>Html을 PDF로</title>");
saveHtml.Append("</head>");
saveHtml.Append("<body>");
saveHtml.Append("<h1>Html을 PDF로</h1><p>좋은하루입니다.</p>");
saveHtml.Append("</body>");
saveHtml.Append("</html>");
// NReco 호출
var converter = new NReco.PdfGenerator.HtmlToPdfConverter();
// 저장할 파일명
string pdfFile = @"d:\test.pdf";
// 파일이 있을경우 삭제
if (File.Exists(pdfFile))
{
File.Delete(pdfFile);
}
// saveHtml을 pdf byte 형식으로 반환
byte[] f = converter.GeneratePdf(saveHtml.ToString());
// 파일을 저장
File.WriteAllBytes(pdfFile, f);
}
}
}
VB
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
Dim saveHtml As StringBuilder = New StringBuilder
saveHtml.Append("<!DOCTYPE html>")
saveHtml.Append("<html lang=""ko"">")
saveHtml.Append("<head>")
saveHtml.Append("<meta charset=""utf-8"" />")
saveHtml.Append("<title>Html을 PDF로</title>")
saveHtml.Append("</head>")
saveHtml.Append("<body>")
saveHtml.Append("<h1>Html을 PDF로</h1><p>좋은하루입니다.</p>")
saveHtml.Append("</body>")
saveHtml.Append("</html>")
' NReco 호출
Dim Converter = New NReco.PdfGenerator.HtmlToPdfConverter
' 저장할 파일명
Dim pdfFile As String = "d:\test.pdf"
' 파일이 있을경우 삭제
If File.Exists(pdfFile) Then
File.Delete(pdfFile)
End If
' saveHtml을 pdf byte 형식으로 반환
Dim f As Byte() = Converter.GeneratePdf(saveHtml.ToString())
' 파일을 저장
File.WriteAllBytes(pdfFile, f)
End Sub
End Module
19. 1. 26.
C# 에서 엑셀(Xlsx) 저장
Visual Studio 의 솔루션 탐색기에서 우클릭
Nuget 패키지 관리 -> 찾아보기 -> EPPlus -> 설치
Nuget 패키지 관리 -> 찾아보기 -> EPPlus -> 설치
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
namespace XlsxSaveProgram
{
class Program
{
static void Main(string[] args)
{
// 저장파일명
string xlsxfile = string.Format("Test{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss"));
// 기존파일있을경우 삭제
FileInfo excelFile = new FileInfo(xlsxfile);
if (excelFile.Exists) { excelFile.Delete(); }
// 조회기간
DateTime date1 = DateTime.Now.AddDays(-7);
DateTime date2 = DateTime.Now.AddDays(-1);
// 시트가 여러개일 경우
string[] sheets = new string[] { "시트1", "시트2", "시트3" };
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
// 패키지가 이용가능하다면
using (ExcelPackage excel = new ExcelPackage())
{
// 시트 개수만큼 반복
for (var i = 0; i < sheets.Length; i++)
{
// 시트 추가
excel.Workbook.Worksheets.Add(sheets[i]);
// 상단 고정내용 처리
List<object[]> dataRow = new List<object[]>()
{
new string[] { sheets[i] },
new string[] { string.Format("{0} ~ {1}", date1.ToString("yyyy.MM.dd"), date2.ToString("yyyy.MM.dd")) },
new string[] { "컬럼1","컬럼2","컬럼3","컬럼4","컬럼5","컬럼6" }
};
// 몇줄인지 cnt에저장
decimal cnt = 0;
dataRow.Add(new object[] { "필드1_1", "필드2_1", "필드3_1", "필드4_1", "필드5_1", "필드6_1" });
dataRow.Add(new object[] { "필드1_2", "필드2_2", "필드3_2", "필드4_2", "필드5_2", "필드6_2" });
// 2줄만 추가했으므로
cnt = 2;
string headerRange = "A1:" + Char.ConvertFromUtf32(dataRow[0].Length + 64) + "1";
// 시트선택
var worksheet = excel.Workbook.Worksheets[sheets[i]];
// 워크시트에 DataRow 를 불러옴
worksheet.Cells[headerRange].LoadFromArrays(dataRow);
// 스타일 지정
worksheet.Column(1).Width = 18;
worksheet.Column(2).Width = 26;
worksheet.Column(3).Width = 26;
worksheet.Column(4).Width = 16;
worksheet.Column(5).Width = 16;
worksheet.Column(6).Width = 21;
worksheet.Column(1).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Column(2).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Column(3).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Column(4).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Column(5).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Column(6).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
worksheet.Column(1).Style.Font.SetFromFont(new System.Drawing.Font("나눔고딕", 10));
worksheet.Column(2).Style.Font.SetFromFont(new System.Drawing.Font("나눔고딕", 10));
worksheet.Column(3).Style.Font.SetFromFont(new System.Drawing.Font("나눔고딕", 10));
worksheet.Column(4).Style.Font.SetFromFont(new System.Drawing.Font("나눔고딕", 10));
worksheet.Column(5).Style.Font.SetFromFont(new System.Drawing.Font("나눔고딕", 10));
worksheet.Column(6).Style.Font.SetFromFont(new System.Drawing.Font("나눔고딕", 10));
worksheet.Row(1).Style.Font.Bold = true;
worksheet.Row(1).Style.Font.Size = 16;
worksheet.Row(1).Height = 30;
worksheet.Row(2).Style.Font.Size = 12;
worksheet.Row(2).Height = 24;
worksheet.Row(3).Style.Font.Bold = true;
worksheet.Row(3).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
worksheet.Row(3).Style.Font.Size = 10;
worksheet.Row(3).Height = 18;
using (ExcelRange range = worksheet.Cells[string.Format("A3:F{0}", (cnt + 3).ToString())])
{
range.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
range.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
range.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
range.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
}
using (ExcelRange range = worksheet.Cells[string.Format("B3:C{0}", (cnt + 3).ToString())])
{
range.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
using (ExcelRange range = worksheet.Cells[string.Format("E3:E{0}", (cnt + 3).ToString())])
{
range.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
}
for (var x = 0; x < cnt + 3; x++)
{
worksheet.Row(x + 3).Height = 18;
}
}
// 비밀번호 pwd
//excel.Encryption.Password = "pwd";
// 내용을 엑셀파일로 저장
excel.SaveAs(excelFile);
// 저장위치 출력
Console.WriteLine("SavePath : {0}", excelFile);
}
}
}
}
18. 11. 23.
ASP.NET AES 암호화 클래스
C#
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// 클래스 호출
Security AES = new Security();
// 키32자리
string key = "12345678901234567890123456789012";
// 암호화 문자열
string str = "암호화할 문자열입니다.";
// 암호화된 문자열
string result1 = AES.AES_encrypt(str, key);
// 암호화된 문자열 출력
Console.WriteLine(result1);
// 복호화된 문자열
string result2 = AES.AES_decrypt(result1, key);
// 복호화된 문자열 출력
Console.WriteLine(result2);
}
}
public class Security
{
public string AES_encrypt(string input, string key)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = new Byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
Byte[] xBuff = null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
{
Byte[] xXml = Encoding.UTF8.GetBytes(input);
cs.Write(xXml, 0, xXml.Length);
}
xBuff = ms.ToArray();
}
return Convert.ToBase64String(xBuff);
}
public string AES_decrypt(string input, string key)
{
if (input == "") { return ""; }
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = new Byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
var decrypt = aes.CreateDecryptor();
Byte[] xBuff = null;
using (MemoryStream ms = new MemoryStream())
{
try
{
using (CryptoStream cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
{
Byte[] xXml = Convert.FromBase64String(input);
cs.Write(xXml, 0, xXml.Length);
}
}
catch
{
return "";
}
xBuff = ms.ToArray();
}
if (xBuff.Length > 0)
{
string Output = Encoding.UTF8.GetString(xBuff);
return Output.Trim();
}
else
{
return "";
}
}
}
}
Visual Basic
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Module Module1
Sub Main()
'클래스 호출
Dim AES As Security = New Security()
'키32자리
Dim key As String = "12345678901234567890123456789012"
'암호화 문자열
Dim str As String = "암호화할 문자열입니다."
'암호화된 문자열
Dim result1 As String = AES.AES_encrypt(str, key)
'암호화된 문자열 출력
Console.WriteLine(result1)
'복호화된 문자열
Dim result2 As String = AES.AES_decrypt(result1, key)
'복호화된 문자열 출력
Console.WriteLine(result2)
End Sub
Private Class Security
Function AES_encrypt(ByVal input As String, ByVal key As String) As String
Dim aes As RijndaelManaged = New RijndaelManaged
aes.KeySize = 256
aes.BlockSize = 128
aes.Mode = CipherMode.CBC
aes.Padding = PaddingMode.PKCS7
aes.Key = Encoding.UTF8.GetBytes(key)
aes.IV = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
Dim encrypt = aes.CreateEncryptor(aes.Key, aes.IV)
Dim xBuff As Byte() = Nothing
Using ms As MemoryStream = New MemoryStream()
Using cs As CryptoStream = New CryptoStream(ms, encrypt, CryptoStreamMode.Write)
Dim xXml As Byte() = Encoding.UTF8.GetBytes(input)
cs.Write(xXml, 0, xXml.Length)
End Using
xBuff = ms.ToArray()
End Using
Dim Output As String = Convert.ToBase64String(xBuff)
Return Output
End Function
Function AES_decrypt(ByVal input As String, ByVal key As String) As String
If input = "" Then Return ""
Dim aes As RijndaelManaged = New RijndaelManaged
aes.KeySize = 256
aes.BlockSize = 128
aes.Mode = CipherMode.CBC
aes.Padding = PaddingMode.PKCS7
aes.Key = Encoding.UTF8.GetBytes(key)
aes.IV = New Byte() {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
Dim decrypt = aes.CreateDecryptor()
Dim xBuff As Byte() = Nothing
Using ms As MemoryStream = New MemoryStream()
Try
Using cs As CryptoStream = New CryptoStream(ms, decrypt, CryptoStreamMode.Write)
Dim xXml As Byte() = Convert.FromBase64String(input)
cs.Write(xXml, 0, xXml.Length)
End Using
Catch ex As Exception
End Try
xBuff = ms.ToArray()
End Using
If IsDBNull(xBuff) Then
Return ""
Else
Dim Output As String = Encoding.UTF8.GetString(xBuff)
Return Output.Trim()
End If
End Function
End Class
End Module
17. 12. 1.
C#으로 네이트온 팀룸 OPEN API를 이용하기(알림)
네이트온 팀룸 api를 c#으로 이용하기
※ Webhook url 은 네이트온의 팀룸을 열면 팀룸메뉴 -> 오픈 API 이용하기 -> 새로 연결하기 또는 편집으로 들어가면 확인 가능하다.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace TeamRoomTest
{
class Program
{
static void Main(string[] args)
{
try
{
// Webhook URL
string webHookUrl = "https://teamroom.nate.com/api/webhook/6fc73b8a/MDNieeQGWvEGnqQXO4wugRra";
// Send Message
string sendMessage = "테스트입니당~";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(string.Format("content={0}", System.Web.HttpUtility.UrlEncode(sendMessage)));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(webHookUrl);
req.Timeout = 5000;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
req.GetResponse();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
※ Webhook url 은 네이트온의 팀룸을 열면 팀룸메뉴 -> 오픈 API 이용하기 -> 새로 연결하기 또는 편집으로 들어가면 확인 가능하다.
16. 7. 28.
C#으로 MS-SQL 연동
insert,update,delete
select
using System;
using System.Data.SqlClient;
namespace MsSql
{
class Program
{
static void Main(string[] args)
{
// Sql 연결정보(서버:127.0.0.1, 포트:3535, 아이디:sa, 비밀번호 : password, db : member)
string connectionString = "server = 127.0.0.1,3535; uid = sa; pwd = password; database = member;";
// Sql 새연결정보 생성
SqlConnection sqlConn = new SqlConnection(connectionString);
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlConn;
sqlComm.CommandText = "insert into tbl_member (id,name,addr) values (@param1,@param2,@param3)";
//sqlComm.CommandText = "update tbl_member set addr=@param3 where id=@param1 and name=@param2";
//sqlComm.CommandText = "delete tbl_member where id=@param1 and name=@param2 and addr=@param3";
sqlComm.Parameters.AddWithValue("@param1", "abc");
sqlComm.Parameters.AddWithValue("@param2", "홍길동");
sqlComm.Parameters.AddWithValue("@param3", "서울");
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}
}
}
select
using System;
using System.Data.SqlClient;
namespace MsSql
{
class Program
{
static void Main(string[] args)
{
// Sql 연결정보(서버:127.0.0.1, 포트:3535, 아이디:sa, 비밀번호 : password, db : member)
string connectionString = "server = 127.0.0.1,3535; uid = sa; pwd = password; database = member;";
// Sql 새연결정보 생성
SqlConnection sqlConn = new SqlConnection(connectionString);
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlConn;
sqlComm.CommandText = "select top 10 id,addr from tbl_member where name=@param1 order by id asc";
sqlComm.Parameters.AddWithValue("@param1", "김준");
sqlConn.Open();
using (SqlDataReader SqlRs = sqlComm.ExecuteReader())
{
Console.WriteLine("ID \t \t | Address");
while (SqlRs.Read())
{
Console.WriteLine(string.Format("{0} \t \t | {1}", SqlRs[0].ToString(),SqlRs[1].ToString()));
}
}
sqlConn.Close();
}
}
}
16. 7. 20.
C#.NET 파일업로드
upload.html 파일
<!doctype html> <html> <head> <meta charset="utf-8"> <title>파일업로드</title> </head> <body> <form name="form1" method="post" action="Upload.aspx" enctype="multipart/form-data"> <input type="file" name="file1" multiple/> <input type="submit" value="업로드"/> </form> </body> </html>
Upload.aspx 파일
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upload.aspx.cs" Inherits="Upload" %>
Upload.aspx.cs 파일
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
public partial class Upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpFileCollection uploadedFiles = Request.Files;
int maxFile = 10;
if (uploadedFiles.Count > maxFile)
{
Response.Write("한번에 올릴 수 있는 파일수는 " + maxFile.ToString() + "개입니다.");
return;
}
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile userPostedFile = uploadedFiles[i];
if (userPostedFile.ContentLength > 0 && !String.IsNullOrEmpty(userPostedFile.FileName))
{
string result = UploadFileSave(userPostedFile, i);
if (result != "")
{
// 업로드 성공
Response.Write(result + " ");
}
else
{
// 업로드 실패
}
}
}
}
private string UploadFileSave(HttpPostedFile SaveFile, int no)
{
// 저장폴더
string wPath = Server.MapPath("/file") + "\\";
string thumPath = Server.MapPath("/file/thum") + "\\";
DirectoryInfo di = new DirectoryInfo(wPath);
// 폴더가 없을 경우 생성
if (di.Exists == false)
di.Create();
di = new DirectoryInfo(thumPath);
// 폴더가 없을 경우 생성
if (di.Exists == false)
di.Create();
// 확장자
string fileType = SaveFile.FileName.Substring(SaveFile.FileName.LastIndexOf(".") + 1);
// 변경할 파일 이름
string saveFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + '_' + no + "." + fileType;
try
{
// 이미지 확장자 일 경우
if (("jpg|jpeg|bmp|gif|png").IndexOf(fileType.ToLower()) > -1)
{
Bitmap img = new Bitmap(SaveFile.InputStream);
RotateFlipType rft = RotateFlipType.RotateNoneFlipNone;
PropertyItem[] properties = img.PropertyItems;
foreach (PropertyItem p in properties)
{
// 이미지가 똑바로 되어있지 않은 경우
if (p.Id == 274)
{
Int16 orientation = BitConverter.ToInt16(p.Value, 0);
switch (orientation)
{
case 1:
rft = RotateFlipType.RotateNoneFlipNone;
break;
case 3:
rft = RotateFlipType.Rotate180FlipNone;
break;
case 4:
rft = RotateFlipType.Rotate90FlipNone;
break;
case 8:
rft = RotateFlipType.Rotate270FlipNone;
break;
}
}
}
// 이미지가 부분은 이미지가 누워있을 경우 세워준다
if (rft != RotateFlipType.RotateNoneFlipNone)
{
img.RotateFlip(rft);
}
// 저장
img.Save(wPath + "\\" + saveFileName);
// 썸네일 작업
// 썸네일 폭
int thumW = 100;
// 썸네일 높이
int thumH = 100;
// 썸네일 좌표 X
int thumX = 0;
// 썸네일 좌표 Y
int thumY = 0;
// 썸네일 이미지 그리기전 사이즈 지정
Bitmap thumimg = new Bitmap(thumW, thumH);
if (img.Width >= thumW && img.Height >= thumH)
{
if (img.Width >= img.Height)
{
thumW = (thumH * img.Width) / img.Height;
thumX = (thumW - thumH) / 2;
thumY = 0;
}
else
{
thumH = (thumW * img.Height) / img.Width;
thumY = (thumH - thumW) / 2;
thumX = 0;
}
}
else if (img.Width >= img.Height && img.Height < thumH)
{
thumW = img.Width;
thumH = img.Height;
thumX = (img.Width - thumW) / 2;
thumY = (img.Height - thumH) / 2 * -1;
}
else if (img.Width < img.Height && img.Height >= thumH)
{
thumW = img.Width;
thumH = img.Height;
thumX = (img.Width - thumW) / 2 * -1;
thumY = (img.Height - thumH) / 2;
}
else
{
thumW = img.Width;
thumH = img.Height;
thumX = (img.Width - thumW) / 2 * -1;
thumY = (img.Height - thumH) / 2 * -1;
}
Graphics gp = Graphics.FromImage(thumimg);
gp.InterpolationMode = InterpolationMode.HighQualityBicubic;
gp.DrawImage(img, new Rectangle(-thumX, -thumY, thumW, thumH));
// 썸네일 저장
thumimg.Save(wPath + "\\thum\\" + saveFileName);
}
else
{
// 이미지가 아닐경우
// 저장하기
SaveFile.SaveAs(wPath + "\\" + saveFileName);
}
}
catch
{
return "";
}
return saveFileName;
}
}
15. 12. 29.
C# MP3 파일에서 정보불러오기 및 앨범아트 추출
UltraID3Lib.dll 를 참조에 추가
string Mp3filePath = @"e:\파일명.mp3";
FileInfo tempMp3 = new FileInfo(Mp3filePath);
// UltraID3 객체생성
UltraID3 myFile = new UltraID3();
// HEADER 정보 불러오기
myFile.Read(tempMp3.FullName);
Console.WriteLine("Artist : " + myFile.ID3v2Tag.Artist);
Console.WriteLine("Title : " + myFile.ID3v2Tag.Title);
Console.WriteLine("Duration : " + myFile.Duration.ToString());
Bitmap mpImgBitmap;
// 앨범아트로 저장할 이미지명
string AlbumArtFileName = "image.png";
// 저장할 경로
string AlbumArtFilePath = @"e:\" + AlbumArtFileName;
ID3FrameCollection myFrames = myFile.ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture);
try
{
mpImgBitmap = ((ID3v23PictureFrame)myFrames[0]).Picture;
mpImgBitmap.Save(AlbumArtFilePath, System.Drawing.Imaging.ImageFormat.Png);
}
catch
{
Console.WriteLine("noImage");
}
13. 8. 10.
안드로이드 C#.NET PUSH 서버
push.aspx 파일
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="push.aspx.cs" Inherits="mobile_push" %>
<!DOCTYPE html>
<html>
<head>
<title>푸쉬 전송 TEST</title>
</head>
<body>
<asp:Literal ID="SendResult" runat="server" />
</body>
</html>
push.aspx.cs 파일
using System;
using System.Net.Security;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography.X509Certificates;
public partial class mobile_push : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 브라우저APIkey
string BrowserAPIKey = Request.QueryString["ApiKey"];
// BrowserAPIKey = "AIzaSyBi0pn1ckaJhRL9kK3mbwsHzk7x0fdE_Z8";
// regId(받을사람이 지급받은 registration_ids - 여러명일 경우 배열로 받아처리하면 될 듯 최대 1000)
string RegId = Request.QueryString["RegId"];
// RegId = "APA91bFNkzpbgBJnWkDgyGmU0XsF8ZLMAEhVaAtcbf9po8_i1GoA4JNt4HiUc6xScBMEOoJMIHHybZECIns9e2EF4AGalfOgZqwmQIEUG1UpVk08nTapx0iY17vOELD_9wIQTUdRwUsR";
// 알림명
string tickerText = Request.QueryString["Ticker"];
// tickerText = "알림테스트";
// 알림 제목
string contentTitle = Request.QueryString["Title"];
// contentTitle = "알림제목";
// 알림 내용
string message = Request.QueryString["Msg"];
// message = "안녕하세요~~~푸쉬입니다.";
string postData = "";
postData += "{";
postData += " \"registration_ids\": [ \"" + RegId + "\" ]";
postData += ", \"data\": {";
postData += " \"tickerText\":\"" + tickerText + "\"";
postData += " , \"contentTitle\":\"" + contentTitle + "\"";
postData += " , \"message\": \"" + message + "\"";
postData += " }";
postData += "}";
string response = SendGCMNotification(BrowserAPIKey, postData);
SendResult.Text = response;
}
private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
Console.Write(text);
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
Console.Write(text);
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "Error";
}
public static bool ValidateServerCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
13. 5. 29.
C# DNS로 아이피 알아내기
using System;
using System.Net;
namespace cShapNslookup
{
class Program
{
static void Main(string[] args)
{
string HostName = "";
HostName = "www.naver.com";
//실제 name 을 가져오기 위해 IPHostEntry을 이용
IPHostEntry hostEntry = Dns.GetHostByName(HostName);
Console.WriteLine("실제이름 : " + hostEntry.HostName + "");
//IP 주소를 찾아서 출력함
foreach (IPAddress ip in hostEntry.AddressList)
{
Console.WriteLine(ip.ToString());
}
}
}
}
13. 5. 14.
C# 컴퓨터 재부팅 및 끄기
프로젝트 << 참조 << .NET << System.Management 추가
나머지는 알아서 추가 ㅡ.ㅡ;;
나머지는 알아서 추가 ㅡ.ㅡ;;
public partial class Form1 : Form
{
[DllImport("user32.Dll")]
public static extern int SystemParametersInfo(int uAction, int uparam, string lpvParam, int fuWinIni);
public Form1()
{
InitializeComponent();
}
public enum ShutDown
{
LogOff = 0,
Shutdown = 1,
Reboot = 2,
ForcedLogOff = 4,
ForcedShutdown = 5,
ForcedReboot = 6,
PowerOff = 8,
ForcedPowerOff = 12
}
private void button1_Click(object sender, EventArgs e)
{
// 컴퓨터 재시작
// shutDown(ShutDown.ForcedReboot);
// 컴퓨터 끄기
// shutDown(ShutDown.ForcedShutdown);
}
// 끄기모드
private void shutDown(ShutDown flag)
{
ManagementBaseObject outParam = null;
ManagementClass sysOS = new ManagementClass("Win32_OperatingSystem");
sysOS.Get();
// enables required security privilege.
sysOS.Scope.Options.EnablePrivileges = true;
// get our in parameters
ManagementBaseObject inParams = sysOS.GetMethodParameters("Win32Shutdown");
// pass the flag of 0 = System Shutdown
inParams["Flags"] = flag;
inParams["Reserved"] = "0";
foreach (ManagementObject manObj in sysOS.GetInstances())
{
outParam = manObj.InvokeMethod("Win32Shutdown", inParams, null);
}
}
}
피드 구독하기:
덧글 (Atom)