Monday, April 30, 2012

IIS, DLL and Exhange

Sunday, April 29, 2012

Catch Enter on ASP Form example

1st thing u must know - u cant do it directly like any other controls.OnTextChange
therefor the good lord gave us JS!
put this script on:
<script language="javascript" type="text/javascript">   
   document.onkeypress = function() {      
      document.getElementById("Hidden1").value="false";      
      if (window.event.keyCode==13){
          alert(window.event.keyCode); //to see that it works      
      }
      document.getElementById("Hidden1").value="true";           
      form1.submit();        
   }
</script>

This on the aspx page :
<input id="Hidden1" type="hidden" runat="server"/>

and on the cs page:
protected void Page_Load(object sender, EventArgs e)
{
    if (Hidden1.Value == "true")
         TextBox1.Text = "We Got an Enter to the Server Side";
    else                
         TextBox1.Text = "just a page load, no enter";        
}
//put a TextBox with width 300, run the page and press enter :)

Wednesday, April 25, 2012

Access: Call a Func from another Form with example

the main points are:
1 - make the func public (daa but we forget) and "As Variant"
2 - actualy find the damn form and how to call the func
when u have that u have it (double daa)
and for the example
call a func in a subform from the main form
the func:
Public Function Call_payment_date_AfterUpdate() As Variant
       payment_date_AfterUpdate
End Function
from the main form (in a func o/c)
Forms!ei_main_form![ei_purchase subsubform].Form.Call_payment_date_AfterUpdate

from a stand alone form call a func in another form
the func
Public Function Call_Refresh_From_ei_main() As Variant    Me.Refresh
End Function

the call
Forms!ei_main_form.Call_Refresh_From_ei_main

תקשורת על גבי רשת האינטרנט מאת ALEXSUH

כל התודות לאלכס מפורום תפוז שהשקיע בנו כ"כ, הכל מועתק ללא שינוי

מה שאתה מדבר עליו נקרא פרוטוקול SOAP לתקשורת על גבי רשת האינטרנט.
זה פרוטוקול מקובל בד"כ אם אתה שולט הן בצד השרת וצד הלקוח .
סיומת ASMX מקובלת במימוש הפרוטוקול על גבי שרתי MISCROSOFT מסוג ASP.NET אך הפוטוקול אינו ייחודי ל MIcrosoft וניתן לשתמש בכל סיומת כל עוד עומדים בתקנים של הפרוטוקול.
בעולם האמיתי לא תמיד ניתן לקבל שירות נוח של קליק וגמרנו ומדי פעם צריך לבצע קצת עבודה ע"מ לקבל את הנתונים.
במקרה הנ"ל אין מדובר בשרות מסוג SOAP אלא בקובץ XML רגיל אשר מתעדכן אחת לכמה זמן (לדעתי פעמיים שלוש ביום) וניתן להורדה ישירה תוך שימוש בפרוטוקול HTTP רגיל.

קצת רקע
עוד מידע על לפרוטוקול SOAP
http://www.w3schools.com/soap/default.asp

פרוטוקול HTTP עליו פרוטוקול SOAP מבוסס
http://he.wikipedia.org/wiki/Hypertext_Transfer_Pr...

פרוטוקולים נוספים המבוססים על HTTP
REST
http://www.infoq.com/articles/rest-introduction
XML-RPC (המיושן אך עדיין נפוץ בפינות נשכחות של האינטרנט)
http://en.wikipedia.org/wiki/XML-RPC

עכשיו.
לגבי השיטה שהצעתי - עליך קודם כל להוריד את הקובץ
http://www.csharp-examples.net/download-files/

לקרוא את הקובץ על מנת להגיע לנתונים
http://support.microsoft.com/kb/307548

יתכן שתצתרך להעזר ב DOM , XPATH או XQUERY לשם כך
http://support.microsoft.com/kb/317662
http://stackoverflow.com/questions/9173991/how-to-...
http://www.csharp-examples.net/xpath-top-xml-nodes...
(ממליץ ללככת על XPATH)

ולבסוף להציב את הנתונים בממשק המשתמש שבנית (בין אם זה וובי או לא)

בהצלחה.

Sunday, April 22, 2012

Ajax Image Asp example

1st we need a source to return a requested img, i'll use an ASP page like this (ASPX part doesnt matter, u may not touch it), lets call it ReturnPic.aspx
protected void Page_Load(object sender, EventArgs e)
{
    System.Drawing.Image img = System.Drawing.Image.FromFile(         Request.QueryString["file"].ToString());
    //u have to use the system.drawing or ull get the we.ui.image    string ext = Path.GetExtension(Request.QueryString["file"].ToString());
    if (ext == "jpg")
       ext = "jpeg";
   *MemoryStream ms = new MemoryStream();
    img.Save(ms, System.Drawing.Imaging.
    ImageFormat.Jpeg);
    ms.Close();
    byte[] content = ms.ToArray();
    Response.ContentType = "image/" + ext;
    Response.BinaryWrite(content);
}
u can always use ImageConverter
http://www.vcskicks.com/image-to-byte.php

now here is my default page, i used 2 method to return the pic by ajax, one with UpdatePanel and the other with WebMethod both explained in my post:
http://bresleveloper.blogspot.com/2012/04/ajax-3-simle-ways.html
o/c the ddl was filled in the pageLoad
<script type="text/javascript">
  function ChangeSource(times){
     var e = document.getElementById("ddlImg");
     var num = 0;
     num = num + e.options[e.selectedIndex].value;
     PageMethods.ChangeSource(num, ChangeSourceComplete);
}
function ChangeSourceComplete(result){
   var div = document.getElementById("img2");
   div.src = result;
}            </script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePageMethods="true" >   --->>> if ur planing use the webmethod
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:Button runat="server" Text="Button" ID="btnChangeImg"
        onclick="btnChangeImg_Click" /> <br />
    <img id="img1" alt="" src="" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
      
<asp:DropDownList ID="ddlImg" runat="server">
</asp:DropDownList><br />
<input id="Button1" type="button" value="button"
     onclick="ChangeSource();" /><br />
<img id="img2" alt="" src="" />
</div>
</form>
</body>
</html>

CS:
for the UpdatePanel Btn:
protected void btnChangeImg_Click(object sender, EventArgs e)
{
     Random rnd = new Random();
     int r = rnd.Next(3);
     string file = "";
     switch (r)
    {
          case 0: file = @"H:\My Pictures\white-light1.jpg"; break;
          case 1: file = @"H:\My " +
                    Pictures\p4788853bb1286d6947587e8ec3b6090f2181898.gif"; break;
          case 2: file = @"H:\My Pictures\have-a-nice-day.jpg"; break;
          default: break;
    }
    img1.Src = "ReturnPic.aspx?file=" + file;
}

for the lower part and its JS code u need
[WebMethod]
public static string ChangeSource(int num)
{
    string file = "";
    switch (num)
    {
          case 0: file = @"H:\My Pictures\white-light1.jpg"; break;
          case 1: file = @"H:\My " +
                     Pictures\p4788853bb1286d6947587e8ec3b6090f2181898.gif"; break;
          case 2: file = @"H:\My Pictures\have-a-nice-day.jpg"; break;
          default: break;
    }    return "ReturnPic.aspx?file=" + file;
}


just try it - its cool

Thursday, April 19, 2012

Linq Vs Mysql

the answer - mysql (and i guess any sql kind) is about 500-1000 times faster
BUT, yes we have a HUGE but - this is only for the query time the SQL query himself from the DB.
then we have transportation - there, the bigger the data requested is the more u might be better using Linq, AND we have a BUT here too - Linq depends on ur computer resources so...

anyway on my job's machine i did a query from a table with 300K+ rows.
when the answer was less than 100 rows the mysql was that fast.
when i tried something with 60k+ rows and another with 250K rows the Linq became 60%+ faster.
*!this does not include the initial query of all the 300K lines

Soooo...   for me it means that if i am gonna query something alot it might be better a Linq or even 2 querys on something with 60K+ rows

More:
on 4K they r the same
20K Linq is faster by about 20%+
again my machine my router speed...

my conclusion:
*Linq is better when u query at least 3-5 times and more AND were talking about 10K+ rows a query
SQL is ALWAYS better if u query once (DAAA...)
*SQL is better when u query more than once AND were talking less about 5K+ rows a query
*these numbers also depend on transportation and W/O initial query


Wednesday, April 18, 2012

DataSource a Linq(ed) DataTable example

if u ever tried to query with Linq a datatable and then assign it to a DataGridView (and other stuff i guess) then u might have noticed that the grid shows the properties of the DataRow(s).
And if you tried to select the ItemArray, again a mess.
Sooo... its so simple i laugh at myself but i must:

var query =
     from data in tblAllData.AsEnumerable()
     where data.Field<DateTime>("Start").Month == (int)cmbMonths.SelectedValue
     select data;
if (query.Count() > 0)                
    dgvMain.DataSource = query.CopyToDataTable();

TADA!

Winforms ComboBox Text & Value example

the really simple way, and goes for the rest of the winform controls
you could also put a list of any class and choose 2 properties

DataTable tblMonths = new DataTable();
tblMonths.Columns.Add(new DataColumn("Name", typeof(string)));
tblMonths.Columns.Add(new DataColumn("Value", typeof(int)));
for (int i = 1; i <= 12; i++)
{
    string month = DateTimeFormatInfo.CurrentInfo.GetMonthName(i);
    tblMonths.Rows.Add(
    new object[] { month, i });
}
cmbMonths.DataSource = tblMonths;
cmbMonths.ValueMember = "Value";

cmbMonths.DisplayMember = "Name";
cmbMonths.SelectedValue =
DateTime.Now.Month;

Tuesday, April 17, 2012

mysql Count the Distinct example

like:
ari
ari
dani
ari
I want select like this:
ari     3
dani  1
SELECT   my_column,  
COUNT(*) AS num
FROM my_table
GROUP BY  my_column
ORDER BY COUNT(*) DESC
thanks stack overflow

WinForms Bypass Cross Thread Update Error example

we can do 2 things
the 1st, not everybody loves it (and i guess that in large slns  u should avoid it) is the
CheckForIllegalCrossThreadCalls  prop:.

public Form1()
{
    InitializeComponent();
    Form1.CheckForIllegalCrossThreadCalls = false;
}
 private void button1_Click(object sender, EventArgs e)
{
     Thread t = new Thread(new ThreadStart(target));
     t.Start();
}
 private void target()
{
     this.Text = "ddddd";
}


the other way is to use a delegate:

delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
   if (this.textBox1.InvokeRequired)
   {
      SetTextCallback d = new SetTextCallback(SetText);
      this.Invoke(d, new object[] { text });
   }
   else
   {
       this.textBox1.Text = textBox1.Text + text;
   }
}
p.s. - thanks to rabi dot net and stack overflow

Sunday, April 15, 2012

Ease of WebRequest example

this is and example of a generic method to execute POST WebRequests, and in this case login into a site, don't worry, the values are fake.

the 1st part is a secondary example, how to call MakeWebRequest method itself, which is the main thing in this post.

System.Collections.Specialized; - ns for NameValueCollection
NameValueCollection parameters = new NameValueCollection();

parameters.Add("textBox1", "422");
parameters.Add("textBox2", "gensearch");
parameters.Add("textBoxUserName", "UserName");
parameters.Add("textBoxPassword", "mode matchallpartial");
string strRes = "";
string url = "http://www.mysite.com/login.aspx\jsp\php\ect.";
CookieContainer cookie = new CookieContainer();

MakeWebRequest(url, "POST", ref cookie, parameters, ref strRes);

//and strRes is our response, either html or csv or whatever the resposne is
//if you dont send any params then parameters is null and mehtod is "GET"
//if you need a page that require a pre login just resend the cookie

p.s.
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentText = strRes;
wb.Document.Write(strRes);

HTMLDocument doc = (HTMLDocument )wb.Document.DomDocument

public bool MakeWebRequest(String url, String method,
ref CookieContainer cookies, NameValueCollection parameters,
ref String strResponse)
{  HttpWebRequest request;
  HttpWebResponse response;
   request = (   HttpWebRequest)WebRequest.Create(url);
  request.AllowAutoRedirect = true;
  request.CookieContainer = cookies;
  request.Method = method;  if ((parameters != null) && (parameters.Count > 0))
  {      bool first = true;
      StringBuilder sbData = new StringBuilder();
      foreach (String key in parameters.AllKeys)
      {
        if (first)
          first = false;
        else
        sbData.Append("&");
        sbData.Append(HttpUtility.UrlEncode(key));
        sbData.Append("=");
        sbData.Append(HttpUtility.UrlEncode(parameters[key]));
      }
    if ("POST" == request.Method)
   {
      request.ContentType =          "application/x-www-form-urlencoded";
      request.ContentLength = sbData.Length;
   }   StreamWriter sw = new StreamWriter(request.GetRequestStream());
   sw.Write(sbData.ToString());
   sw.Close();
}
response = (
HttpWebResponse)request.GetResponse();
cookies = request.CookieContainer;
StreamReader sr = new StreamReader(response.GetResponseStream());
strResponse = sr.ReadToEnd();
sr.Close();
response.Close();

return true;
}
//end make web req


Paralel Events example

So you wanna have 2 events running at the same time (parallel)?
nope - they will run as a stack, we need , threads!
so typically I would recommend using the TPL library but sometimes its not exactly what you need, and sometimes you work with .Net 3.5.

If we just start new thread in WinForms we also get cross trread exception... - this is solved with delegates!

Here is my code for 2 textboxes with doubleClick event to write to a 3rd textbox, 1st textbox by an event, the other textbox by a thread.

note that the event are still in a stack although they get a different class.
the threads should work without a class but this is a pattern for "heavier" work:

public partial class Eventer : Form
{
     int id = 10;
     public Eventer()
    {
           InitializeComponent();
     }
    
    private void txtEnter_DoubleClick(object sender, EventArgs e)
    {
         cWriter cw = new cWriter(id++);
         cw.SendBack += new cWriter.BackToTextBox(cw_SendBack);
         cw.StartWriting();
     }

      private void txtStartThread_DoubleClick(object sender, EventArgs e)
     {
           object oID = id++;
           Thread t = new Thread(new ParameterizedThreadStart(StartSingleThread));
           t.Start(oID);
      }

      void StartSingleThread(object oID)
      {
            int id = (int)oID;
            cWriter cw = new cWriter(id);
            cw.SendBack += new cWriter.BackToTextBox(cw_SendBack);
            cw.StartWriting();
      }

     void cw_SendBack(string str)
     {  
            if (txtBigBox.InvokeRequired)
           {    
                 SetTextCallback d = new SetTextCallback(cw_SendBack);
                 this.Invoke(d, new object[] { str });
           }
           else
          {
                 txtBigBox.AppendText(str);
           }           
      }

     delegate void SetTextCallback(string text);
}//end class form

public class cWriter
{
       public delegate void Writer(int id);
       public event Writer StartWrite;
       public delegate void BackToTextBox(string str);
       public event BackToTextBox SendBack;
       int id;
       public cWriter(int id)
      {
            this.id = id;
      }

       public void StartWriting()
      {
            StartWrite += new Writer(cWriter_StartWrite);
            StartWrite(id);
       }

       void cWriter_StartWrite(int id)
       {
             for (int i = 0; i < 10; i++)
             {
                     SendBack(id.ToString() + " " +
                     DateTime.Now.ToLongTimeString() + "\r\n");
                     System.Threading.Thread.Sleep(300);
                     Application.DoEvents();
              }
       }
}//end cwriter

Tuesday, April 3, 2012

Ajax - the 3 simple ways example

the most easy way to do ajax, if you're developing with .Net, is to use the AjaxUpdatePanel. tp use it you must add a script manager to your page, preferred in you master page if you have one, and from there on all your standard logic and fields and whatever inside the Content Template

<asp:ScriptManager ID="ScriptManager1" runat="server" > </asp:ScriptManager>
<asp:UpdatePanel ID="uppContact" runat="server" UpdateMode="Conditional">
   <ContentTemplate>
      <!-- html tags -->
      <%-- server tags --%>
   </ContentTemplate>
</asp:UpdatePanel>
most developers don't like the UpdatePanel and for good reasons:
1 - for it to trigger you need a server control that will trigger a post back
2 - it actually do a full postback, with a full page life cycle, and a full response, only in the client if "fakes" it to feel as only whatever in the panel has changed, meaning its really heavy, and kinda lose the point of ajax, its more useful for big stuff like paging or big forms.
another option given by the .Net framework is the PageMethods, where if you develop a .Net page you can give some static methods a WebMethod attribute (System.Web.Services) and call them from the client. For that you must enable the page methods within the script manager

<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
 
 

an example for a WebMethods in the server code:

[WebMethod]
public static string GetTime(int modifier)
{
      return DateTime.Now.AddDays(modifier);
}

and in order to call it via javascript you need 2 methods, one to call it and another for the callback:

function GetTime(value){
    PageMethods.GetTime(value, OnUpdateComplete);
}


function OnUpdateComplete(result){
    alert(result);
}


the last option, and the most common one, is the original one, using jQuery

using jQuery in your page you must use a jQuery lib of any version, for example

<script src="jquery-1.9.1.min.js" ></script>

you are most welcome to use their CDN's like this

<script src="https://code.jquery.com/jquery-1.11.2.js" ></script>

here we can choose what to call, a WebMethod, some generic handler, or any api available, lets start by demonstrating how to call a WebMethod

<script type="text/javascript">
$(document).ready(function () {
    // Add the page method call as an onclick handler for the div.
    $("#MyButton").click(function () {
        $.ajax({   
            type: "POST",
            url: "Default.aspx/GetTime",
            data: "{modifier: 1}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
               // Replace the div's content with the page method's return.
               $("#Result").text(msg.d); //DO NOT FORGET .d
            }
         });
    });
});
</script>

in case you don't want to use any WebMethod, or maybe you just can't, then its really easy to create a handler for yourself. I have 2 posts, one with some explanations and the other with an example

http://bresleveloper.blogspot.co.il/2014/07/create-handler-tutorial-and-example.html
http://bresleveloper.blogspot.co.il/2013/04/jquery-ui-autocomplete-with-ajax-novice.html

from there the ajax call gets as easy as this

$.ajax({
 
url: "Handler1.ashx",
  success: function (data) {
    $("#Result").text(msg);
  }
})
 


HAVE A NICE AJAX!