레이블이 C#인 게시물을 표시합니다. 모든 게시물 표시
레이블이 C#인 게시물을 표시합니다. 모든 게시물 표시

2015년 11월 10일 화요일

checkbox select all with asp.net

javascript
<script type="text/javascript">
    var TotalChkBx = 0;
    var Counter = 0;

    function gridOnLoad(rowCnt) {
        TotalChkBx = rowCnt;
        Counter = 0;
    }

    function HeaderClick(CheckBox) {
        var TargetBaseControl = document.getElementById('<%= this.egvWPPrint.ClientID %>');
        var TargetChildControl = "chkBxSelect";

        try {
            var Inputs = TargetBaseControl.getElementsByTagName("input");

            for (var n = 0; n < Inputs.length; ++n)
                if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
                    Inputs[n].checked = CheckBox.checked;

            Counter = CheckBox.checked ? TotalChkBx : 0;
        }
        catch (err) {
            Counter = 0;
        }
    }
   
    function ChildClick(CheckBox, HCheckBox) {
        try {
            var HeaderCheckBox = document.getElementById(HCheckBox);

            if (CheckBox.checked && Counter < TotalChkBx)
                Counter++;
            else if (Counter > 0)
                Counter--;

            if (Counter < TotalChkBx)
                HeaderCheckBox.checked = false;
            else if (Counter == TotalChkBx)
                HeaderCheckBox.checked = true;
        }
        catch (err) {
        }
    }  
</script>


c#
    // bind after
    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "GridLoad", "gridOnLoad(" + ds.Tables[0].Rows.Count.ToString() + ");", true);
   
    protected void egvWPPrint_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkBxSelect");
            CheckBox chkBxHeader = (CheckBox)this.egvWPPrint.HeaderRow.FindControl("chkBxHeader");
            chkBxSelect.Attributes["onclick"] = string.Format
                                                   (
                                                      "javascript:ChildClick(this,'{0}');",
                                                      chkBxHeader.ClientID
                                                   );        
        }
    }

aspx
                    <asp:TemplateField HeaderText="선택">
                        <ItemTemplate><asp:CheckBox ID="chkBxSelect" runat="server" /></ItemTemplate>
                        <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                        <HeaderTemplate>
                            <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" />
                        </HeaderTemplate>
                    </asp:TemplateField>

2015년 11월 5일 목요일

asp.net control refresh by c#

asp.net
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </ContentTemplate>
</asp:UpdatePanel>

c#
Button1.text = "123";

2015년 10월 29일 목요일

RegisterPostBackControl add & file download for dynamic LinkButton

asp.net
<asp:TemplateField HeaderText="name">
    <ItemTemplate><asp:LinkButton ID="lbFildDW" CommandArgument='<%# Bind("DOCBIGO") %>' runat="server" Text='<%# Bind("DOCNAME") %>' OnClick="ExcelDW_Click"></asp:LinkButton> </ItemTemplate>
    <itemstyle horizontalalign="Center" Wrap="false"/> <headerstyle Wrap="false"/>
</asp:TemplateField>  

c#
protected void egvPopDDSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        LinkButton lnkbtnDetail = (LinkButton)e.Row.FindControl("lbFildDW");
        ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkbtnDetail);
    }
}

protected void ExcelDW_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string filePath = btn.CommandArgument;

    if (File.Exists(HttpContext.Current.Server.MapPath(filePath)))
    {
        string strFileName = "";
        strFileName = System.IO.Path.GetFileName(HttpContext.Current.Server.MapPath(filePath));
        strFileName = HttpUtility.UrlEncode(strFileName, new UTF8Encoding()).Replace("+", "%20");
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath(filePath));
        HttpContext.Current.Response.End();
    }
}

2015년 10월 11일 일요일

c# Struct Marshal for c++ dll

c++

typedef struct
{
HANDLE aaa;
HWND bbb;
BYTE ccc[2500];

} SStruct, LPSCStruct;


BOOL __stdcall func1(LPSCStruct zzz);



c#
public struct LPSCStruct
{
    public int aaa;
    public IntPtr bbb;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2500)]
    public byte[] ccc;
}


public partial class Form1 : Form /*, IMessageFilter*/
{      
    [DllImport("test.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.I1)]
    unsafe extern public static bool func1(IntPtr zzz);
   
    public LPSCStruct sss;
    public LPSCStruct rrr;
    public IntPtr m_lpstruct;
   
    private void Form1_Load(object sender, EventArgs e)
    {
        sss = new LPSCStruct();
    }  
   
    private IntPtr MarshalToPointer(object data)
    {
        IntPtr buf = Marshal.AllocHGlobal(Marshal.SizeOf(pse));
        Marshal.StructureToPtr(data, buf, false);
        return buf;
    }

    private object MarshalToStruct(IntPtr buf, Type t)
    {
        return Marshal.PtrToStructure(buf, t);
    }  
   
    private void button1_Click(object sender, EventArgs e)
    {
        sss.bbb = FindWindow(null, "Form1");

        m_lpstruct = MarshalToPointer(sss);

        bool bRtn = func1(m_lpstruct);
        if (bRtn)
        {
            rrr = (LPSCStruct)MarshalToStruct(m_lpstruct, typeof(LPSCStruct));

            textBox1.AppendText(Encoding.Default.GetString(rrr.ccc));
        }          
    }

2015년 7월 21일 화요일

audio capture & udp send by cscore

public class AudioCapture
    {
        public enum CaptureMode
        {
            Capture,
            LoopbackCapture
        }

        private const CaptureMode captureMode = CaptureMode.LoopbackCapture;
        private MMDevice _selectedDevice;
        private WasapiCapture _soundIn;
        private IWaveSource _finalSource;
        private bool bCapturedStop = false;

        private const int AUDIOBLOCKSIZE = 3528;

        public MMDevice SelectedDevice
        {
            get { return _selectedDevice; }
            set
            {
                _selectedDevice = value;
            }
        }

        private AudioSender audioSender = new AudioSender();

        public bool AudioDeviceInit()
        {
            bool bRtn = false;

            try
            {
                using (var deviceEnumerator = new MMDeviceEnumerator())
                using (var deviceCollection = deviceEnumerator.EnumAudioEndpoints(
                    captureMode == CaptureMode.Capture ? DataFlow.Capture : DataFlow.Render, DeviceState.Active))
                {
                    foreach (var device in deviceCollection)
                    {
                        var deviceFormat = WaveFormatFromBlob(device.PropertyStore[
                            new PropertyKey(new Guid(0xf19f064d, 0x82c, 0x4e27, 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c), 0)].BlobValue);

                        _selectedDevice = device;

                        bRtn = true;
                    }
                }
            }
            catch (Exception e)
            {
                K_BoxLog.LogDebug(e);
            }

            return bRtn;
        }

        public bool AudioCaptureStart(string serverip)
        {
            bool bRtn = false;

            try
            {
                if (SelectedDevice == null)
                {
                    return false;
                }

                if (AudioSender.connected == false)
                    audioSender.AudioSendConnect(serverip);

                if (captureMode == CaptureMode.Capture)
                    _soundIn = new WasapiCapture();
                else
                    _soundIn = new WasapiLoopbackCapture();

                _soundIn.Device = SelectedDevice;
                _soundIn.Initialize();

                var soundInSource = new SoundInSource(_soundIn, AUDIOBLOCKSIZE * 4);
                var singleBlockNotificationStream = new SimpleNotificationSource(soundInSource);

                _finalSource = singleBlockNotificationStream
                    .ToWaveSource(16);

                byte[] buffer = new byte[AUDIOBLOCKSIZE * 2];
           
                soundInSource.DataAvailable += (s, e) =>
                {
                    int read;
                    while ((read = _finalSource.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        audioSender.AudioSend(buffer, read);
                    }
                };

                _soundIn.Start();

                bRtn = true;
            }
            catch { }

            return bRtn;
        }

        private void SingleBlockNotificationStreamOnSingleBlockRead(object sender, SingleBlockReadEventArgs e)
        {          
         
        }

        public bool AudioCaptureStop()
        {
            bool bRtn = false;

            try
            {
                if (AudioSender.connected == true)
                    audioSender.AudioSendDisconnect();
                _soundIn.Stop();

                bRtn = false;
            }
            catch  {  }

            return bRtn;
        }

        private static WaveFormat WaveFormatFromBlob(Blob blob)
        {
            if (blob.Length == 40)
                return (WaveFormat)Marshal.PtrToStructure(blob.Data, typeof(WaveFormatExtensible));
            return (WaveFormat)Marshal.PtrToStructure(blob.Data, typeof(WaveFormat));
        }
    }

2015년 5월 22일 금요일

App Config 이 잘못되었습니다

Visual Studio 에서 old version 의 프로젝트 migration 시 간혹 "App Config 이 잘못되었습니다" 메세지가 발생하는 경우

프로젝트 아래에 app.config 파일 만들고

<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

작성하고, 프로젝트 다시 연단

2013년 9월 22일 일요일

Byte Array to Float

[ 설명 ]
- 아래 함수면 왠만한 예외 상황은 해결
- ordering : 송신측의 상황에 따라 변경해서 사용
- IsNaN : Return Value 의 상태에 따라 적당히 사용하면 되겠다
- Math.Round : 아래 함수를 사용 할 때, Return Value 가 무한소수점이 반환 된다면, 다른 쪽에서 여러가지 문제가 발생 할 수 있다. Parameter 로 소수점 자리수를 조절해도 괜찮을 것이다. 일단 급해서 hard coding...

        public static float ByteToFloat(byte[] buf, int startIndex, int nLen, bool ordering)
        {
            try
            {
                float fRtn = 0.00f;

                byte[] tempBuf = new byte[nLen];
                Buffer.BlockCopy(buf, startIndex, tempBuf, 0, nLen);

                if (ordering == false)
                {
                    fRtn = System.BitConverter.ToSingle(tempBuf, 0);
                }
                else
                {
                    fRtn = System.BitConverter.ToSingle(tempBuf.Reverse().ToArray(), tempBuf.Length - sizeof(Single) - 0);
                }

                if (float.IsNaN(fRtn))
                    return (float)0;
                else
                {
                    return (float)Math.Round(fRtn, 2);
                }
            }
            catch
            {
                return (float)0;
            }
        }

2013년 9월 5일 목요일

c# 에서 Queue 사용

어떤 객체에 대해서, 한 곳에서 처리하기 위해 간단히 Queue 를 사용해 본다
Transaction 이 거시기 한 Cubrid( invalid buffer position 등과 같은 Exception Error ) 에, 짧은 순간 많은 쿼리를 처리 하거나 할 때...

선언
using System.Collections;
public Queue m_sqlQueue = new Queue();


구현
        public override bool SQLAdd(string sQuery)
        {
            try
            {
                m_sqlQueue.Enqueue(sQuery);
                return true;
            }
            catch (Exception ex)
            {
                MiddlewareLog.LogDebug(ex);
                return false;
            }

        }

// 아래 예제 스레드는 간단하지만, diffTick 을 20ms 으로 고정하지 않고, 짱구를 좀 굴리면 좀 더 최적화 해서 처리 할 수 있다, 여기선 Pass
        private void DoDBApply()
        {
            try
            {
                int startTick = Environment.TickCount;
                int currTick = 0;
                int diffTick = 0;
                do
                {
                    System.Threading.Thread.Sleep(1);

                    if (bShutdown == true) break;

                    currTick = Environment.TickCount;
                    diffTick = currTick - startTick;
                    if (diffTick > 20)
                    {
                        startTick = Environment.TickCount;
                        diffTick = 0;

                        if (m_sqlQueue.Count > 0)
                        {
                            object str = m_sqlQueue.Dequeue();
                            QueryExecute((string)str);
                        }
                    }
                } while (bShutdown == false);
            }
            catch
            {
            }
        }

2013년 9월 3일 화요일

Dictionary 를 Array List 처럼 사용하기

선언

public static Dictionary<string, object> jsonSPDM24n = new Dictionary<string, object>();


할당

두번째 인자인 object 에 다시 같은 형태의 Dictionary<string, object> 를 Add 메소드를 사용하여 추가하거나, Assign 해서 사용 할 수 있다

                if (jsonSPDM24n.ContainsKey(json["device_id"].ToString() + "_" + json["addressno"].ToString()) == true)
                {
                    jsonSPDM24n[json["device_id"].ToString() + "_" + json["addressno"].ToString()] = json;
                }
                else
                {
                    jsonSPDM24n.Add(json["device_id"].ToString() + "_" + json["addressno"].ToString(), json);
                }

즉, 아래와 같은 의미가 되겠다

Dictionary<string, Dictionary<string, object>>


사용

이제 이걸 꺼내서 사용하는 것은,

                foreach (KeyValuePair<string, object> temp in jsonSPDM24n)
                {
                    Dictionary<string, object> json = (Dictionary<string, object>)temp.Value;
                    if ((string)json["producttype"] == "spdm24n")
                    {
                        ....
                     }
                 }

2013년 6월 24일 월요일

Relative path for Uri ( C# )

this.dashboardViewer1.DashboardUri = new System.Uri(@"../bin/data/Xfra_Widget.xml", System.UriKind.Relative);