SELECT * into [backup_db].[dbo].[migrations]
FROM original_db.dbo.__MigrationHistory
after error
insert into original.dbo.__MigrationHistory
select * from [backup_db].[dbo].[migrations]
Showing posts with label C# Apps. Show all posts
Showing posts with label C# Apps. Show all posts
Wednesday, December 28, 2016
how to use EntityFramework in WinForms application beginning
/*WinForms application, EntityFramework ашиглах жишээ*/
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Database.SetInitializer<DbContextCurrentAssets>(new DbContextCurrentAssetsInitializer());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetCompatibleTextRenderingDefault(false);
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.UserSkins.BonusSkins.Register();
UserLookAndFeel.Default.SetSkinStyle("DevExpress Style");//Money Twins//DevExpress Style
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.UserSkins.BonusSkins.Register();
UserLookAndFeel.Default.SetSkinStyle("DevExpress Style");//Money Twins//DevExpress Style
Application.Run(new frmLogin());
}
}
}
}
/*********************************************************************************************************************************/
namespace HO.CURRENT.ASSETS
{
/// <summary>
/// DbContextCurrentAssets -г үүсгэсний дараа Seed дуудагдаж өгөгдөл дээрх анхны утгыг оруулах
/// боломжтой болох ба DropCreateDatabaseIfModelChanges шалтгаалж дахин програмд дуудагдахгүй.
/// </summary>
public class DbContextCurrentAssetsInitializer : DropCreateDatabaseIfModelChanges<DbContextCurrentAssets>
{
protected override void Seed(DbContextCurrentAssets context)
{
base.Seed(context);
namespace HO.CURRENT.ASSETS
{
/// <summary>
/// DbContextCurrentAssets -г үүсгэсний дараа Seed дуудагдаж өгөгдөл дээрх анхны утгыг оруулах
/// боломжтой болох ба DropCreateDatabaseIfModelChanges шалтгаалж дахин програмд дуудагдахгүй.
/// </summary>
public class DbContextCurrentAssetsInitializer : DropCreateDatabaseIfModelChanges<DbContextCurrentAssets>
{
protected override void Seed(DbContextCurrentAssets context)
{
base.Seed(context);
DbDefaultData.Initializer(context);
}
}
/// <summary>
/// DbHelper = new DbHelper<DbContextCurrentAssets>(serverName);
/// int ret = DbHelper.list<UserInfo>().Count();
/// Үед хамгийн түрүүнд дуудагдах ба DropCreateDatabaseIfModelChanges ямар байхаас шалтгаална.
/// </summary>
public class DbContextCurrentAssets : DbContext
{
public DbContextCurrentAssets()
: base(AppConfig.GetConnectionString("."))
{
}
}
}
/// <summary>
/// DbHelper = new DbHelper<DbContextCurrentAssets>(serverName);
/// int ret = DbHelper.list<UserInfo>().Count();
/// Үед хамгийн түрүүнд дуудагдах ба DropCreateDatabaseIfModelChanges ямар байхаас шалтгаална.
/// </summary>
public class DbContextCurrentAssets : DbContext
{
public DbContextCurrentAssets()
: base(AppConfig.GetConnectionString("."))
{
}
public DbContextCurrentAssets(string connStr)
: base(connStr)
{
}
: base(connStr)
{
}
/// <summary>
/// TContext db = instance();
/// DbSet sets = db.Set(typeof(TEntity));
/// IQueryable<TEntity> list = sets.OfType<TEntity>();
/// Үед байнга дуудагдаж ажиллана.
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
/// TContext db = instance();
/// DbSet sets = db.Set(typeof(TEntity));
/// IQueryable<TEntity> list = sets.OfType<TEntity>();
/// Үед байнга дуудагдаж ажиллана.
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null
&& type.BaseType.IsGenericType
&& type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null
&& type.BaseType.IsGenericType
&& type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
//...or do it manually below. For example,
//modelBuilder.Configurations.Add(new UserMap());
//modelBuilder.Configurations.Add(new RoleMap());
//modelBuilder.Configurations.Add(new UserMap());
//modelBuilder.Configurations.Add(new RoleMap());
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
public DbSet<CountryInfo> CountryInfoes { get; set; }
public DbSet<CityInfo> CityInfoes { get; set; }
public DbSet<SexInfo> SexInfoes { get; set; }
public DbSet<UnitInfo> UnitInfoes { get; set; }
public DbSet<CityInfo> CityInfoes { get; set; }
public DbSet<SexInfo> SexInfoes { get; set; }
public DbSet<UnitInfo> UnitInfoes { get; set; }
public DbSet<UserInfo> UserInfoes { get; set; }
public DbSet<RoleInfo> RoleInfoes { get; set; }
public DbSet<UserRoleInfo> UserRoleInfoes { get; set; }
public DbSet<RoleWindowInfo> RoleWindowInfoes { get; set; }
..........................
..........................
}
}
public DbSet<RoleInfo> RoleInfoes { get; set; }
public DbSet<UserRoleInfo> UserRoleInfoes { get; set; }
public DbSet<RoleWindowInfo> RoleWindowInfoes { get; set; }
..........................
..........................
}
}
/****************************************************************************************************/
хэрэв connStr ээ өөрсдөө нууцлан (_ConnectionString дэх user, pass аа нууц файлаас авч) generate ( учир нь апп програм аль ч ком дээр суух учир db,user,pass аа нууцлах шаардлагатай ) хийх бол нэг иймэрхүү функц ашиглаж болно.!
private TContext instance()
{
if (_ContextObject is DbContext)
{
return _ContextObject;
}
try
{
Type type = typeof(TContext);
Assembly assembly = type.Assembly;
ConstructorInfo[] ConstructorInformation = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
object[] args = new object[] { _ConnectionString };
_ContextObject = (TContext)assembly.CreateInstance(type.FullName, true
, BindingFlags.Instance | BindingFlags.Public
, null, args, System.Globalization.CultureInfo.CurrentCulture
, null);
return _ContextObject;
}
catch (Exception ex)
{
MessageBox.Show("Өгөгдлийн сангийн класс үүсгэх үед асуудал гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
, "Системийн Алдаа (DbHelper.instance)", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
{
if (_ContextObject is DbContext)
{
return _ContextObject;
}
try
{
Type type = typeof(TContext);
Assembly assembly = type.Assembly;
ConstructorInfo[] ConstructorInformation = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
object[] args = new object[] { _ConnectionString };
_ContextObject = (TContext)assembly.CreateInstance(type.FullName, true
, BindingFlags.Instance | BindingFlags.Public
, null, args, System.Globalization.CultureInfo.CurrentCulture
, null);
return _ContextObject;
}
catch (Exception ex)
{
MessageBox.Show("Өгөгдлийн сангийн класс үүсгэх үед асуудал гарлаа!\r\n\r\nАлдааны текст: " + ex.Message
, "Системийн Алдаа (DbHelper.instance)", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
<connectionStrings>
<add name="DbContextCurrentAssets" connectionString="Data Source={0};Initial Catalog=DbCurrentAssets;User ID={1};Password={2};MultipleActiveResultSets=True;Pooling=false" providerName="System.Data.SqlClient" />
</connectionStrings>
<add name="DbContextCurrentAssets" connectionString="Data Source={0};Initial Catalog=DbCurrentAssets;User ID={1};Password={2};MultipleActiveResultSets=True;Pooling=false" providerName="System.Data.SqlClient" />
</connectionStrings>
Devexpress show ContextMenu in GridView Item
ContextMenuStrip cms = new ContextMenuStrip();
ToolStripItem tsi = new ToolStripMenuItem("Мэдээлэл", null, (s, e) =>
{
if (DataModel != null)
{
GridItemMetaInfo f = new GridItemMetaInfo(DataModel);
f.Show();
}
});
cms.Items.Add(tsi);
GridItemContextMenu = cms;
/*GridView*/
private void Grd_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
{
showGridItemContextMenu((GridView)sender);
}
private void showGridItemContextMenu(GridView view)
{
if (view.FocusedColumn == null) return;
int ri = view.FocusedRowHandle;
int vi = view.FocusedColumn.VisibleIndex;
GridViewInfo info = (GridViewInfo)view.GetViewInfo();
GridCellInfo cell = info.GetGridCellInfo(ri, view.FocusedColumn);
System.Drawing.Rectangle r = cell.Bounds;
System.Drawing.Point point = new System.Drawing.Point(r.X + r.Width, r.Y + r.Height);
GridItemContextMenu.Show(view.GridControl, point);
}
private void showGridItemContextMenu(GridView view, System.Drawing.Point location)
{
GridHitInfo hitInfo = view.CalcHitInfo(location);
if (hitInfo.InRow)
{
view.FocusedRowHandle = hitInfo.RowHandle;
GridItemContextMenu.Show(view.GridControl, location);
}
}
ToolStripItem tsi = new ToolStripMenuItem("Мэдээлэл", null, (s, e) =>
{
if (DataModel != null)
{
GridItemMetaInfo f = new GridItemMetaInfo(DataModel);
f.Show();
}
});
cms.Items.Add(tsi);
GridItemContextMenu = cms;
/*GridView*/
private void Grd_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
{
showGridItemContextMenu((GridView)sender);
}
private void showGridItemContextMenu(GridView view)
{
if (view.FocusedColumn == null) return;
int ri = view.FocusedRowHandle;
int vi = view.FocusedColumn.VisibleIndex;
GridViewInfo info = (GridViewInfo)view.GetViewInfo();
GridCellInfo cell = info.GetGridCellInfo(ri, view.FocusedColumn);
System.Drawing.Rectangle r = cell.Bounds;
System.Drawing.Point point = new System.Drawing.Point(r.X + r.Width, r.Y + r.Height);
GridItemContextMenu.Show(view.GridControl, point);
}
private void showGridItemContextMenu(GridView view, System.Drawing.Point location)
{
GridHitInfo hitInfo = view.CalcHitInfo(location);
if (hitInfo.InRow)
{
view.FocusedRowHandle = hitInfo.RowHandle;
GridItemContextMenu.Show(view.GridControl, location);
}
}
Thursday, April 16, 2015
How to send an xml from a c# desktop application to a php server script and parse it?
c#
public partial class frmSending : Form
{
public frmSending(string url, string file, XmlDocument xml)
{
InitializeComponent();
this.Url = url;
this.XmlFile = file;
this.Xml = xml;
this.Sent += frmSending_Sent;
}
void frmSending_Sent(object sender, EventArgs e)
{
if (this.Ex != null)
{
MessageBox.Show(Ex.Message, "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("Амжилттай илгээлээ!", "Мэдэгдэл", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
this.Close();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
thread = new Thread(post_to_internet);
thread.Start();
}
private void post_to_internet()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/xml";
request.Accept = "application/xml";
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
Xml.WriteTo(xmlTextWriter);
byte[] bytes = Encoding.UTF8.GetBytes(stringWriter.ToString());
request.ContentLength = bytes.Length;
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
// Log the response from Redmine RESTful service
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
this.Invoke(Sent, new object[] { reader.ReadLine(), EventArgs.Empty });
}
//using (WebClient request = new WebClient())
//{
// request.UploadFile(Url, "POST", XmlFile);
//}
}
catch (Exception ex)
{
this.Ex = ex;
this.Invoke(Sent, new object[] { ex, EventArgs.Empty });
}
}
public string Url { get; set; }
public string XmlFile { get; set; }
public XmlDocument Xml { get; set; }
private Thread thread { get; set; }
private event EventHandler Sent;
public Exception Ex { get; set; }
private void frmSending_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape || e.KeyCode == Keys.F1)
{
thread.Abort();
}
}
}
<?php
include "db.config.php";
debug_log('uploaded ' . $fp);
$fp = fopen('php://input', 'rb');
file_put_contents('report.xml', $fp);
//$upload = isset($_FILES) ? reset($_FILES) : null;
//debug_log('uploaded ' . $upload['tmp_name']);
//move_uploaded_file($upload['tmp_name'], $upload['name']);
afterwards the file test.dat on the server contains
<?xml version="1.0" encoding="utf-8"?>
<Foo>
<bar>
<type>System.String</type>
<value>Stackoverflow</value>
</bar>
<bar>
<type>System.Boolean</type>
<value>True</value>
</bar>
<bar>
<type>System.Char</type>
<value>x</value>
</bar>
<bar>
<type>System.Int32</type>
<value>42</value>
</bar>
</Foo>
Wednesday, April 15, 2015
set system variables using c#
using System; public class Example { public static void Main() { String envName = "AppDomain"; String envValue = "True"; // Determine whether the environment variable exists. if (Environment.GetEnvironmentVariable(envName) == null) // If it doesn't exist, create it. Environment.SetEnvironmentVariable(envName, envValue); bool createAppDomain; Message msg; if (Boolean.TryParse(Environment.GetEnvironmentVariable(envName), out createAppDomain) && createAppDomain) { AppDomain domain = AppDomain.CreateDomain("Domain2"); msg = (Message) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, "Message"); msg.Display(); } else { msg = new Message(); msg.Display(); } } } public class Message : MarshalByRefObject { public void Display() { Console.WriteLine("Executing in domain {0}", AppDomain.CurrentDomain.FriendlyName); } }
Saturday, April 11, 2015
c# ExcelExport from gridview or dataset
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
namespace HiimelOyun.App.Lib.Utils.Export
{
public class ExcelExport
{
public static void toExcel(string filename, Control control)
{
if (control is GridControl)
{
GridView gridView = (GridView)((GridControl)control).MainView;
toExcel(filename, gridView, null);
}
else if (control is ListView)
{
toExcel(filename, (ListView)control, null);
}
}
public static void toExcel(string filename, GridView gridView, DataSet ds)
{
int row = 1;
int col = 1;
int tableIndex = 0;
int colLength = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = null;
Microsoft.Office.Interop.Excel.Range Cel = null;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
if (ds == null)
{
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
colLength = gridView.Columns.Count;
GridColumn column = null;
for (int i = 0; i < gridView.DataRowCount; i++)
{
if (row == 2) i = 0;
object item = gridView.GetRow(i);
for (col = 1; col <= colLength; )
{
column = gridView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Caption;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = column.Width / 4.5;
}
else
{
try
{
xlWorkSheet.Cells[row, col] = "" + AppUtil.GetPropertyValue(item, column.FieldName);
}
catch { }
}
col++;
}
row++;
}
}
else
for (tableIndex = 0; tableIndex < ds.Tables.Count; tableIndex++)
{
DataTable dt = ds.Tables[tableIndex];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
if (gridView != null && gridView.Columns.Count > 0)
{
colLength = gridView.Columns.Count;
GridColumn column = null;
for (int i = 0; i < gridView.DataRowCount; i++)
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = gridView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Caption;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.Caption).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.FieldName];
}
col++;
}
row++;
}
}
else
{
colLength = dt.Columns.Count;
DataColumn column = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = dt.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.ColumnName;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.ColumnName).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.ColumnName];
}
col++;
}
row++;
}
}
}
xlWorkBook.SaveAs(filename
, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal
, misValue, misValue, misValue, misValue
, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive
, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Process p;
ProcessStartInfo pInfo;
try
{
pInfo = new ProcessStartInfo();
pInfo.Verb = "open";
pInfo.FileName = filename;
pInfo.UseShellExecute = true;
pInfo.WindowStyle = ProcessWindowStyle.Maximized;
p = Process.Start(pInfo);
}
catch { }
}
public static void toExcel(string filename, ListView listView, DataSet ds)
{
int row = 1;
int col = 1;
int tableIndex = 0;
int colLength = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = null;
Microsoft.Office.Interop.Excel.Range Cel = null;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
if (ds == null)
{
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
colLength = listView.Columns.Count;
ColumnHeader column = null;
for (int i = 0; i < listView.Items.Count; i++ )
{
if (row == 2) i = 0;
ListViewItem li = listView.Items[i];
for (col = 1; col <= colLength; )
{
column = listView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Text;
Cel = (Microsoft.Office.Interop.Excel.Range) xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = column.Width / 4.5;
}
else
{
try
{
if (col == 1)
xlWorkSheet.Cells[row, col] = "" + li.Text;
else
xlWorkSheet.Cells[row, col] = "" + li.SubItems[col - 1].Text;
}
catch { }
}
col++;
}
row++;
}
}
else
for (tableIndex = 0; tableIndex < ds.Tables.Count; tableIndex++)
{
DataTable dt = ds.Tables[tableIndex];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
if (listView != null && listView.Columns.Count > 0)
{
colLength = listView.Columns.Count;
ColumnHeader column = null;
for (int i = 0; i < listView.Items.Count; i++ )
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = listView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Text;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.Text).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.Tag.ToString()];
}
col++;
}
row++;
}
}
else
{
colLength = dt.Columns.Count;
DataColumn column = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = dt.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.ColumnName;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.ColumnName).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.ColumnName];
}
col++;
}
row++;
}
}
}
xlWorkBook.SaveAs(filename
, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal
, misValue, misValue, misValue, misValue
, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive
, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Process p;
ProcessStartInfo pInfo;
try
{
pInfo = new ProcessStartInfo();
pInfo.Verb = "open";
pInfo.FileName = filename;
pInfo.UseShellExecute = true;
pInfo.WindowStyle = ProcessWindowStyle.Maximized;
p = Process.Start(pInfo);
}
catch { }
}
public static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
namespace HiimelOyun.App.Lib.Utils.Export
{
public class ExcelExport
{
public static void toExcel(string filename, Control control)
{
if (control is GridControl)
{
GridView gridView = (GridView)((GridControl)control).MainView;
toExcel(filename, gridView, null);
}
else if (control is ListView)
{
toExcel(filename, (ListView)control, null);
}
}
public static void toExcel(string filename, GridView gridView, DataSet ds)
{
int row = 1;
int col = 1;
int tableIndex = 0;
int colLength = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = null;
Microsoft.Office.Interop.Excel.Range Cel = null;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
if (ds == null)
{
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
colLength = gridView.Columns.Count;
GridColumn column = null;
for (int i = 0; i < gridView.DataRowCount; i++)
{
if (row == 2) i = 0;
object item = gridView.GetRow(i);
for (col = 1; col <= colLength; )
{
column = gridView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Caption;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = column.Width / 4.5;
}
else
{
try
{
xlWorkSheet.Cells[row, col] = "" + AppUtil.GetPropertyValue(item, column.FieldName);
}
catch { }
}
col++;
}
row++;
}
}
else
for (tableIndex = 0; tableIndex < ds.Tables.Count; tableIndex++)
{
DataTable dt = ds.Tables[tableIndex];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
if (gridView != null && gridView.Columns.Count > 0)
{
colLength = gridView.Columns.Count;
GridColumn column = null;
for (int i = 0; i < gridView.DataRowCount; i++)
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = gridView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Caption;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.Caption).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.FieldName];
}
col++;
}
row++;
}
}
else
{
colLength = dt.Columns.Count;
DataColumn column = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = dt.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.ColumnName;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.ColumnName).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.ColumnName];
}
col++;
}
row++;
}
}
}
xlWorkBook.SaveAs(filename
, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal
, misValue, misValue, misValue, misValue
, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive
, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Process p;
ProcessStartInfo pInfo;
try
{
pInfo = new ProcessStartInfo();
pInfo.Verb = "open";
pInfo.FileName = filename;
pInfo.UseShellExecute = true;
pInfo.WindowStyle = ProcessWindowStyle.Maximized;
p = Process.Start(pInfo);
}
catch { }
}
public static void toExcel(string filename, ListView listView, DataSet ds)
{
int row = 1;
int col = 1;
int tableIndex = 0;
int colLength = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = null;
Microsoft.Office.Interop.Excel.Range Cel = null;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
if (ds == null)
{
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
colLength = listView.Columns.Count;
ColumnHeader column = null;
for (int i = 0; i < listView.Items.Count; i++ )
{
if (row == 2) i = 0;
ListViewItem li = listView.Items[i];
for (col = 1; col <= colLength; )
{
column = listView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Text;
Cel = (Microsoft.Office.Interop.Excel.Range) xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = column.Width / 4.5;
}
else
{
try
{
if (col == 1)
xlWorkSheet.Cells[row, col] = "" + li.Text;
else
xlWorkSheet.Cells[row, col] = "" + li.SubItems[col - 1].Text;
}
catch { }
}
col++;
}
row++;
}
}
else
for (tableIndex = 0; tableIndex < ds.Tables.Count; tableIndex++)
{
DataTable dt = ds.Tables[tableIndex];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(tableIndex + 1);
if (listView != null && listView.Columns.Count > 0)
{
colLength = listView.Columns.Count;
ColumnHeader column = null;
for (int i = 0; i < listView.Items.Count; i++ )
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = listView.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.Text;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.Text).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.Tag.ToString()];
}
col++;
}
row++;
}
}
else
{
colLength = dt.Columns.Count;
DataColumn column = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (row == 2) i = 0;
DataRow dr = dt.Rows[i];
for (col = 1; col <= colLength; )
{
column = dt.Columns[col - 1];
if (row == 1)
{
xlWorkSheet.Cells[row, col] = "" + column.ColumnName;
Cel = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[row, col];
Cel.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous
, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin
, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic
, 1);
Cel.Interior.Color = ColorTranslator.ToOle(Color.Silver);
Cel.Font.Color = ColorTranslator.ToOle(Color.Black);
Cel.Font.Bold = true;
Cel.ColumnWidth = ("" + column.ColumnName).Length * 4.5;
}
else
{
xlWorkSheet.Cells[row, col] = "" + dr[column.ColumnName];
}
col++;
}
row++;
}
}
}
xlWorkBook.SaveAs(filename
, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal
, misValue, misValue, misValue, misValue
, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive
, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Process p;
ProcessStartInfo pInfo;
try
{
pInfo = new ProcessStartInfo();
pInfo.Verb = "open";
pInfo.FileName = filename;
pInfo.UseShellExecute = true;
pInfo.WindowStyle = ProcessWindowStyle.Maximized;
p = Process.Start(pInfo);
}
catch { }
}
public static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
CREATE PROCEDURE for insert for c# nonexecutequery
CREATE PROCEDURE sp_insertemployee
@FirstName nvarchar(10),
@LastName nvarchar(20),
@Title nvarchar(30),
@Notes nvarchar(200),
@PK_New int OUTPUT
AS
INSERT INTO Employees(FirstName,LastName,Title,Notes)
VALUES (@FirstName,@LastName,@Title,@Notes)
SELECT @PK_New = @@IDENTITY
RETURN (1)
GO
---------------------------------------------------------------
IF ( OBJECT_ID('dbo.sp_Students_INS_byPK') IS NOT NULL ) DROP PROCEDURE dbo.sp_Students_INS_byPK GO CREATE PROCEDURE dbo.sp_Students_INS_byPK @student_id INT , @password VARCHAR(15) = NULL , @active_flg TINYINT , @lastname VARCHAR(30) = NULL , @birth_dttm DATETIME = NULL , @gpa INT = NULL , @is_on_staff TINYINT AS BEGIN SET NOCOUNT ON INSERT INTO dbo.Students ( student_id , password , active_flg , lastname , birth_dttm , gpa , is_on_staff ) VALUES ( @student_id , @password , @active_flg , @lastname , @birth_dttm , @gpa , @is_on_staff ) END GO----------------------------------------------------------------------
EXECUTE [dbo].[spINSERT_dbo_Customer] @FirstName = 'Tommy' ,@LastName = 'Crabber' ,@PhoneNumber = '333-333-3333' ,@EmailAddress = 'tommy@KingCrabber.com' ,@Priority = 1 ,@CreateDate = '2011-09-15' GO
c# draw string with line margin, font brush to PrintDocument from text file
using System; using System.IO; using System.Drawing; using System.Drawing.Printing; using System.Windows.Forms; public partial class Form1 : System.Windows.Forms.Form { private System.ComponentModel.Container components; private System.Windows.Forms.Button printButton; private Font printFont; private StreamReader streamToPrint; public Form1() { // The Windows Forms Designer requires the following call. InitializeComponent(); } // The Click event is raised when the user clicks the Print button. private void printButton_Click(object sender, EventArgs e) { try { streamToPrint = new StreamReader ("C:\\My Documents\\MyFile.txt"); try { printFont = new Font("Arial", 10); PrintDocument pd = new PrintDocument(); pd.PrintPage += new PrintPageEventHandler (this.pd_PrintPage); pd.Print(); } finally { streamToPrint.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } // The PrintPage event is raised for each page to be printed. private void pd_PrintPage(object sender, PrintPageEventArgs ev) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; string line = null; // Calculate the number of lines per page. linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); // Print each line of the file. while (count < linesPerPage && ((line = streamToPrint.ReadLine()) != null)) { yPos = topMargin + (count * printFont.GetHeight(ev.Graphics)); ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat()); count++; } // If more lines exist, print another page. if (line != null) ev.HasMorePages = true; else ev.HasMorePages = false; } // The Windows Forms Designer requires the following procedure. private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.printButton = new System.Windows.Forms.Button(); this.ClientSize = new System.Drawing.Size(504, 381); this.Text = "Print Example"; printButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; printButton.Location = new System.Drawing.Point(32, 110); printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; printButton.TabIndex = 0; printButton.Text = "Print the file."; printButton.Size = new System.Drawing.Size(136, 40); printButton.Click += new System.EventHandler(printButton_Click); this.Controls.Add(printButton); } }
c# datatable column Expression to set examples
DataSet1.Tables("Orders").Columns("OrderCount").Expression = "Count(OrderID)"
private void CalcColumns() { DataTable table = new DataTable (); // Create the first column. DataColumn priceColumn = new DataColumn(); priceColumn.DataType = System.Type.GetType("System.Decimal"); priceColumn.ColumnName = "price"; priceColumn.DefaultValue = 50; // Create the second, calculated, column. DataColumn taxColumn = new DataColumn(); taxColumn.DataType = System.Type.GetType("System.Decimal"); taxColumn.ColumnName = "tax"; taxColumn.Expression = "price * 0.0862"; // Create third column. DataColumn totalColumn = new DataColumn(); totalColumn.DataType = System.Type.GetType("System.Decimal"); totalColumn.ColumnName = "total"; totalColumn.Expression = "price + tax"; // Add columns to DataTable. table.Columns.Add(priceColumn); table.Columns.Add(taxColumn); table.Columns.Add(totalColumn); DataRow row = table.NewRow(); table.Rows.Add(row); DataView view = new DataView(table); dataGrid1.DataSource = view; }
Wednesday, January 14, 2015
how to convert video file to types using ffmpeg library
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace boroo.ffmpeg.example
{
class Program
{
const string InputDir = @"E:\\inputs\\";
const string OutputDir = @"E:\\outputs\\";
const string FFmpegPath = @"C:\\ffmpeg\\bin\\ffmpeg.exe";
bool isCompleted = false;
List<Process> processList = new List<Process>();
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Program p = new Program();
p.start(args);
Console.ReadLine();
}
public void start(string[] args)
{
string dirPath = InputDir;
if (args != null && args.Length > 0)
{
dirPath = args[0];
}
Thread thread = null;
while (!isCompleted)
{
if (thread == null)
{
thread = new Thread(convertProcess);
thread.Start(dirPath);
}
Thread.Sleep(2000);
}
}
// private method
private void convertProcess(object param)
{
isCompleted = false;
Console.WriteLine("Хөрвүүлэлт эхэллээ.");
string dirPath = (string)param;
DirectoryInfo dir = new DirectoryInfo(dirPath);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
convertFile(file);
}
isCompleted = true;
killInterruptProcess();
Console.WriteLine("Хөрвүүлэлт дууслаа.");
}
private void convertFile(FileInfo file)
{
string fileTitle = Path.GetFileNameWithoutExtension(file.Name);
string extension = file.Extension;
string srcFilePath = file.FullName;
if (extension == ".mp4" || extension == ".avi")
{
Console.WriteLine("===========================================================================");
Console.WriteLine("Хөрвүүлэх файл олдлоо: '{0}'.", file.Name);
String destPath = OutputDir + fileTitle;
try
{
Process proc1 = createProcess(srcFilePath, destPath, "webm");
processList.Add(proc1);
proc1.WaitForExit();
proc1.Close();
processList.Remove(proc1);
if (extension == ".avi")
{
Process proc2 = createProcess(srcFilePath, destPath, "mp4");
processList.Add(proc2);
proc2.WaitForExit();
proc2.Close();
processList.Add(proc2);
}
}
catch (Exception ex)
{
Console.WriteLine("Алдаа: '{0}'.", ex.Message);
killInterruptProcess();
}
Console.WriteLine("Файлыг хөрвүүлж дууслаа: '{0}'.", file.Name);
Console.WriteLine("===========================================================================");
}
else
{
Console.WriteLine("Хөрвүүлэх шаардлагад нийцэхгүй файл олдлоо.");
Console.WriteLine("Файлыг устгаж байна. '{0}'.", file.FullName);
File.Delete(file.FullName);
}
}
void killInterruptProcess()
{
foreach(Process p in processList)
{
try
{
p.Kill();
}
catch { }
}
processList.Clear();
}
Process createProcess(string srcFilePath, string destPath, string toType)
{
Process proc = new Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = FFmpegPath;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Arguments = "-i \"" + srcFilePath + "\" \""
+ destPath + (toType.StartsWith(".") ? toType : "." + toType) + "\" -y";
proc.Start();
return proc;
}
}
}
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace boroo.ffmpeg.example
{
class Program
{
const string InputDir = @"E:\\inputs\\";
const string OutputDir = @"E:\\outputs\\";
const string FFmpegPath = @"C:\\ffmpeg\\bin\\ffmpeg.exe";
bool isCompleted = false;
List<Process> processList = new List<Process>();
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Program p = new Program();
p.start(args);
Console.ReadLine();
}
public void start(string[] args)
{
string dirPath = InputDir;
if (args != null && args.Length > 0)
{
dirPath = args[0];
}
Thread thread = null;
while (!isCompleted)
{
if (thread == null)
{
thread = new Thread(convertProcess);
thread.Start(dirPath);
}
Thread.Sleep(2000);
}
}
// private method
private void convertProcess(object param)
{
isCompleted = false;
Console.WriteLine("Хөрвүүлэлт эхэллээ.");
string dirPath = (string)param;
DirectoryInfo dir = new DirectoryInfo(dirPath);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
convertFile(file);
}
isCompleted = true;
killInterruptProcess();
Console.WriteLine("Хөрвүүлэлт дууслаа.");
}
private void convertFile(FileInfo file)
{
string fileTitle = Path.GetFileNameWithoutExtension(file.Name);
string extension = file.Extension;
string srcFilePath = file.FullName;
if (extension == ".mp4" || extension == ".avi")
{
Console.WriteLine("===========================================================================");
Console.WriteLine("Хөрвүүлэх файл олдлоо: '{0}'.", file.Name);
String destPath = OutputDir + fileTitle;
try
{
Process proc1 = createProcess(srcFilePath, destPath, "webm");
processList.Add(proc1);
proc1.WaitForExit();
proc1.Close();
processList.Remove(proc1);
if (extension == ".avi")
{
Process proc2 = createProcess(srcFilePath, destPath, "mp4");
processList.Add(proc2);
proc2.WaitForExit();
proc2.Close();
processList.Add(proc2);
}
}
catch (Exception ex)
{
Console.WriteLine("Алдаа: '{0}'.", ex.Message);
killInterruptProcess();
}
Console.WriteLine("Файлыг хөрвүүлж дууслаа: '{0}'.", file.Name);
Console.WriteLine("===========================================================================");
}
else
{
Console.WriteLine("Хөрвүүлэх шаардлагад нийцэхгүй файл олдлоо.");
Console.WriteLine("Файлыг устгаж байна. '{0}'.", file.FullName);
File.Delete(file.FullName);
}
}
void killInterruptProcess()
{
foreach(Process p in processList)
{
try
{
p.Kill();
}
catch { }
}
processList.Clear();
}
Process createProcess(string srcFilePath, string destPath, string toType)
{
Process proc = new Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = FFmpegPath;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.Arguments = "-i \"" + srcFilePath + "\" \""
+ destPath + (toType.StartsWith(".") ? toType : "." + toType) + "\" -y";
proc.Start();
return proc;
}
}
}
Monday, August 18, 2014
c# socket library core class with usage chat e.g
- some using class -
public class ArrList
{
private ArrayList _Key = new ArrayList();
private ArrayList _Comment = new ArrayList();
private ArrayList _List = new ArrayList();
public object this[int index]
{
get { return _List[index]; }
}
public object this[string key]
{
get { return _List[_Key.IndexOf(key)]; }
}
public string this[object data]
{
get { return (string)_Key[_List.IndexOf(data)]; }
}
public int Count
{
get { return _List.Count; }
}
public int Length
{
get { return _List.Count; }
}
public bool Add(string key, object data, object comment)
{
if (_Key.IndexOf(key) < 0)
{
_List.Add(data);
_Comment.Add(comment);
_Key.Add(key);
return true;
}
else return false;
}
public bool Add(string key, object data)
{
if (_Key.IndexOf(key) < 0)
{
_List.Add(data);
_Comment.Add(null);
_Key.Add(key);
return true;
}
else return false;
}
public bool Add(object data)
{
if (_Key.IndexOf(_List.Count.ToString()) < 0)
{
_List.Add(data);
_Comment.Add(null);
_Key.Add((_List.Count - 1).ToString());
return true;
}
else return false;
}
public object Get(int index)
{
return _List[index];
}
public object Get(string key)
{
try
{
return _List[_Key.IndexOf(key)];
}
catch { return null; }
}
public string Get(object data)
{
try
{
return (string)_Key[_List.IndexOf(data)];
}
catch { return null; }
}
public bool Remove(object data)
{
int nd = _List.IndexOf(data);
if (nd < 0) return false;
else
{
_List.RemoveAt(nd);
_Comment.RemoveAt(nd);
_Key.RemoveAt(nd);
return true;
}
}
public bool Remove(string key)
{
int nd = _Key.IndexOf(key);
if (nd < 0) return false;
else
{
_List.RemoveAt(nd);
_Comment.RemoveAt(nd);
_Key.RemoveAt(nd);
return true;
}
}
public bool Remove(int index)
{
if (index < 0 || _List.Count <= index) return false;
else
{
_List.RemoveAt(index);
_Comment.RemoveAt(index);
_Key.RemoveAt(index);
return true;
}
}
public int IndexOf(string key)
{
return _Key.IndexOf(key);
}
public int IndexOf(object data)
{
return _List.IndexOf(data);
}
public void Clear()
{
_List.Clear();
_Comment.Clear();
_Key.Clear();
}
public ArrList()
{ }
}
namespace SocketLibraryCore
{
/// <summary>
/// Холбоосоор дамжих өгөгдлийг хүлээн авагч
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
public delegate void SocketHandler(ClientSocketJob sender, object data);
/// <summary>
/// Холбоосын үйлдэл бүрийг мэдэгдэгч
/// </summary>
/// <param name="sender"></param>
/// <param name="msg"></param>
public delegate void SocketMessageHandler(ClientSocketJob sender, SocketCommandBlock msg);
[Serializable]
public enum SocketDataAccess
{
Accept = 0,
Sent = 1,
Receive = 2,
ServerStop = 3,
ServerStart = 4,
ClientStop = 5,
ClientStart = 6,
Log = 7,
Error = 8
}
[Serializable]
public class SocketCommandBlock
{
public string DataCommand { get; set; }
public string DataString { get; set; }
public object DataBuffer { get; set; }
public long DataResult { get; set; }
public SocketDataAccess DataAccess { get; set; }
public SocketCommandBlock()
{
DataAccess = SocketDataAccess.Log;
}
}
/// <summary>
/// Сервер эсвэл клиент холболт
/// </summary>
public class SocketLib
{
#region Control Methods
public event SocketMessageHandler MsgRecieved;
public void CallMsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
if (MsgRecieved != null) MsgRecieved.Invoke(sender, msg);
}
public event SocketHandler DataRecieved;
public void CallDataRecieved(ClientSocketJob sender, object data)
{
if (DataRecieved != null) DataRecieved.Invoke(sender, data);
}
public int SendToClient(int index, object data)
{
var sender = (ClientSocketJob)_ClientList[index];
return SendToClient(sender, data);
}
public int SendToClient(ClientSocketJob sender, object data)
{
if (sender != null) return sender.DataSend(data);
else return 0;
}
public List<int> SendToAll(object data, ClientSocketJob ignoreJob = null)
{
List<int> list = new List<int>();
int l = _ClientList.Count;
for (int i = 0; i < l; i++)
{
var job = (_ClientList[i] as ClientSocketJob);
if (ignoreJob == null || job.JobIndex != ignoreJob.JobIndex)
{
var ret = SendToClient(job, data);
list.Add(ret);
}
}
return list;
}
public int SendToServer(object data)
{
//ClientSocketJob is bridge for server connection
return (_ClientList[0] as ClientSocketJob).DataSend(data);
}
public void Stop(ClientSocketJob sender, object data)
{
sender.Stop();
}
public void Stop()
{
if (_IsServer)
this.Desconnect();
else
{
if (_ClientList.Count > 0)
{
(_ClientList[0] as ClientSocketJob).Stop();
}
}
}
#endregion Control Methods
#region Properties
private bool _ClientDistinct = true;
public bool ClientDistinct
{
get { return _ClientDistinct; }
set { _ClientDistinct = value; }
}
private Thread _ServerThread;
private TcpListener _Server;
private string _HostName = "127.0.0.1";
public string HostName
{
get { return _HostName; }
}
private int _PortNumber = 1986;
public int PortNumber
{
get { return _PortNumber; }
}
private bool _IsServer;
public bool IsServer
{
get { return _IsServer; }
}
private bool _IsRunning;
public bool IsRunning
{
get { return _IsRunning; }
}
//
private ArrList _ClientList;
public ArrList ClientList
{
get { return _ClientList; }
}
public ClientSocketJob Me
{
get
{
return (_IsServer == true) ? null :
((_ClientList == null || _ClientList.Count == 0) ? null : (ClientSocketJob)_ClientList[0]);
}
}
private long _ClientJobCount;
public long ClientJobCount
{
get { return _ClientJobCount; }
}
#endregion Properties
/// <summary>
/// Сервер эсвэл клиент холболтын ажлын класс
/// </summary>
/// <param name="isServer">Сервер талын холбоос эсэх</param>
/// <param name="isDistinct">Клиент талын хаяг давхардах эсэх</param>
public SocketLib(bool isServer, bool isDistinct)
{
_ClientJobCount = 0;
_ClientList = new ArrList();
_IsServer = isServer;
_ClientDistinct = isDistinct;
}
/// <summary>
/// Холболтыг эхлүүлэх
/// </summary>
/// <param name="HostName"></param>
/// <param name="PortNumber"></param>
public void Connect(string HostName, int PortNumber)
{
if (_IsRunning == false)
{
_HostName = HostName;
_PortNumber = PortNumber;
if (_IsServer)
{
IPAddress ip = Dns.GetHostEntry(Environment.MachineName).AddressList[0];
_Server = new TcpListener(ip, _PortNumber);
_ServerThread = new Thread(new ThreadStart(this.serverProcess));
_ServerThread.Start();
}
else
{
TcpClient tcpclient = new TcpClient(_HostName, _PortNumber);
createClientSocketJob(tcpclient);
}
_IsRunning = true;
}
}
/// <summary>
/// Сервер эсвэл клиент холболтыг унтраана
/// </summary>
public void Desconnect()
{
if (_Server != null)
{
try { _Server.Stop(); }
catch (Exception ex) { ex.ToString(); }
_Server = null;
}
int l = _ClientList.Count;
for (int i = 0; i < l; i++)
{
try
{
(_ClientList[i] as ClientSocketJob).Stop();
}
catch { }
}
_ClientList.Clear();
_ClientJobCount = 0;
_IsRunning = false;
if (_ServerThread != null)
{
try { _ServerThread.Abort(); }
catch (Exception ex) { ex.ToString(); }
_ServerThread = null;
SocketCommandBlock cmd = new SocketCommandBlock();
if (_IsServer)
cmd.DataAccess = SocketDataAccess.ServerStop;
else
cmd.DataAccess = SocketDataAccess.ClientStop;
MsgRecieved.DynamicInvoke(new object[] { null, cmd });
}
}
/// <summary>
/// Аль нэг холбоосыг таслана
/// </summary>
/// <param name="job"></param>
public void RemoveJob(ClientSocketJob job)
{
try
{
_ClientList.Remove(job.JobIndex.ToString());
}
catch (Exception ex) { ex.ToString(); }
if (_IsServer == false && _ClientList.Count == 0) _IsRunning = false;
}
/// <summary>
/// Холболтыг чагнаж шинэ клиентийн холбоосыг бүртгэн авч цуглуулна
/// </summary>
private void serverProcess()
{
try
{
_Server.Start();
SocketCommandBlock cmd = new SocketCommandBlock();
cmd.DataAccess = SocketDataAccess.ServerStart;
MsgRecieved.DynamicInvoke(new object[] { null, cmd });
while (true)
{
try
{
TcpClient tcpclient = _Server.AcceptTcpClient();
cmd.DataAccess = SocketDataAccess.Accept;
MsgRecieved.DynamicInvoke(new object[] { null, cmd });
if (_ClientDistinct)
{
var prevJob = existsClientSocketJobByIP(tcpclient);
if (prevJob != null)
{
prevJob.Stop();
}
}
createClientSocketJob(tcpclient);
}
catch (Exception ex)
{
ex.ToString();
this.Desconnect();
}
finally
{
Thread.Sleep(10);
}
}
}
catch { }
}
/// <summary>
/// Клиентийн хаяг давхардсан эсэхийг шалгах
/// </summary>
/// <param name="tcp"></param>
/// <returns></returns>
private ClientSocketJob existsClientSocketJobByIP(TcpClient tcp)
{
IPEndPoint ipep = (IPEndPoint)tcp.Client.RemoteEndPoint;
string ip = ipep.Address.ToString();
int l = _ClientList.Count;
for (int i = 0; i < l; i++)
{
if ((_ClientList[i] as ClientSocketJob).IP == ip)
{
return (_ClientList[i] as ClientSocketJob);
}
}
return null;
}
/// <summary>
/// Шинэ холбоос үүсгэж байна
/// </summary>
/// <param name="tcpclient"></param>
private void createClientSocketJob(TcpClient tcpclient)
{
ClientSocketJob job = new ClientSocketJob(this, tcpclient, _ClientJobCount);
_ClientList.Add(job.JobIndex.ToString(), job);
_ClientJobCount++;
job.Start();
}
}
/// <summary>
/// Клиент холбоос
/// </summary>
public class ClientSocketJob
{
private string _IP;
public string IP
{
get { return _IP; }
set { _IP = value; }
}
private long _JobIndex;
public long JobIndex
{
get { return _JobIndex; }
}
private object _Tag;
public object Tag
{
get { return _Tag; }
set { _Tag = value; }
}
private object _Commit;
public object Commit
{
get { return _Commit; }
set { _Commit = value; }
}
private event SocketMessageHandler MsgRecieved;
private event SocketHandler DataRecieved;
private SocketLib _Main;
private TcpClient _Client;
public TcpClient Client
{
get { return _Client; }
set { _Client = value; }
}
private Thread _ClientThread;
/// <summary>
/// Клиент холбоосын ажлын класс
/// </summary>
/// <param name="main">Үндсэн класс</param>
/// <param name="tcpclient">Сокет клиент</param>
/// <param name="jobindex">Дугаар</param>
public ClientSocketJob(SocketLib main, TcpClient tcpclient, long jobindex)
{
IPEndPoint endp = (IPEndPoint)tcpclient.Client.RemoteEndPoint;
_IP = endp.Address.ToString();
_Main = main;
_Client = tcpclient;
_JobIndex = jobindex;
DataRecieved += new SocketHandler(ClientSocketJob_DataRecieved);
MsgRecieved += new SocketMessageHandler(ClientSocketJob_MsgRecieved);
}
void ClientSocketJob_MsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
_Main.CallMsgRecieved(sender, msg);
}
void ClientSocketJob_DataRecieved(ClientSocketJob sender, object data)
{
_Main.CallDataRecieved(sender, data);
}
/// <summary>
/// Холбоосоор өгөгдөл илгээх
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public int DataSend(object data)
{
try
{
lock (_Client)
{
byte[] bytes = ObjLib.Serialize(data);
int i = _Client.Client.Send(bytes);
SocketCommandBlock cmd = new SocketCommandBlock();
cmd.DataAccess = SocketDataAccess.Sent;
MsgRecieved.DynamicInvoke(new object[] { this, cmd });
}
}
catch (Exception ex)
{
ex.ToString();
this.Stop();
}
return 0;
}
/// <summary>
/// Холбоос таслах
/// </summary>
/// <param name="exception"></param>
public void Stop(Exception exception = null)
{
if (_Client != null)
{
try { _Client.Client.Close(); }
catch (Exception ex) { ex.ToString(); }
_Client = null;
}
_Main.RemoveJob(this);
if (_ClientThread != null)
{
try { _ClientThread.Abort(); }
catch (Exception ex) { ex.ToString(); }
_ClientThread = null;
SocketCommandBlock cmdClientStop = new SocketCommandBlock();
cmdClientStop.DataAccess = SocketDataAccess.ClientStop;
MsgRecieved.DynamicInvoke(new object[] { this, cmdClientStop });
}
}
/// <summary>
/// Холбоосын ажиллагааг эхлүүлэх
/// </summary>
public void Start()
{
if (_ClientThread == null && _Client != null)
{
_ClientThread = new Thread(new ThreadStart(clientProcess));
_ClientThread.Start();
}
}
/// <summary>
/// Клиент холбоосоор дамжих өгөгдлийг хүлээн авна
/// </summary>
private void clientProcess()
{
try
{
SocketCommandBlock cmdClientStart = new SocketCommandBlock();
cmdClientStart.DataAccess = SocketDataAccess.ClientStart;
MsgRecieved.DynamicInvoke(new object[] { this, cmdClientStart });
while (true)
{
try
{
MemoryStream ms = new MemoryStream();
byte[] recb = new byte[_Client.Client.ReceiveBufferSize];
int reci = 0;
reci = _Client.Client.Receive(recb);
ms.Write(recb, 0, reci);
while (_Client.GetStream().DataAvailable)
{
reci = _Client.Client.Receive(recb);
ms.Write(recb, 0, reci);
}
byte[] bytes = (ms.Length == 0) ? (new byte[] { }) : ms.GetBuffer();
try { ms.Close(); }
catch { }
if (bytes == null || bytes.Length == 0) continue;
try
{
var obj = ObjLib.DeSerialize(bytes);
DataRecieved.Invoke(this, obj );
}
catch (Exception e)
{
e.ToString();
}
finally
{
SocketCommandBlock cmdReceive = new SocketCommandBlock();
cmdReceive.DataAccess = SocketDataAccess.Receive;
MsgRecieved.Invoke(this, cmdReceive);
}
}
catch (Exception ex)
{
ex.ToString();
this.Stop(ex);
}
}
}
catch { }
}
public override string ToString()
{
return string.Format("{0}. ({1})", _JobIndex, _IP);
}
}
}
in SERVER FORM
SocketLib _ServerSocket;
event SocketHandler sh;
event SocketMessageHandler smh;
public frmServerForm()
{
InitializeComponent();
this.Text = " [ Сервер ] - Хувилбар " + Application.ProductVersion;
sh += frmServerForm_sh;
smh += frmServerForm_smh;
}
void frmServerForm_smh(ClientSocketJob sender, SocketCommandBlock msg)
{
if (msg.DataAccess == SocketDataAccess.ClientStart)
{
lstConnectedDevices.Items.Add(sender);
}
if (msg.DataAccess == SocketDataAccess.ClientStop)
{
lstConnectedDevices.Items.Remove(sender);
}
if (sender == null)
{
lstLog.Items.Insert(0, msg.DataAccess.ToString());
}
else
{
lstLog.Items.Insert(0, "IP: " + sender.IP + " , Job: " + sender.JobIndex.ToString() + " , Access: " + msg.DataAccess.ToString());
}
}
void frmServerForm_sh(ClientSocketJob sender, object data)
{
if (data == null || !(data is string)) return;
lstLog.Items.Insert(0, "IP: " + sender.IP + " , Job: " + sender.JobIndex.ToString() + " , Data: " + data);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_ServerSocket = new SocketLib(true, true);
_ServerSocket.DataRecieved += _ServerSocket_DataRecieved;
_ServerSocket.MsgRecieved += _ServerSocket_MsgRecieved;
int Setting_SocketServerPort = 1986;
_ServerSocket.Connect(Environment.MachineName, Setting_SocketServerPort);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_ServerSocket != null)
{
_ServerSocket.Stop();
}
}
void _ServerSocket_MsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
this.Invoke(smh, new object[] { sender, msg });
}
void _ServerSocket_DataRecieved(ClientSocketJob sender, object data)
{
this.Invoke(sh, new object[] { sender, data });
}
private void btnSend_Click(object sender, EventArgs e)
{
string data = txtMessage.Text;
ClientSocketJob job = (ClientSocketJob)lstConnectedDevices.SelectedItem;
_ServerSocket.SendToClient(job, data);
}
in CLIENT FORM
SocketLib _ClientSocket;
event SocketHandler sh;
event SocketMessageHandler smh;
public frmChat()
{
InitializeComponent();
this.Text = Controller.Current.AboutDocument.DocumentElement.FirstChild.InnerText;
sh += frmChatForm_sh;
smh += frmChatForm_smh;
}
void frmChatForm_smh(ClientSocketJob sender, SocketCommandBlock msg)
{
if (sender == null)
{
txtLog.AppendText(msg.DataAccess.ToString());
}
else
{
txtLog.AppendText("IP: " + sender.IP +
" , Job: " + sender.JobIndex.ToString() +
" , Access: " + msg.DataAccess.ToString());
}
txtLog.AppendText("\r\n");
}
void frmChatForm_sh(ClientSocketJob sender, object data)
{
txtLog.AppendText("IP: " + sender.IP +
" , Job: " + sender.JobIndex.ToString() +
" , Data: " + data);
txtLog.AppendText("\r\n");
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_ClientSocket = new SocketLib(false, true);
_ClientSocket.DataRecieved += _ClientSocket_DataRecieved;
_ClientSocket.MsgRecieved += _ClientSocket_MsgRecieved;
string Setting_SocketServerName = "127.0.0.1";
int Setting_SocketServerPort = 1986;
_ClientSocket.Connect(Setting_SocketServerName, Setting_SocketServerPort);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_ClientSocket != null)
{
_ClientSocket.Stop();
}
}
void _ClientSocket_MsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
this.Invoke(smh, new object[] { sender, msg });
}
void _ClientSocket_DataRecieved(ClientSocketJob sender, object data)
{
this.Invoke(sh, new object[] { sender, data });
}
private void button1_Click(object sender, EventArgs e)
{
_ClientSocket.SendToServer(textBox1.Text);
}
public class ArrList
{
private ArrayList _Key = new ArrayList();
private ArrayList _Comment = new ArrayList();
private ArrayList _List = new ArrayList();
public object this[int index]
{
get { return _List[index]; }
}
public object this[string key]
{
get { return _List[_Key.IndexOf(key)]; }
}
public string this[object data]
{
get { return (string)_Key[_List.IndexOf(data)]; }
}
public int Count
{
get { return _List.Count; }
}
public int Length
{
get { return _List.Count; }
}
public bool Add(string key, object data, object comment)
{
if (_Key.IndexOf(key) < 0)
{
_List.Add(data);
_Comment.Add(comment);
_Key.Add(key);
return true;
}
else return false;
}
public bool Add(string key, object data)
{
if (_Key.IndexOf(key) < 0)
{
_List.Add(data);
_Comment.Add(null);
_Key.Add(key);
return true;
}
else return false;
}
public bool Add(object data)
{
if (_Key.IndexOf(_List.Count.ToString()) < 0)
{
_List.Add(data);
_Comment.Add(null);
_Key.Add((_List.Count - 1).ToString());
return true;
}
else return false;
}
public object Get(int index)
{
return _List[index];
}
public object Get(string key)
{
try
{
return _List[_Key.IndexOf(key)];
}
catch { return null; }
}
public string Get(object data)
{
try
{
return (string)_Key[_List.IndexOf(data)];
}
catch { return null; }
}
public bool Remove(object data)
{
int nd = _List.IndexOf(data);
if (nd < 0) return false;
else
{
_List.RemoveAt(nd);
_Comment.RemoveAt(nd);
_Key.RemoveAt(nd);
return true;
}
}
public bool Remove(string key)
{
int nd = _Key.IndexOf(key);
if (nd < 0) return false;
else
{
_List.RemoveAt(nd);
_Comment.RemoveAt(nd);
_Key.RemoveAt(nd);
return true;
}
}
public bool Remove(int index)
{
if (index < 0 || _List.Count <= index) return false;
else
{
_List.RemoveAt(index);
_Comment.RemoveAt(index);
_Key.RemoveAt(index);
return true;
}
}
public int IndexOf(string key)
{
return _Key.IndexOf(key);
}
public int IndexOf(object data)
{
return _List.IndexOf(data);
}
public void Clear()
{
_List.Clear();
_Comment.Clear();
_Key.Clear();
}
public ArrList()
{ }
}
namespace SocketLibraryCore
{
/// <summary>
/// Холбоосоор дамжих өгөгдлийг хүлээн авагч
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
public delegate void SocketHandler(ClientSocketJob sender, object data);
/// <summary>
/// Холбоосын үйлдэл бүрийг мэдэгдэгч
/// </summary>
/// <param name="sender"></param>
/// <param name="msg"></param>
public delegate void SocketMessageHandler(ClientSocketJob sender, SocketCommandBlock msg);
[Serializable]
public enum SocketDataAccess
{
Accept = 0,
Sent = 1,
Receive = 2,
ServerStop = 3,
ServerStart = 4,
ClientStop = 5,
ClientStart = 6,
Log = 7,
Error = 8
}
[Serializable]
public class SocketCommandBlock
{
public string DataCommand { get; set; }
public string DataString { get; set; }
public object DataBuffer { get; set; }
public long DataResult { get; set; }
public SocketDataAccess DataAccess { get; set; }
public SocketCommandBlock()
{
DataAccess = SocketDataAccess.Log;
}
}
/// <summary>
/// Сервер эсвэл клиент холболт
/// </summary>
public class SocketLib
{
#region Control Methods
public event SocketMessageHandler MsgRecieved;
public void CallMsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
if (MsgRecieved != null) MsgRecieved.Invoke(sender, msg);
}
public event SocketHandler DataRecieved;
public void CallDataRecieved(ClientSocketJob sender, object data)
{
if (DataRecieved != null) DataRecieved.Invoke(sender, data);
}
public int SendToClient(int index, object data)
{
var sender = (ClientSocketJob)_ClientList[index];
return SendToClient(sender, data);
}
public int SendToClient(ClientSocketJob sender, object data)
{
if (sender != null) return sender.DataSend(data);
else return 0;
}
public List<int> SendToAll(object data, ClientSocketJob ignoreJob = null)
{
List<int> list = new List<int>();
int l = _ClientList.Count;
for (int i = 0; i < l; i++)
{
var job = (_ClientList[i] as ClientSocketJob);
if (ignoreJob == null || job.JobIndex != ignoreJob.JobIndex)
{
var ret = SendToClient(job, data);
list.Add(ret);
}
}
return list;
}
public int SendToServer(object data)
{
//ClientSocketJob is bridge for server connection
return (_ClientList[0] as ClientSocketJob).DataSend(data);
}
public void Stop(ClientSocketJob sender, object data)
{
sender.Stop();
}
public void Stop()
{
if (_IsServer)
this.Desconnect();
else
{
if (_ClientList.Count > 0)
{
(_ClientList[0] as ClientSocketJob).Stop();
}
}
}
#endregion Control Methods
#region Properties
private bool _ClientDistinct = true;
public bool ClientDistinct
{
get { return _ClientDistinct; }
set { _ClientDistinct = value; }
}
private Thread _ServerThread;
private TcpListener _Server;
private string _HostName = "127.0.0.1";
public string HostName
{
get { return _HostName; }
}
private int _PortNumber = 1986;
public int PortNumber
{
get { return _PortNumber; }
}
private bool _IsServer;
public bool IsServer
{
get { return _IsServer; }
}
private bool _IsRunning;
public bool IsRunning
{
get { return _IsRunning; }
}
//
private ArrList _ClientList;
public ArrList ClientList
{
get { return _ClientList; }
}
public ClientSocketJob Me
{
get
{
return (_IsServer == true) ? null :
((_ClientList == null || _ClientList.Count == 0) ? null : (ClientSocketJob)_ClientList[0]);
}
}
private long _ClientJobCount;
public long ClientJobCount
{
get { return _ClientJobCount; }
}
#endregion Properties
/// <summary>
/// Сервер эсвэл клиент холболтын ажлын класс
/// </summary>
/// <param name="isServer">Сервер талын холбоос эсэх</param>
/// <param name="isDistinct">Клиент талын хаяг давхардах эсэх</param>
public SocketLib(bool isServer, bool isDistinct)
{
_ClientJobCount = 0;
_ClientList = new ArrList();
_IsServer = isServer;
_ClientDistinct = isDistinct;
}
/// <summary>
/// Холболтыг эхлүүлэх
/// </summary>
/// <param name="HostName"></param>
/// <param name="PortNumber"></param>
public void Connect(string HostName, int PortNumber)
{
if (_IsRunning == false)
{
_HostName = HostName;
_PortNumber = PortNumber;
if (_IsServer)
{
IPAddress ip = Dns.GetHostEntry(Environment.MachineName).AddressList[0];
_Server = new TcpListener(ip, _PortNumber);
_ServerThread = new Thread(new ThreadStart(this.serverProcess));
_ServerThread.Start();
}
else
{
TcpClient tcpclient = new TcpClient(_HostName, _PortNumber);
createClientSocketJob(tcpclient);
}
_IsRunning = true;
}
}
/// <summary>
/// Сервер эсвэл клиент холболтыг унтраана
/// </summary>
public void Desconnect()
{
if (_Server != null)
{
try { _Server.Stop(); }
catch (Exception ex) { ex.ToString(); }
_Server = null;
}
int l = _ClientList.Count;
for (int i = 0; i < l; i++)
{
try
{
(_ClientList[i] as ClientSocketJob).Stop();
}
catch { }
}
_ClientList.Clear();
_ClientJobCount = 0;
_IsRunning = false;
if (_ServerThread != null)
{
try { _ServerThread.Abort(); }
catch (Exception ex) { ex.ToString(); }
_ServerThread = null;
SocketCommandBlock cmd = new SocketCommandBlock();
if (_IsServer)
cmd.DataAccess = SocketDataAccess.ServerStop;
else
cmd.DataAccess = SocketDataAccess.ClientStop;
MsgRecieved.DynamicInvoke(new object[] { null, cmd });
}
}
/// <summary>
/// Аль нэг холбоосыг таслана
/// </summary>
/// <param name="job"></param>
public void RemoveJob(ClientSocketJob job)
{
try
{
_ClientList.Remove(job.JobIndex.ToString());
}
catch (Exception ex) { ex.ToString(); }
if (_IsServer == false && _ClientList.Count == 0) _IsRunning = false;
}
/// <summary>
/// Холболтыг чагнаж шинэ клиентийн холбоосыг бүртгэн авч цуглуулна
/// </summary>
private void serverProcess()
{
try
{
_Server.Start();
SocketCommandBlock cmd = new SocketCommandBlock();
cmd.DataAccess = SocketDataAccess.ServerStart;
MsgRecieved.DynamicInvoke(new object[] { null, cmd });
while (true)
{
try
{
TcpClient tcpclient = _Server.AcceptTcpClient();
cmd.DataAccess = SocketDataAccess.Accept;
MsgRecieved.DynamicInvoke(new object[] { null, cmd });
if (_ClientDistinct)
{
var prevJob = existsClientSocketJobByIP(tcpclient);
if (prevJob != null)
{
prevJob.Stop();
}
}
createClientSocketJob(tcpclient);
}
catch (Exception ex)
{
ex.ToString();
this.Desconnect();
}
finally
{
Thread.Sleep(10);
}
}
}
catch { }
}
/// <summary>
/// Клиентийн хаяг давхардсан эсэхийг шалгах
/// </summary>
/// <param name="tcp"></param>
/// <returns></returns>
private ClientSocketJob existsClientSocketJobByIP(TcpClient tcp)
{
IPEndPoint ipep = (IPEndPoint)tcp.Client.RemoteEndPoint;
string ip = ipep.Address.ToString();
int l = _ClientList.Count;
for (int i = 0; i < l; i++)
{
if ((_ClientList[i] as ClientSocketJob).IP == ip)
{
return (_ClientList[i] as ClientSocketJob);
}
}
return null;
}
/// <summary>
/// Шинэ холбоос үүсгэж байна
/// </summary>
/// <param name="tcpclient"></param>
private void createClientSocketJob(TcpClient tcpclient)
{
ClientSocketJob job = new ClientSocketJob(this, tcpclient, _ClientJobCount);
_ClientList.Add(job.JobIndex.ToString(), job);
_ClientJobCount++;
job.Start();
}
}
/// <summary>
/// Клиент холбоос
/// </summary>
public class ClientSocketJob
{
private string _IP;
public string IP
{
get { return _IP; }
set { _IP = value; }
}
private long _JobIndex;
public long JobIndex
{
get { return _JobIndex; }
}
private object _Tag;
public object Tag
{
get { return _Tag; }
set { _Tag = value; }
}
private object _Commit;
public object Commit
{
get { return _Commit; }
set { _Commit = value; }
}
private event SocketMessageHandler MsgRecieved;
private event SocketHandler DataRecieved;
private SocketLib _Main;
private TcpClient _Client;
public TcpClient Client
{
get { return _Client; }
set { _Client = value; }
}
private Thread _ClientThread;
/// <summary>
/// Клиент холбоосын ажлын класс
/// </summary>
/// <param name="main">Үндсэн класс</param>
/// <param name="tcpclient">Сокет клиент</param>
/// <param name="jobindex">Дугаар</param>
public ClientSocketJob(SocketLib main, TcpClient tcpclient, long jobindex)
{
IPEndPoint endp = (IPEndPoint)tcpclient.Client.RemoteEndPoint;
_IP = endp.Address.ToString();
_Main = main;
_Client = tcpclient;
_JobIndex = jobindex;
DataRecieved += new SocketHandler(ClientSocketJob_DataRecieved);
MsgRecieved += new SocketMessageHandler(ClientSocketJob_MsgRecieved);
}
void ClientSocketJob_MsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
_Main.CallMsgRecieved(sender, msg);
}
void ClientSocketJob_DataRecieved(ClientSocketJob sender, object data)
{
_Main.CallDataRecieved(sender, data);
}
/// <summary>
/// Холбоосоор өгөгдөл илгээх
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public int DataSend(object data)
{
try
{
lock (_Client)
{
byte[] bytes = ObjLib.Serialize(data);
int i = _Client.Client.Send(bytes);
SocketCommandBlock cmd = new SocketCommandBlock();
cmd.DataAccess = SocketDataAccess.Sent;
MsgRecieved.DynamicInvoke(new object[] { this, cmd });
}
}
catch (Exception ex)
{
ex.ToString();
this.Stop();
}
return 0;
}
/// <summary>
/// Холбоос таслах
/// </summary>
/// <param name="exception"></param>
public void Stop(Exception exception = null)
{
if (_Client != null)
{
try { _Client.Client.Close(); }
catch (Exception ex) { ex.ToString(); }
_Client = null;
}
_Main.RemoveJob(this);
if (_ClientThread != null)
{
try { _ClientThread.Abort(); }
catch (Exception ex) { ex.ToString(); }
_ClientThread = null;
SocketCommandBlock cmdClientStop = new SocketCommandBlock();
cmdClientStop.DataAccess = SocketDataAccess.ClientStop;
MsgRecieved.DynamicInvoke(new object[] { this, cmdClientStop });
}
}
/// <summary>
/// Холбоосын ажиллагааг эхлүүлэх
/// </summary>
public void Start()
{
if (_ClientThread == null && _Client != null)
{
_ClientThread = new Thread(new ThreadStart(clientProcess));
_ClientThread.Start();
}
}
/// <summary>
/// Клиент холбоосоор дамжих өгөгдлийг хүлээн авна
/// </summary>
private void clientProcess()
{
try
{
SocketCommandBlock cmdClientStart = new SocketCommandBlock();
cmdClientStart.DataAccess = SocketDataAccess.ClientStart;
MsgRecieved.DynamicInvoke(new object[] { this, cmdClientStart });
while (true)
{
try
{
MemoryStream ms = new MemoryStream();
byte[] recb = new byte[_Client.Client.ReceiveBufferSize];
int reci = 0;
reci = _Client.Client.Receive(recb);
ms.Write(recb, 0, reci);
while (_Client.GetStream().DataAvailable)
{
reci = _Client.Client.Receive(recb);
ms.Write(recb, 0, reci);
}
byte[] bytes = (ms.Length == 0) ? (new byte[] { }) : ms.GetBuffer();
try { ms.Close(); }
catch { }
if (bytes == null || bytes.Length == 0) continue;
try
{
var obj = ObjLib.DeSerialize(bytes);
DataRecieved.Invoke(this, obj );
}
catch (Exception e)
{
e.ToString();
}
finally
{
SocketCommandBlock cmdReceive = new SocketCommandBlock();
cmdReceive.DataAccess = SocketDataAccess.Receive;
MsgRecieved.Invoke(this, cmdReceive);
}
}
catch (Exception ex)
{
ex.ToString();
this.Stop(ex);
}
}
}
catch { }
}
public override string ToString()
{
return string.Format("{0}. ({1})", _JobIndex, _IP);
}
}
}
in SERVER FORM
SocketLib _ServerSocket;
event SocketHandler sh;
event SocketMessageHandler smh;
public frmServerForm()
{
InitializeComponent();
this.Text = " [ Сервер ] - Хувилбар " + Application.ProductVersion;
sh += frmServerForm_sh;
smh += frmServerForm_smh;
}
void frmServerForm_smh(ClientSocketJob sender, SocketCommandBlock msg)
{
if (msg.DataAccess == SocketDataAccess.ClientStart)
{
lstConnectedDevices.Items.Add(sender);
}
if (msg.DataAccess == SocketDataAccess.ClientStop)
{
lstConnectedDevices.Items.Remove(sender);
}
if (sender == null)
{
lstLog.Items.Insert(0, msg.DataAccess.ToString());
}
else
{
lstLog.Items.Insert(0, "IP: " + sender.IP + " , Job: " + sender.JobIndex.ToString() + " , Access: " + msg.DataAccess.ToString());
}
}
void frmServerForm_sh(ClientSocketJob sender, object data)
{
if (data == null || !(data is string)) return;
lstLog.Items.Insert(0, "IP: " + sender.IP + " , Job: " + sender.JobIndex.ToString() + " , Data: " + data);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_ServerSocket = new SocketLib(true, true);
_ServerSocket.DataRecieved += _ServerSocket_DataRecieved;
_ServerSocket.MsgRecieved += _ServerSocket_MsgRecieved;
int Setting_SocketServerPort = 1986;
_ServerSocket.Connect(Environment.MachineName, Setting_SocketServerPort);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_ServerSocket != null)
{
_ServerSocket.Stop();
}
}
void _ServerSocket_MsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
this.Invoke(smh, new object[] { sender, msg });
}
void _ServerSocket_DataRecieved(ClientSocketJob sender, object data)
{
this.Invoke(sh, new object[] { sender, data });
}
private void btnSend_Click(object sender, EventArgs e)
{
string data = txtMessage.Text;
ClientSocketJob job = (ClientSocketJob)lstConnectedDevices.SelectedItem;
_ServerSocket.SendToClient(job, data);
}
in CLIENT FORM
SocketLib _ClientSocket;
event SocketHandler sh;
event SocketMessageHandler smh;
public frmChat()
{
InitializeComponent();
this.Text = Controller.Current.AboutDocument.DocumentElement.FirstChild.InnerText;
sh += frmChatForm_sh;
smh += frmChatForm_smh;
}
void frmChatForm_smh(ClientSocketJob sender, SocketCommandBlock msg)
{
if (sender == null)
{
txtLog.AppendText(msg.DataAccess.ToString());
}
else
{
txtLog.AppendText("IP: " + sender.IP +
" , Job: " + sender.JobIndex.ToString() +
" , Access: " + msg.DataAccess.ToString());
}
txtLog.AppendText("\r\n");
}
void frmChatForm_sh(ClientSocketJob sender, object data)
{
txtLog.AppendText("IP: " + sender.IP +
" , Job: " + sender.JobIndex.ToString() +
" , Data: " + data);
txtLog.AppendText("\r\n");
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_ClientSocket = new SocketLib(false, true);
_ClientSocket.DataRecieved += _ClientSocket_DataRecieved;
_ClientSocket.MsgRecieved += _ClientSocket_MsgRecieved;
string Setting_SocketServerName = "127.0.0.1";
int Setting_SocketServerPort = 1986;
_ClientSocket.Connect(Setting_SocketServerName, Setting_SocketServerPort);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_ClientSocket != null)
{
_ClientSocket.Stop();
}
}
void _ClientSocket_MsgRecieved(ClientSocketJob sender, SocketCommandBlock msg)
{
this.Invoke(smh, new object[] { sender, msg });
}
void _ClientSocket_DataRecieved(ClientSocketJob sender, object data)
{
this.Invoke(sh, new object[] { sender, data });
}
private void button1_Click(object sender, EventArgs e)
{
_ClientSocket.SendToServer(textBox1.Text);
}
Subscribe to:
Posts (Atom)