Sunday, July 19, 2015

XML formatdan JSON formatiga o`tkazish (example)

foydalanish:

public static T Get(string body){
       body.XmlToObject();
}
 dasturning kodi
internal static class XmlJsonExt
    {
        public static T Deserialize(this string data)
        {
            return JsonConvert.DeserializeObject(data);
        }
        public static T XmlToObject(this string data)
        {
            return CreateDocument(data).XmlToJson().Deserialize();
        }
        #region Utils
        private static XmlDocument CreateDocument(string body)
        {
            var document = new XmlDocument();
            document.InnerXml = body;
            return document;
        }
        private static string XmlToJson(this XmlDocument xmlDoc)
        {
            var sbJson = new StringBuilder();
            sbJson.Append("{ ");
            XmlToJsoNnode(sbJson, xmlDoc.DocumentElement, true);
            sbJson.Append("}");
            return sbJson.ToString();
        }
        //  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
        private static void XmlToJsoNnode(StringBuilder sbJson, XmlElement node, bool showNodeName)
        {
            if (showNodeName)
                sbJson.Append("\"" + SafeJson(node.Name) + "\": ");
            sbJson.Append("{");
            // Build a sorted list of key-value pairs
            //  where   key is case-sensitive nodeName
            //          value is an ArrayList of string or XmlElement
            //  so that we know whether the nodeName is an array or not.
            var childNodeNames = new SortedList();
            //  Add in all node attributes
            if (node.Attributes != null)
                foreach (XmlAttribute attr in node.Attributes)
                    StoreChildNode(childNodeNames, attr.Name, attr.InnerText);
            //  Add in all nodes
            foreach (XmlNode cnode in node.ChildNodes)
            {
                if (cnode is XmlText)
                    StoreChildNode(childNodeNames, "value", cnode.InnerText);
                else if (cnode is XmlElement)
                    StoreChildNode(childNodeNames, cnode.Name, cnode);
            }
            // Now output all stored info
            foreach (string childname in childNodeNames.Keys)
            {
                var alChild = (ArrayList) childNodeNames[childname];
                if (alChild.Count == 1)
                    OutputNode(childname, alChild[0], sbJson, true);
                else
                {
                    sbJson.Append(" \"" + SafeJson(childname) + "\": [ ");
                    foreach (var child in alChild)
                        OutputNode(childname, child, sbJson, false);
                    sbJson.Remove(sbJson.Length - 2, 2);
                    sbJson.Append(" ], ");
                }
            }
            sbJson.Remove(sbJson.Length - 2, 2);
            sbJson.Append(" }");
        }
        //  StoreChildNode: Store data associated with each nodeName
        //                  so that we know whether the nodeName is an array or not.
        private static void StoreChildNode(SortedList childNodeNames, string nodeName, object nodeValue)
        {
            // Pre-process contraction of XmlElement-s
            if (nodeValue is XmlElement)
            {
                // Convert   into "aa":null
                //          xx into "aa":"xx"
                var cnode = (XmlNode) nodeValue;
                if (cnode.Attributes.Count == 0)
                {
                    var children = cnode.ChildNodes;
                    if (children.Count == 0)
                        nodeValue = null;
                    else if (children.Count == 1 && (children[0] is XmlText))
                        nodeValue = ((XmlText) (children[0])).InnerText;
                }
            }
            // Add nodeValue to ArrayList associated with each nodeName
            // If nodeName doesn't exist then add it
            var oValuesAl = childNodeNames[nodeName];
            ArrayList valuesAl;
            if (oValuesAl == null)
            {
                valuesAl = new ArrayList();
                childNodeNames[nodeName] = valuesAl;
            }
            else
                valuesAl = (ArrayList) oValuesAl;
            valuesAl.Add(nodeValue);
        }
        private static void OutputNode(string childname, object alChild, StringBuilder sbJson, bool showNodeName)
        {
            if (alChild == null)
            {
                if (showNodeName)
                    sbJson.Append("\"" + SafeJson(childname) + "\": ");
                sbJson.Append("null");
            }
            else if (alChild is string)
            {
                if (showNodeName)
                    sbJson.Append("\"" + SafeJson(childname) + "\": ");
                var sChild = (string) alChild;
                sChild = sChild.Trim();
                sbJson.Append("\"" + SafeJson(sChild) + "\"");
            }
            else
                XmlToJsoNnode(sbJson, (XmlElement) alChild, showNodeName);
            sbJson.Append(", ");
        }
        // Make a string safe for JSON
        private static string SafeJson(string sIn)
        {
            var sbOut = new StringBuilder(sIn.Length);
            foreach (var ch in sIn)
            {
                if (Char.IsControl(ch) || ch == '\'')
                {
                    int ich = ch;
                    sbOut.Append(@"\u" + ich.ToString("x4"));
                    continue;
                }
                if (ch == '\"' || ch == '\\' || ch == '/')
                {
                    sbOut.Append('\\');
                }
                sbOut.Append(ch);
            }
            return sbOut.ToString();
        }
        #endregion
    }

C# Windows Formsda controllarni asynchrone usulda qo`shish

Odatsa asynchrone usulda controllarni formada joylashtirganda xatolik yuz beradi, ammo bunday qilmasa dastur sekin ishlashi tabiiy(agar katta dastur bo`lsa)

Buning yo`li oson:

Extention yozib olamiz ,

public static class ControlExt
    {
public static void Asynch(this TControl control, Action action)
            where TControl : Control
        {
            if (control.InvokeRequired)
                control.Invoke(action, control);
            else
                action(control);
        }
}

Extentionimiz tayyor, endi istagan yerda asynchrone usulda qo`shaveramiz,

   content.Asynch(delegate (Panel panel)
            {
                panel.Add(new Malumotnoma
                {
                    Name = "malumotnoma",
                    Dock = DockStyle.Fill,
                    EmployeeCode = Code
                }, "Malumotnoma");
            }); 

SQLite ma`lumotlar ba`zasini boshqarish tizimida qo`shimcha funksiya(custom function)lardan foydalanish

   Sqlite da atigi bir nechta funksiya bor, oddiy dasturlar uchun bu yetarli. Lekin murakkabroq so`rovlarni tuzish uchun bu albatta kamlik qiladi. Shu sababli Sqlite o`ziga qo`shimcha funksiya yozib undan keng foydalanishimiz uchun darvozalarini ochib qo`ygan.

   Biz istan tipdagi funksiyani qo`shib, unga maxsus logikani ishlatishimiz mumkin. Bu funksiyalar yacheykalar bo`yicha har bir ustun uchun alohida tepadan pastga qarab ishlaydi.
Aggregate funksiyalar 1 dona natija qaytaradi(masalan: sum, min, max,avg, count,..), Scalar funksiyalar satrlarning soniga teng natija qaytaradi.(length, lower, upper, day, year,...)

Foydalanish tartibi:

1. Yangi funksiyamizni Connection dan ro`yxatdan o`tkazamiz

_connection.BindFunction(new Lower());
2. Yangi funksiya tanasi
using System; using System.Data.SQLite; namespace SQLite.CustomFunction {     [SQLiteFunction(Name = "lower", Arguments = 1, FuncType = FunctionType.Scalar)]     public sealed class Lower : SQLiteFunction     {         public override object Invoke(object[] args)         {             return args.Length > 0 ? (args[0].ToString() ?? "").ToLower() : null;        }     } }
Sqliteda lower funksiyasi bor, ammo u krill harfi uchun ishlamaydi, bizni yangi funksiyamiz  Sqlite ning funksiyasini qayta yuklaydi(override, overload). Esda tuting: Bu so`rov sqlite browserida ishlamaydi, chunki uning kodida bu funksiya yo`q, faqat bizning ulanish usluniimizdagi ro`yxatga olingan dasturimizda ishlaydi

Saturday, June 28, 2014

Sonlarni so`zlarga aylantiradigan kichik va oson dastur


/**
 * Created by Virus on 6/28/2014.
 */
public class Simple {

    public static void main(String[] args) {

        String text = "346836873469720";

        String[] a = {"", "bir", "ikki", "uch", "to`rt", "besh", "olti", "yetti", "sakkiz", "to`qqiz"};
        String[] b = {"", "o`n", "yigirma", "o`ttiz", "qirq", "ellik", "oltmish", "yetmish", "sakson", "to`qson"};
        String[] c = {"", "ming", "million", "milliard", "trillion"};

        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < text.length(); i++) {

            if ((text.length() - i) % 3 == 0) {

                buffer.append(a[Integer.valueOf(text.substring(i, i + 1))]);
                buffer.append(" yuz ");
            } else if ((text.length() - i) % 3 == 1) {

                buffer.append(a[Integer.valueOf(text.substring(i, i + 1))]);
                buffer.append(" ");
                int h = text.length() / 3 - i / 3 - 1;
                buffer.append(c[h < 0 ? 0 : h]);
                buffer.append(" ");
            } else if ((text.length() - i) % 3 == 2) {

                buffer.append(b[Integer.valueOf(text.substring(i, i + 1))]);
                buffer.append(" ");
            }
        }

        System.out.print(buffer);
    }
}

Saturday, May 3, 2014

C# .NET da Excel ga jadval tuzib unga mos Bar Chart chizish dasturi

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection; 

Biz pastda Microsoft.Office.Interop.Excel ning o`rniga Excel deb yozib ketamiz(yozuvni qisqartirish maqsadida).

1-qadamda excel jadvaliga ma`lumot yozilgan
private void button1_Click(object sender, System.EventArgs e)
{
 Excel.Application oXL;
 Excel._Workbook oWB;
 Excel._Worksheet oSheet;
 Excel.Range oRng;

 try
 {
  //Start Excel and get Application object.
  oXL = new Excel.Application();
  oXL.Visible = true;

  //Get a new workbook.
  oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
  oSheet = (Excel._Worksheet)oWB.ActiveSheet;

  //Add table headers going cell by cell.
  oSheet.Cells[1, 1] = "First Name";
  oSheet.Cells[1, 2] = "Last Name";
  oSheet.Cells[1, 3] = "Full Name";
  oSheet.Cells[1, 4] = "Salary";

  //Format A1:D1 as bold, vertical alignment = center.
  oSheet.get_Range("A1", "D1").Font.Bold = true;
  oSheet.get_Range("A1", "D1").VerticalAlignment = 
   Excel.XlVAlign.xlVAlignCenter;
  
  // Create an array to multiple values at once.
  string[,] saNames = new string[5,2];
  
  saNames[ 0, 0] = "John";
  saNames[ 0, 1] = "Smith";
  saNames[ 1, 0] = "Tom";
  saNames[ 1, 1] = "Brown";
  saNames[ 2, 0] = "Sue";
  saNames[ 2, 1] = "Thomas";
  saNames[ 3, 0] = "Jane";
  saNames[ 3, 1] = "Jones";
  saNames[ 4, 0] = "Adam";
  saNames[ 4, 1] = "Johnson";

         //Fill A2:B6 with an array of values (First and Last Names).
         oSheet.get_Range("A2", "B6").Value2 = saNames;

  //Fill C2:C6 with a relative formula (=A2 & " " & B2).
  oRng = oSheet.get_Range("C2", "C6");
  oRng.Formula = "=A2 & \" \" & B2";

  //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
  oRng = oSheet.get_Range("D2", "D6");
  oRng.Formula = "=RAND()*100000";
  oRng.NumberFormat = "$0.00";

  //AutoFit columns A:D.
  oRng = oSheet.get_Range("A1", "D1");
  oRng.EntireColumn.AutoFit();

  //Manipulate a variable number of columns for Quarterly Sales Data.
  DisplayQuarterlySales(oSheet);

  //Make sure Excel is visible and give the user control
  //of Microsoft Excel's lifetime.
  oXL.Visible = true;
  oXL.UserControl = true;
 }
 catch( Exception theException ) 
 {
  String errorMessage;
  errorMessage = "Error: ";
  errorMessage = String.Concat( errorMessage, theException.Message );
  errorMessage = String.Concat( errorMessage, " Line: " );
  errorMessage = String.Concat( errorMessage, theException.Source );

  MessageBox.Show( errorMessage, "Error" );
 }
}

2-qadamda esa chart chizilgan

private void DisplayQuarterlySales(Excel._Worksheet oWS)
{
 Excel._Workbook oWB;
 Excel.Series oSeries;
 Excel.Range oResizeRange;
 Excel._Chart oChart;
 String sMsg;
 int iNumQtrs;

 //Determine how many quarters to display data for.
 for( iNumQtrs = 4; iNumQtrs >= 2; iNumQtrs--)
 {
  sMsg = "Enter sales data for ";
  sMsg = String.Concat( sMsg, iNumQtrs );
  sMsg = String.Concat( sMsg, " quarter(s)?");

  DialogResult iRet = MessageBox.Show( sMsg, "Quarterly Sales?", 
   MessageBoxButtons.YesNo );
  if (iRet == DialogResult.Yes)
   break;
 }

 sMsg = "Displaying data for ";
 sMsg = String.Concat( sMsg, iNumQtrs );
 sMsg = String.Concat( sMsg, " quarter(s)." );

 MessageBox.Show( sMsg, "Quarterly Sales" );

 //Starting at E1, fill headers for the number of columns selected.
 oResizeRange = oWS.get_Range("E1", "E1").get_Resize( Missing.Value, iNumQtrs);
 oResizeRange.Formula = "=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\"";

 //Change the Orientation and WrapText properties for the headers.
 oResizeRange.Orientation = 38;
 oResizeRange.WrapText = true;

 //Fill the interior color of the headers.
 oResizeRange.Interior.ColorIndex = 36;

 //Fill the columns with a formula and apply a number format.
 oResizeRange = oWS.get_Range("E2", "E6").get_Resize( Missing.Value, iNumQtrs);
 oResizeRange.Formula = "=RAND()*100";
 oResizeRange.NumberFormat = "$0.00";

 //Apply borders to the Sales data and headers.
 oResizeRange = oWS.get_Range("E1", "E6").get_Resize( Missing.Value, iNumQtrs);
 oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;

 //Add a Totals formula for the sales data and apply a border.
 oResizeRange = oWS.get_Range("E8", "E8").get_Resize( Missing.Value, iNumQtrs);
 oResizeRange.Formula = "=SUM(E2:E6)";
 oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).LineStyle 
  = Excel.XlLineStyle.xlDouble;
 oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).Weight 
  = Excel.XlBorderWeight.xlThick;

 //Add a Chart for the selected data.
 oWB = (Excel._Workbook)oWS.Parent;
 oChart = (Excel._Chart)oWB.Charts.Add( Missing.Value, Missing.Value, 
  Missing.Value, Missing.Value );

 //Use the ChartWizard to create a new chart from the selected data.
 oResizeRange = oWS.get_Range("E2:E6", Missing.Value ).get_Resize( 
  Missing.Value, iNumQtrs);
 oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,
  Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value, 
  Missing.Value, Missing.Value, Missing.Value, Missing.Value );
 oSeries = (Excel.Series)oChart.SeriesCollection(1);
 oSeries.XValues = oWS.get_Range("A2", "A6");
 for( int iRet = 1; iRet <= iNumQtrs; iRet++)
 {
  oSeries = (Excel.Series)oChart.SeriesCollection(iRet);
  String seriesName;
  seriesName = "=\"Q";
  seriesName = String.Concat( seriesName, iRet );
  seriesName = String.Concat( seriesName, "\"" );
  oSeries.Name = seriesName;
 }                
 
 oChart.Location( Excel.XlChartLocation.xlLocationAsObject, oWS.Name );

 //Move the chart so as not to cover your data.
 oResizeRange = (Excel.Range)oWS.Rows.get_Item(10, Missing.Value );
 oWS.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top;
 oResizeRange = (Excel.Range)oWS.Columns.get_Item(2, Missing.Value );
 oWS.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;
}


Monday, March 3, 2014

Ikki va undan ortiq, ko`p o`lchovli massivlar haqida

Ikki va undan ortiq, ko`p o`lchovli massivlar haqida

Bir o`lchovli massivlar vector(vektor) deyiladi.
Ikki o`lchovli massiv esa matrix(matritsa) deyiladi.
Vektorlar - int[] a={2,3,4,54,5}; (C#, Java)
Matritsa - int[,] a={{3,5,3},{3,5,6},{544,3,64},{654,0,-5}}; (C#,Java)
Massivning ixtiyoriy elementini o`zgartirishda uning indexi(pozitsiyasi) orqali o`zgartiriladi.
a[4]=2; (5- element o`zgartirildi)

b[3]="3423"; (4- element o` zgartirildi)

Main funksiyasi

Main funksiyasi(asosiy funksiya) - Barcha dasturlarda mazkur funksiya bor. Bu funksiya dasturning kirish eshigi, dastur ishga tushirilganda avtomatik shu funksiyaga murojaat bo`lib, shu funksiyada qaysi funksiya ko`rsatilsa shu yerga yo`naltiriladi. agar hech bir funksiyaga murojaat qilinmagan bo`lsa boshqa class yoki funksiyalarga murojaat qilmasdan dastur ish faoliyatini tugatadi.