Wednesday, December 12, 2012

set focus for text box in asp.net

in angular tags "input onfocus="this.form.focusedField.value = this.name;" name="TextBoxMSISDN" id="TextBoxMSISDN1" type="text" "

Wednesday, October 31, 2012

Linq to SQL Insert update delete read operations


  DataClasses1DataContext dbcontext = new DataClasses1DataContext();

        //insert
        protected void Button1_Click(object sender, EventArgs e)
        {

            dbcontext = new DataClasses1DataContext();
            PRDErrorCodes_ cd = new PRDErrorCodes_
                {

                    ErrorCode = "test",
                    ErrorDescription = "testDesc"

                };
            dbcontext.PRDErrorCodes_s.InsertOnSubmit(cd);
            dbcontext.SubmitChanges();
            Response.Write("successfull inserted");
        }
        //update
        protected void Button2_Click(object sender, EventArgs e)
        {
            var det = (from p in dbcontext.PRDErrorCodes_s
                       where p.ErrorCode.Equals("test")
                       select p).SingleOrDefault();

            if (det != null)
            {
                det.ErrorCode = "new test";
                det.ErrorDescription = "new test Desc";
                dbcontext.SubmitChanges();
                Response.Write("successfull saved");
            }
        }
        //delete
        protected void Button3_Click(object sender, EventArgs e)
        {
            PRDErrorCodes_ det = (from p in dbcontext.PRDErrorCodes_s
                                  where p.ErrorCode.Equals("test")
                                  select p).SingleOrDefault();

            if (det != null)
            {
                dbcontext.PRDErrorCodes_s.DeleteOnSubmit(det);
                dbcontext.SubmitChanges();
                Response.Write("deleted saved");
            }
        }
        //read
        protected void Button4_Click(object sender, EventArgs e)
        {
            var det = (from p in dbcontext.PRDErrorCodes_s
                       select p).ToList();
            GridView1.DataSource = det;
            GridView1.DataBind();
        }

Thursday, October 25, 2012

Accessing registery keye in 64 bit windows 7 machine


For information into our implicit knowledge bank.

If you on 64 bit machine and need to read registry, sometimes you need to manually copy the keys under the Wow6432Node node as shown below.




Accessing selected item from combo box wen items are added dynamically using List item


using System.Web.UI.WebControls;


//add items to combobox

 comboBox1.Items.Clear();
            List dataBundles = getDataVodacomDataBundles();
            //Value="UDB75MB">Data Bundle 75MB (R88.00)<
            foreach (sp_GetProductDataBundlesResult dataEntry in dataBundles)
            {
                string tssProductBundleValue = String.Format("{0:C0}", dataEntry.TSSProductBundleValue);
                String text = dataEntry.TSSProductBundleName + "(" + tssProductBundleValue + ")";
                String value = "" + dataEntry.TSSProductBundleMegs;
           
                ListItem li = new ListItem(text, value);
                comboBox1.Items.Add(li);
            }


string selectedVAL= ((System.Web.UI.WebControls.ListItem)(comboBox1.SelectedItem)).Value;

Wednesday, October 17, 2012

setting c# windows service in debug mode


setting service in debug mode


just comment the below lines

 ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new CLIMimoneyTestAsync()
            };
            ServiceBase.Run(ServicesToRun);



and write this,uncomment the above lines when, debugging is done and you want to start the service

 //CLITest service = new CLITest ();
            //service.OnDebug();
            //System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

c# timer example


using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Normally, the timer is declared at the class level, 
        // so that it stays in scope as long as it is needed. 
        // If the timer is declared in a long-running method,   
        // KeepAlive must be used to prevent the JIT compiler  
        // from allowing aggressive garbage collection to occur  
        // before the method ends. You can experiment with this 
        // by commenting out the class-level declaration and  
        // uncommenting the declaration below; then uncomment 
        // the GC.KeepAlive(aTimer) at the end of the method. 
        //System.Timers.Timer aTimer; 

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use 
        // KeepAlive to prevent garbage collection from occurring 
        // before the method ends. 
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

Tuesday, October 16, 2012

Installing c# windows service using cmd

C:\Windows\Microsoft.NET\Framework\v2.0.50727\installutil   xxxxx.exe


For EG:

"C:\Windows\Microsoft.NET\Framework\v2.0.50727\installutil"  "C:\Program Files\Virtual Payment Solutions\PRD Test\PRDTest.exe"

Thursday, October 11, 2012

FTP File Upload using FtpWebRequest in .Net C#


using System.Net;
using System.IO; 


 public void ftpfile(string ftpfilepath, string inputfilepath)
    {
        string ftphost = "127.0.0.1";
        //here correct hostname or IP of the ftp server to be given

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
        FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
        ftp.Credentials = new NetworkCredential("userid", "password");
        //userid and password for the ftp server to given

        ftp.KeepAlive = true;
        ftp.UseBinary = true;
        ftp.Method = WebRequestMethods.Ftp.UploadFile;
        FileStream fs = File.OpenRead(inputfilepath);
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        fs.Close();
        Stream ftpstream = ftp.GetRequestStream();
        ftpstream.Write(buffer, 0, buffer.Length);
        ftpstream.Close();
    }

Function can be used as 

ftpfile(@"/testfolder/testfile.xml", @"c:\testfile.xml");

Tuesday, October 2, 2012

Accessing Check box inside a list view c# windows



richTextBox2.Text = String.Empty;
foreach (ListViewItem item in listView1.Items)
{
    if (item.Checked)
    {
        richTextBox2.Text += item.SubItems[1].Text + Environment.NewLine;
    }
}
You could also write this with a LINQ expression and String.Join
richTextBox2.Text = String.Join(Environment.NewLine,
    from item in listView1.Items.OfType<ListViewItem>()
    where item.Checked
    select item.SubItems[1].Text);


http://stackoverflow.com/questions/10908416/how-to-grab-subitems-with-checkboxes-in-listview




private bool allowCheck = false;
private bool preventOverflow = true;
private void lstvwRaiseLimitStore_MouseClick(object sender, MouseEventArgs e)
    {
        preventOverflow = false;
        ListViewItem item = lstvwRaiseLimitStore.HitTest(e.X, e.Y).Item;
        if (item.Checked)
        {
            allowCheck = true;
            item.Checked = false;
        }
        else
        {
            allowCheck = true;
            item.Checked = true;
        }
    }
private void lstvwRaiseLimitStore_ItemChecked(object sender, ItemCheckedEventArgs e)
    {
        if (!preventOverflow)
        {
            if (!allowCheck)
            {
                preventOverflow = true;
                e.Item.Checked = !e.Item.Checked;
            }
            else
                allowCheck = false;
        }
    }
OR
private bool allowCheck = false;
private bool preventOverflow = true;

private void lstvwRaiseLimitStore_MouseClick(object sender, MouseEventArgs e)
    {
        preventOverflow = false;
        ListViewItem item = lstvwRaiseLimitStore.HitTest(e.X, e.Y).Item;
        if (item.Checked)
        {
            allowCheck = true;
            item.Checked = false;
        }
        else
        {
            allowCheck = true;
            item.Checked = true;
        }
    }

private void lstvwRaiseLimitStore_ItemChecked(object sender, ItemCheckedEventArgs e)
    {
        if (!preventOverflow)
        {
            if (!allowCheck)
            {
                preventOverflow = true;
                e.Item.Checked = !e.Item.Checked;
            }
            else
                allowCheck = false;
        }
    }

Thursday, September 27, 2012

Creating and renaming Logs when the size exceeds 400 MB


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace readtxt
{
    public class CreateLog
    {
        string fileName = "";
        public string CreateLogFile()
        {
            return getsizeofFile();

        }

        public string getsizeofFile()
        {
            fileName = @"C:\Program Files\Virtual Payment Solutions\TSS 1.5\Retail.log";
            FileInfo f = new FileInfo(fileName);
            long s1 = f.Length;
            string size = GetFileSize(s1);
            createNewLogFile(size, fileName);
            return size;
        }

        public void createNewLogFile(string size, string fileLoc)
        {
            FileStream fs = null;
            if (size.Contains("MB"))
            {
                Regex re = new Regex(@"\d+");
                Match m = re.Match(size);
                if (Convert.ToInt64(m.Value) >= 400)
                {
                    string fileLocCopy = @"C:\Program Files\Virtual Payment Solutions\TSS 1.5\Retail_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
                    if (File.Exists(fileLoc))
                    {
                        File.Move(fileLoc, fileLocCopy);
                        if (File.Exists(fileLoc))
                        {
                            File.Delete(fileLoc);
                            using (fs = File.Create(fileLoc))
                            {

                            }
                        }
                        else if (!File.Exists(fileLoc))
                        {
                            using (fs = File.Create(fileLoc))
                            {

                            }
                        }
                    }
                    else if (!File.Exists(fileLoc))
                    {
                        using (fs = File.Create(fileLoc))
                        {

                        }
                    }
                }

            }

        }

        public static string GetFileSize(long Bytes)
        {
            if (Bytes >= 1073741824)
            {
                Decimal size = Decimal.Divide(Bytes, 1073741824);
                return String.Format("{0:##.##} GB", size);
            }
            else if (Bytes >= 1048576)
            {
                Decimal size = Decimal.Divide(Bytes, 1048576);
                return String.Format("{0:##.##} MB", size);
            }
            else if (Bytes >= 1024)
            {
                Decimal size = Decimal.Divide(Bytes, 1024);
                return String.Format("{0:##.##} KB", size);
            }
            else if (Bytes > 0 & Bytes < 1024)
            {
                Decimal size = Bytes;
                return String.Format("{0:##.##} Bytes", size);
            }
            else
            {
                return "0 Bytes";
            }
        }
    }

}

Tuesday, September 18, 2012

USING single quote in SQL insert statement

INSERT INTO [CLITransaction](CLITransactionTypeID,ReceivedDateTime,ContentDetail04) VALUES(7,'10-10-2012','Greg''s'+' Company') 

Wednesday, September 12, 2012

Enable/Disable Proxy in IE through C#

// ProxyEnable == 0 means the proxy is on
// ProxyEnable == 1 means the proxy is off




string key = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
                string serverName = ConfigurationManager.AppSettings["proxyAddress"];
                int port = Convert.ToInt32(ConfigurationManager.AppSettings["proxyPort"]);
                string proxyy = serverName + ":" + port;

                RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(key, true);
                RegKey.SetValue("ProxyServer", proxyy);
                RegKey.SetValue("ProxyEnable", 1);

                proxy = new WebProxy(proxyy, true);;
                proxy.Credentials = CredentialCache.DefaultCredentials;

                proxy.BypassProxyOnLocal = true;

Tuesday, September 11, 2012

Passing Subqueries to Stored procedure


ALTER PROC [dbo].[sp_GetPinnedSalesDetail]
    -- Add the parameters for the stored procedure here
    @orderNumber varchar(50) = 'VPSORD8013',
 @merchantAccount varchar(50),
    @userlogin  varchar(50)
AS
BEGIN
DECLARE @ReprintCount int
DECLARE @UserName varchar(50)

    SET NOCOUNT ON;
SET @ReprintCount=(SELECT COUNT(*) AS Expr1 FROM  WebAdminDBTest.dbo.AuditTable WHERE
 (WebAdminDBTest.dbo.AuditTable.masterAccount = @merchantAccount) AND (WebAdminDBTest.dbo.AuditTable.userName = @userlogin)
AND WebAdminDBTest.dbo.AuditTable.description = @orderNumber)


SET @UserName=(SELECT WebAdminDBTest.dbo.WebUserSales.subuser_name FROM  WebAdminDBTest.dbo.WebUserSales WHERE (WebAdminDBTest.dbo.WebUserSales.voucher_orderno = @orderNumber))


SELECT     @UserName AS username,@ReprintCount AS reprintcount,dbo.TSSMerchant.MerchantAccount, dbo.TSSMerchant.CompanyName,
dbo.TMPVoucherOrder.OrderNo,
 dbo.TMPVendor.CompanyName AS Vendor,
 TMPVendor.Description1 AS Instruction1, TMPVendor.Description2 AS Instruction2,
TMPVendor.Description3 AS Instruction3, TMPVendor.Description4 AS Instruction4, TMPVoucher.ExpiryDate,
dbo.TMPVoucherType.Description as VoucherType,
                      dbo.TMPVoucherType.VoucherCode, dbo.TMPVoucherOrderDetail.TotalSellingPrice,TMPVoucherType.FaceValuePrice,TMPVoucherType.AirtimeWindow, dbo.TMPVoucherOrderDetail.Quantity, dbo.TMPVoucher.S1,
                      dbo.TMPVoucher.S2, dbo.TMPVoucher.S3,dbo.TMPVoucher.RechargePin, dbo.TMPServerOrder.ImportDate, dbo.TMPVoucherOrder.OrderDate
FROM         dbo.TMPVoucherType INNER JOIN
                      dbo.TMPVoucher ON dbo.TMPVoucherType.TMPVoucherTypeID = dbo.TMPVoucher.TMPVoucherTypeID INNER JOIN
                      dbo.TMPVoucherOrder ON dbo.TMPVoucher.TMPVoucherOrderID = dbo.TMPVoucherOrder.TMPVoucherOrderID INNER JOIN
                      dbo.TMPServerOrder ON dbo.TMPVoucher.TMPServerOrderID = dbo.TMPServerOrder.TMPServerOrderID INNER JOIN
                      dbo.TSSMerchant ON dbo.TMPVoucher.TSSMerchantID = dbo.TSSMerchant.TSSMerchantID INNER JOIN
                      dbo.TMPVendor ON dbo.TMPVoucherType.TMPVendorID = dbo.TMPVendor.TMPVendorID INNER JOIN
                      dbo.TMPVoucherOrderDetail ON dbo.TMPVoucherType.TMPVoucherTypeID = dbo.TMPVoucherOrderDetail.TMPVoucherTypeID AND
                      dbo.TMPVoucherOrder.TMPVoucherOrderID = dbo.TMPVoucherOrderDetail.TMPVoucherOrderID
WHERE     (dbo.TMPVoucherOrder.OrderNo = @orderNumber);
END

Tuesday, September 4, 2012

Reading XML Document using XML Reader C#

Reading XML Document using XML Reader C#



StringBuilder myresult = new StringBuilder(); Dictionary myHeader = new Dictionary();
string response1 =










XmlReader xRead = XmlReader.Create(new System.IO.StringReader(response1));
XmlReader result = xRead;
public string processXMLTextReader(XmlReader xRead, String element)
{
                       value = "";
                      try
                           {
                               while (xRead.Read())
                                 {
                                    if (xRead.NodeType == XmlNodeType.Element)
                                           {
                                               if (xRead.Name == element)
                                              {
                                                  value = xRead.GetAttribute("AccountNo").ToString();                                             
                                                  break;
                                              }
                                           }
                                        }
                                 }
                                catch (Exception e)
                                {
                               value = e.Message;

                               }
  return value;
 }


Sample 2:

public Dictionary(int,string) processReader(XmlReader xRead, String element)
{
                   xRead.ReadToFollowing(element);
                   xRead.MoveToFirstAttribute();
                  Dictionary(int,string) mydict = new Dictionary();
              for (int i = 0; i < xRead.AttributeCount; i++)
                {
                        //string genre = .ToString(); 
                         mydict.Add(i, xRead.GetAttribute(i)); 
                   }
                 return mydict;
}

reading Response:


//the below method call returns result in XML format string response = ConfirmMuncipality(mRequest);


XmlReader xReadx = XmlReader.Create(new System.IO.StringReader(response(OR)(Response1)));
 XmlReader resultb = xReadb;
  myHeader = new Dictionary();
//pass the name of the XML element you want to get attributes for
//for EG: ns0:ConfirmPaymentItems
  myHeader = syntelTest.processReader(resultx, "ns0:ConfirmPaymentItems");
  if (myHeader.Count == 1)
            {
string AccountNo="";
                AccountNo = myHeader[0];
             
            }





Reading XML file


http://forum.codecall.net/topic/58239-c-tutorial-reading-and-writing-xml-files/
http://csharptutorial.blogspot.com/2006/10/reading-xml-fast.html
using System;
using System.Collections.Generic;
using System.Xml;
namespace TempCSharp
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
XmlNodeList customers = doc.SelectNodes("//customer");
foreach (XmlNode customer in customers)
{
Console.WriteLine("Age = {0}, Gender = {1}",
customer.Attributes["age"].Value, customer.Attributes["gender"].Value);
}
}
}
}

Monday, September 3, 2012

Round double in two decimal places in C#


You can try any of the following ways:

inputValue = Math.Round(inputValue, 2);

decimalVar.ToString ("#.##");
ToString("0.00"); //2dp Number
ToString("n2"); // 2dp Number
ToString("c2"); // 2dp currency


http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Wednesday, August 29, 2012

XML node


using System; using System.IO; using System.Xml; public class Sample
{
public static void Main()
{

XmlDocument doc = new XmlDocument();
doc.LoadXml("" +
"Pride And Prejudice" +
"
");
XmlNode root = doc.DocumentElement;
//Create a new node.
XmlElement elem = doc.CreateElement("price");
elem.InnerText="19.95";
//Add the node to the document.
root.AppendChild(elem);
Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out);
}
}
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild.aspx

Monday, August 27, 2012

Create, Read, Write, Copy, Move and Delete a Text File using C#


private void btnCreate_Click(object sender, EventArgs e)
{
FileStream fs = null;
if (!File.Exists(fileLoc))
{
using (fs = File.Create(fileLoc))
{
}
}
}
http://www.dotnetcurry.com/ShowArticle.aspx?ID=144

Get Size of file on disk C#


fileName = @"C:\Program Files\CLIRetail.log";
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
string size = GetFileSize(s1);
Console.WriteLine("Size : " + size);


public static string GetFileSize(long Bytes) {
if (Bytes >= 1073741824) {
Decimal size = Decimal.Divide(Bytes, 1073741824);
return String.Format("{0:##.##} GB", size);
}
else if (Bytes >= 1048576)
{
Decimal size = Decimal.Divide(Bytes, 1048576);
return String.Format("{0:##.##} MB", size);
}
else if (Bytes >= 1024)
{
Decimal size = Decimal.Divide(Bytes, 1024);
return String.Format("{0:##.##} KB", size);
}
else if (Bytes > 0 & Bytes < 1024)
{
Decimal size = Bytes;
return String.Format("{0:##.##} Bytes", size);
}
else
{
return "0 Bytes";
}

Friday, July 27, 2012

Sample Linq queries

http://msdn.microsoft.com/en-us/vstudio/bb688084.aspx
var queryAllCustomers = from cust in customers
select cust;

var queryLondonCustomers = from cust in customers
where cust.City == "London"
select cust;



var queryLondonCustomers = from cust in customers
where cust.City == "London"
select cust;

Grouping
// queryCustomersByCity is an IEnumerable>
var queryCustomersByCity =
from cust in customers
group cust by cust.City;

// customerGroup is an IGrouping
foreach (var customerGroup in queryCustomersByCity)
{
Console.WriteLine(customerGroup.Key);
foreach (Customer customer in customerGroup)
{
Console.WriteLine(" {0}", customer.Name);

}
}
// custQuery is an IEnumerable>
var custQuery =
from cust in customers
group cust by cust.City into custGroup
where custGroup.Count() > 2
orderby custGroup.Key
select custGroup;



var innerJoinQuery =
from cust in customers
join dist in distributors on cust.City equals dist.City
select new { CustomerName = cust.Name, DistributorName = dist.Name };





Complex Ling query with inner joins
from pListNames in _etblPriceListNames
join priceListPrices in _etblPriceListPrices on new { PL = pListNames.IDPriceListName } equals new { PL = priceListPrices.IPriceListNameID }
join client in Clients on new { C = pListNames.IDPriceListName } equals new { C = (int)client.IARPriceListNameID }
join sales in SalesReps on new { S = (int)client.RepID } equals new { S = (int)sales.IdSalesRep }
join stkitem in StkItems on new { STK = priceListPrices.IStockID } equals new { STK = stkitem.StockLink }
join grptbl in GrpTbls on new { GRP = stkitem.ItemGroup } equals new { GRP = grptbl.StGroup }
join whseStk in WhseStks on new { WHE = stkitem.StockLink } equals new { WHE = whseStk.WHStockLink }
join whseMST in WhseMsts on new { wMST = (int)whseStk.WHWhseID } equals new { wMST = (int)whseMST.WhseLink }
where (stkitem.ItemActive == true) && (stkitem.WhseItem == true) &&
(client.On_Hold == false) &&
stkitem.UlIISubCategory == "Samsung" &&
stkitem.UlIISubCategory != null &&
stkitem.UlIISubCategory != " " &&
stkitem.Code == "BATSAB3310L" &&
grptbl.Description == "BATTERIES" &&
client.Account == "CEL07" &&
whseMST.Code == "ZZZ" &&
whseStk.WHQtyOnHand > 0
orderby
pListNames.CDescription,
grptbl.Description, stkitem.UlIISubCategory,
stkitem.Code, client.Account
select new
{ warehouse = whseMST.Code, pricelist = pListNames.CDescription, ItemGroup = grptbl.Description, SubCategory = stkitem.UlIISubCategory, StockCode = stkitem.Code, Description = stkitem.Description_1, ClientAccount = client.Account, CompanyName = client.Name, SalesRep = sales.Name, ExclPrice = priceListPrices.FExclPrice, fInclPrice = priceListPrices.FInclPrice, QTYOnHand = whseStk.WHQtyOnHand, QTYOnSalesOrders = whseStk.WHQtyOnSO, QTYOnPurchaseOrders = whseStk.WHQtyOnPO } }

Friday, July 20, 2012

Access Command Line Arguments in C#

www.c-sharpcorner.com/uploadfile/mahesh/cmdlineargs03212006232449pm/cmdlineargs.aspx

Thursday, July 19, 2012

Add webreference in windows application

Adding web reference in C# Windows app
Steps
1:Add the below lines in app.config file
then go to solution explorer,click on add services reference
2:click on advanced button
3:then click add web reference
4:then add respective web reference

Friday, July 13, 2012

Renaming table sql:

sp_rename 'old_table_name', new_table_name'

delete a service from services when it is no longer used or still resent in services after uninstalling it

delete a service from services when it is no longer used or still resent in services after uninstalling it sc.exe delete < service name > OR Just delete it from registery

Thursday, July 5, 2012

Paging in RDLC

=Int((RowNumber(Nothing)-1)/8) add a group to your table in Report by going to table properties and then add the above line