แสดงบทความที่มีป้ายกำกับ C# แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ C# แสดงบทความทั้งหมด

วันพุธที่ 4 ธันวาคม พ.ศ. 2556

Allow C# to manager IIS when use Microsoft.Web.Administration

I use reference Microsoft.Web.Administration from
C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll

to read IIs Status must allow IIS user readable on folder
C:\Windows\System32\inetsrv\config

and to write or change IIS must writable on it.

It can create new user and set to Application pool and allow this user for read and write on above folder.

วันอังคารที่ 20 สิงหาคม พ.ศ. 2556

Format number % in High Chart

I try pie chart but it have 2 categories and show 33.33333333333333 % and 66.66666666666666 %
then i try to format this number

in code have 2 part for show this number first is tooltip that will show when mouse over
and label for static show look at

this.percentage

and change it to this

this.percentage.toFixed(2)


hope this help

วันจันทร์ที่ 29 กรกฎาคม พ.ศ. 2556

Disable SimpleMembership in MVC 4

Today I need to use simple membership in web.config but SimpleMembership in MVC 4 is not simple.

First u need to custom Web.config like this
        <authentication mode="Forms">
            <forms loginUrl="~/Account/Login" timeout="2880" >
                <credentials passwordFormat="Clear">
                    <user name="test" password="test"/>
                </credentials>
            </forms>
        </authentication>

add this to AppSettings
<add key="enableSimpleMembership" value="false"/>

and in AccountController disable InitializeSimpleMembership
//[InitializeSimpleMembership]

now for Login use this for realy simple life.

        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login( LoginModel model, string returnUrl )
        {
            //if (ModelState.IsValid && WebSecurity.Login( model.UserName, model.Password, persistCookie: model.RememberMe ))
            //{
            //    return RedirectToLocal( returnUrl );
            //}
            if (!ValidateLogOn( model.UserName, model.Password ))
                return View( model );

            FormsAuthentication.SetAuthCookie( model.UserName, model.RememberMe );

            if (!String.IsNullOrEmpty( returnUrl ))
                return Redirect( returnUrl );
            else
                return RedirectToAction( "LogOn" );

            //// If we got this far, something failed, redisplay form
            //ModelState.AddModelError( "", "The user name or password provided is incorrect." );
            //return View( model );
        }

        //Add Custom Validate for validate user and pass in Web.config
        private bool ValidateLogOn( string userName, string passWord )
        {
            if (string.IsNullOrEmpty( userName ))
                ModelState.AddModelError( "username", "User name required" );

            if (string.IsNullOrEmpty( passWord ))
                ModelState.AddModelError( "password", "Password required" );

            if (ModelState.IsValid && !FormsAuthentication.Authenticate( userName, passWord ))
                ModelState.AddModelError( "_FORM", "Wrong user name or password" );

            return ModelState.IsValid;
        }
        //End Custom Validate

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            //WebSecurity.Logout();

            //return RedirectToAction( "Index", "Home" );

            FormsAuthentication.SignOut();
            return RedirectToAction( "LogOn" );
        }

c# Assembly QualifiedName format and How to find.

Format is
NamespaceQualifiedTypeName, AssemblyName
 
How to get is
 
Type objType = typeof(System.Array);

        // Print the full assembly name.
        Console.WriteLine ("Full assembly name:\n   {0}.", 
                           objType.Assembly.FullName.ToString()); 

        // Print the qualified assembly name.
        Console.WriteLine ("Qualified assembly name:\n   {0}.", 
                           objType.AssemblyQualifiedName.ToString());  

วันจันทร์ที่ 10 มิถุนายน พ.ศ. 2556

EPPlus Format cell as text.

I need to type like 08x-xxx-xxxx but can't because General format will convert text to number and will be 8x-xxx-xxxx that not fit requirement.

fix this by
worksheet.Cells["A1"].Style.NumberFormat.Format="@"

this command will convert cell to Text Style.

วันพฤหัสบดีที่ 23 พฤษภาคม พ.ศ. 2556

C# Ajax.ActionLink How to Add Onclick for confirm or validate.

I try to insert onclick or @onclick in html attribute but it don't work.
so I try research and found this

@Ajax.ActionLink("Done", "ActionName", 
    new AjaxOptions 
    { 
        OnBegin = "return ConfirmDone()", 
        UpdateTargetId = "MyContainerId" 
    })
@Ajax.ActionLink("Done", "ActionName", 
    new AjaxOptions 
    { 
        Confirm= "Are you sure you want to do this?", 
        UpdateTargetId = "MyContainerId" 
    })
With this i can add function validate on begin or add confirm before click from Ajax Option.

ref: http://stackoverflow.com/questions/9604942/asp-net-mvc3-ajax-actionlink-conditional-confirmation-dialog-box

วันพุธที่ 16 พฤศจิกายน พ.ศ. 2554

Linq and about OrderBy

Linq has OrderBy and OrderByDescending when need multiple order use ThenBy or ThenByDescending

วันอังคารที่ 18 ตุลาคม พ.ศ. 2554

Problem with razor on MVC 3 ?

try this Quick Reference
http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
and
http://www.asp.net/webmatrix/tutorials/2-introduction-to-asp-net-web-programming-using-the-razor-syntax

วันอังคารที่ 4 ตุลาคม พ.ศ. 2554

Generate Excel file in C#.

2 opensource help a lot for this job.
1 for xls is http://code.google.com/p/excellibrary/
2 for xsls is http://epplus.codeplex.com/

that's all.

วันพฤหัสบดีที่ 2 มิถุนายน พ.ศ. 2554

How can make Visual Studio to support CSS 3.0 Validation

--- Obsolete please see bottom on update ---
This is CSS 3 Intellisense Schema
http://visualstudiogallery.msdn.microsoft.com/7211bcac-091b-4a32-be2d-e797be0db210

And if need more Html 5 support and CSS 3.0 full support install VS2010 SP1.

Update on 2012/11/10 (y/m/d)

After install VS2010 SP1 install this
http://visualstudiogallery.msdn.microsoft.com/a15c3ce9-f58f-42b7-8668-53f6cdc2cd83

วันพฤหัสบดีที่ 13 มกราคม พ.ศ. 2554

XmlTextWriter to format out xml with newline and indent.

This is sample from my project to serializer object with utf8.

XmlSerializer xmlFormat = new XmlSerializer( typeof( LeaveObjectItem ) );

string xml = String.Empty;

Encoding utf8EncodingWithNoByteOrderMark = new UTF8Encoding( false );
using (MemoryStream stream = new MemoryStream())
{
XmlTextWriter xtw = new XmlTextWriter( stream, utf8EncodingWithNoByteOrderMark );
xtw.Formatting = Formatting.Indented;
xtw.Indentation = 4;
xmlFormat.Serialize( xtw, ItemToExport );
xml = Encoding.UTF8.GetString( stream.ToArray() );
}

using (StreamWriter outfile =
new StreamWriter( fullpath, false, System.Text.Encoding.UTF8 ))
{
outfile.Write( xml.Replace( ">�<", ">DBNULL<" ) );
}

วันพุธที่ 4 สิงหาคม พ.ศ. 2553

All about array Items on C#

/ Add an item to the end of an existing array
string[] ar1 = new string[] {"I", "Like", "To"}

// create a temporary array with an extra slot
// at the end
string[] ar2 = new string[ar1.Length + 1];

// add the contents of the ar1 to ar2
// at position 0
ar1.CopyTo(ar2, 0);

// add the desired value
ar2.SetValue("Code.", ar1.Length);

// overwrite ar1 with ar2 and voila!
// the contents of ar1 should now be {"I", "Like", "To", "Code."}
ar1 = ar2;

Or use List

List ls = new List();
ls.Add("Hello");

Or

Array.Resize(ref array, newsize);
array[newsize - 1] = "newvalue"

วันพุธที่ 28 เมษายน พ.ศ. 2553

Xml Serializer in memory.

My object name is request.
and I send TextReader parameter to ChargeRequestFactory Object
This explain simple 2 way to do about this.
But because StringWriter has alway create xml with utf 16 encoding
and I need UTF 8 instead so my choice is choose to use in second solution

Yes we can use StringWriter to create XML with UTF 8 but it must create new
Class and override Encoding so Second task look enough for me.

(1)
StringWriter stringWriter = new StringWriter();

xmlSerializer.Serialize( stringWriter, request );

StringReader stringReader = new StringReader( stringWriter.ToString() );

ChargeRequestFactory factory = new ChargeRequestFactory( stringReader );

(2)
Stream s = new MemoryStream();

XmlWriter xw = new XmlTextWriter( s, Encoding.UTF8 );

xmlSerializer.Serialize( xw, request );

TextReader tr = new StreamReader( s );

s.Seek( 0, SeekOrigin.Begin );

ChargeRequestFactory factory = new ChargeRequestFactory( tr );

In ChargeRequest function I have Deserialize to get XML Back to Object.

วันศุกร์ที่ 23 เมษายน พ.ศ. 2553

Autobuild Nant in Console

Another Example to use Autobild Nant in console.

using System.Threading;

namespace AutobuildConsole
{
class Program
{
static void Main( string[] args )
{
//Console.Write( @"C:\WebBuild\nant-0.86-beta1\bin\NAnt.exe -help" );

//Console.ReadKey();

string commandLine = @"C:\WebBuild\nant-0.86-beta1\bin\NAnt.exe -help";

ExecuteCmd exe = new ExecuteCmd();
exe.ExecuteCommandSync( commandLine );
//exe.ExecuteCommandAsync( commandLine );

//Console.WriteLine( "\nDone !" );
Console.ReadLine();
}

public class ExecuteCmd
{

#region ExecuteCommand Sync and Async

///

/// Executes a shell command synchronously.

///


/// string command

/// string, as output of the command.

public void ExecuteCommandSync( object command )
{

try
{

// create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.

// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo( "cmd", "/c " + command );

// The following commands are needed to redirect the standard output.

//This means that it will be redirected to the Process.StandardOutput StreamReader.

procStartInfo.RedirectStandardOutput = true;

procStartInfo.UseShellExecute = false;

// Do not create the black window.

procStartInfo.CreateNoWindow = true;

// Now we create a process, assign its ProcessStartInfo and start it

System.Diagnostics.Process proc = new System.Diagnostics.Process();

proc.StartInfo = procStartInfo;

proc.Start();



// Get the output into a string

string result = proc.StandardOutput.ReadToEnd();



// Display the command output.

Console.WriteLine( result );

}

catch (Exception objException)
{

// Log the exception

}

}



///

/// Execute the command Asynchronously.

///


/// string command.

public void ExecuteCommandAsync( string command )
{

try
{

//Asynchronously start the Thread to process the Execute command request.

Thread objThread = new Thread( new ParameterizedThreadStart( ExecuteCommandSync ) );

//Make the thread as background thread.

objThread.IsBackground = true;

//Set the Priority of the thread.

objThread.Priority = ThreadPriority.AboveNormal;

//Start the thread.

objThread.Start( command );

}

catch (ThreadStartException objException)
{

// Log the exception

}

catch (ThreadAbortException objException)
{

// Log the exception

}

catch (Exception objException)
{

// Log the exception

}

}

#endregion

}
}
}

Use ShellCommand in Web Form.

sing System.Diagnostics; // For Process


//string fileName = @"C:\WebBuild\nant-0.86-beta1\bin\NAnt.exe";
//string arguments = " -help";

//ProcessStartInfo startInfo = new ProcessStartInfo( fileName, arguments );
//startInfo.CreateNoWindow = false;
//startInfo.UseShellExecute = false;

////If this option is set the DOS window appear again
////startInfo.WindowStyle = ProcessWindowStyle.Hidden;
//startInfo.RedirectStandardOutput = true;
//string result = String.Empty;
//using (Process exeProcess = Process.Start( startInfo ))
//{
// result = exeProcess.StandardOutput.ToString(); ;
// exeProcess.WaitForExit();
//}

//string command = @"C:\WebBuild\nant-0.86-beta1\bin\NAnt.exe -help";
uxResult.Text = String.Empty;
string command = @"C:\WebBuild\nant-0.86-beta1\bin\NAnt.exe -buildfile:C:\WebBuild\vpaspSkin.build";

// create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo( "cmd", "/c " + command );

// The following commands are needed to redirect the standard output.
//This means that it will be redirected to the Process.StandardOutput StreamReader.

//true
procStartInfo.RedirectStandardOutput = true;

// false
procStartInfo.UseShellExecute = false;

//If true Do not create the black window.
procStartInfo.CreateNoWindow = true;

// Now we create a process, assign its ProcessStartInfo and start it

System.Diagnostics.Process proc = new System.Diagnostics.Process();

proc.StartInfo = procStartInfo;

proc.Start();

// Get the output into a string

string result = proc.StandardOutput.ReadToEnd();

uxResult.Text = result;
// Display the command output.

//Console.WriteLine( result );
MessageBox.Show( "Success" );


From old code i have 2 solution to use shell command. this example is about build Nant by win form.

วันจันทร์ที่ 29 มีนาคม พ.ศ. 2553

Use Membership to get UserId

User.Identity have name but where userId

Here how to get that

MembershipUser CurrentUser = Membership.GetUser( User.Identity.Name ); // or use Membership.GetUser();
int userID = int.parce( CurrentUser.ProviderUserKey.ToString() );

by the way this mean when you want userID you must connect database so
check on this article for use other way to keep user

http://www.eggheadcafe.com/tutorials/aspnet/33d4018a-03cf-48aa-9b68-82ba27aa6af9/forms-auth-membership-r.aspx

and some customize provider will help this job done.

http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx

วันพฤหัสบดีที่ 25 มีนาคม พ.ศ. 2553

Add Header link in C# Code Behind and Front

use HtmlHead and HtmlLink for this job

HtmlHead header = (HtmlHead) Page.Header;
HtmlLink link = new HtmlLink();
link.Attributes.Add( "href", Page.ResolveClientUrl( "~/App_Themes/Default/Default.css" ) );
link.Attributes.Add( "type", "text/css");
link.Attributes.Add( "rel", "stylesheet");
header.Controls.Add(link);

วันอังคารที่ 9 กุมภาพันธ์ พ.ศ. 2553

When you need graph in WinForm (C#)

Try free graph

http://csharp-source.net/open-source/charting-and-reporting
http://www.nplot.com/
http://zedgraph.org/wiki/index.php?title=Main_Page

Or pay for it

http://www.gigasoft.com/netchart.html

Hope this help.

วันเสาร์ที่ 30 มกราคม พ.ศ. 2553

Use function show text in aspx page

This hard one when i found but write for don't forget this again.

Commonly we use <% =Function() %>

Or <% Response.Write( Function() ) %>

For this task

If this page you bind some data it will <%# Function() %>

PS. I hate to convert tag html in this blog for my self.

วันศุกร์ที่ 25 ธันวาคม พ.ศ. 2552

Break And Continue in loop?

for(int i = 0; i < 10; i++){
if(i == 0) break;
DoSomeThing(i);
}

for(int i = 0; i < 10; i++){
if(i == 0) continue;
DoSomeThing(i);
}

From above code is simple to explain

break is complete stop and exit loop
continue use to stop current loop but can continue to next loop